BfModule.cpp 934 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include "BfConstResolver.h"
  12. #include "BfMangler.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/StackHelper.h"
  16. #include "BfSourceClassifier.h"
  17. #include "BfAutoComplete.h"
  18. #include "BfDemangler.h"
  19. #include "BfResolvePass.h"
  20. #include "BfFixits.h"
  21. #include "BfIRCodeGen.h"
  22. #include "BfDefBuilder.h"
  23. #include "BfDeferEvalChecker.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #include <fcntl.h>
  27. #include <time.h>
  28. #pragma warning (disable:4267)
  29. //#include "llvm/Support/Compiler.h"
  30. //#include "llvm/IR/IRBuilder.h"
  31. //#include "llvm/IR/Type.h"
  32. #include "llvm/IR/DIBuilder.h"
  33. //#include "llvm/IR/DebugInfo.h"
  34. //#include "llvm/IR/Argument.h"
  35. //#include "llvm/IR/Constants.h"
  36. #pragma warning(pop)
  37. //////////////////////////////////////////////////////////////////////////
  38. static bool gDebugStuff = false;
  39. USING_NS_BF;
  40. //////////////////////////////////////////////////////////////////////////
  41. void BfLocalVariable::Init()
  42. {
  43. if (mResolvedType->IsValuelessType())
  44. {
  45. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  46. return;
  47. }
  48. if (mAssignedKind != BfLocalVarAssignKind_None)
  49. return;
  50. bool isStruct = mResolvedType->IsStruct();
  51. if (mResolvedType->IsRef())
  52. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  53. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  54. {
  55. auto resolvedTypeRef = mResolvedType;
  56. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  57. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  58. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  59. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  60. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  61. {
  62. // Base ctor is responsible for initializing its own fields
  63. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  64. }
  65. if (mUnassignedFieldFlags == 0)
  66. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  67. }
  68. else
  69. {
  70. mUnassignedFieldFlags = 1;
  71. }
  72. }
  73. BfLocalMethod::~BfLocalMethod()
  74. {
  75. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  76. if (mMethodDeclaration != NULL)
  77. {
  78. mSource->mRefCount--;
  79. BF_ASSERT(mSource->mRefCount >= 0);
  80. }
  81. delete mMethodInstanceGroup;
  82. delete mMethodDef;
  83. }
  84. void BfLocalMethod::Dispose()
  85. {
  86. if (mMethodInstanceGroup == NULL)
  87. return;
  88. if (mMethodInstanceGroup->mDefault != NULL)
  89. mMethodInstanceGroup->mDefault->Dispose();
  90. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  91. {
  92. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  93. kv.mValue->Dispose();
  94. }
  95. }
  96. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  97. {
  98. mIsChained = doChain;
  99. if (outerLocalAssignData == NULL)
  100. return;
  101. mChainedAssignData = outerLocalAssignData;
  102. if (!doChain)
  103. {
  104. outerLocalAssignData->BreakExtendChain();
  105. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  106. }
  107. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  108. }
  109. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  110. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  111. // if ((GetValue(out a)) && (GetValue(out b)) {}
  112. void BfDeferredLocalAssignData::BreakExtendChain()
  113. {
  114. if (!mIsChained)
  115. return;
  116. mIsChained = false;
  117. if (mChainedAssignData == NULL)
  118. return;
  119. mChainedAssignData->BreakExtendChain();
  120. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  121. }
  122. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  123. {
  124. BreakExtendChain();
  125. if (otherLocalAssignData.mLeftBlockUncond)
  126. {
  127. // Intersection of self and infinity is self
  128. }
  129. else if (mLeftBlockUncond)
  130. {
  131. // Intersection of infinity and other is other
  132. mAssignedLocals = otherLocalAssignData.mAssignedLocals;
  133. }
  134. else
  135. {
  136. for (int i = 0; i < (int)mAssignedLocals.size(); )
  137. {
  138. auto& local = mAssignedLocals[i];
  139. bool wantRemove = true;
  140. bool foundOtherFields = false;
  141. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  142. {
  143. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  144. {
  145. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  146. {
  147. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  148. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  149. wantRemove = false;
  150. }
  151. else
  152. foundOtherFields = true;
  153. }
  154. }
  155. if ((wantRemove) && (foundOtherFields))
  156. {
  157. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  158. {
  159. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  160. {
  161. mAssignedLocals.Add(otherLocalAssignData);
  162. }
  163. }
  164. }
  165. if (wantRemove)
  166. {
  167. mAssignedLocals.RemoveAt(i);
  168. }
  169. else
  170. i++;
  171. }
  172. }
  173. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  174. mLeftBlockUncond = mLeftBlockUncond && otherLocalAssignData.mLeftBlockUncond;
  175. }
  176. void BfDeferredLocalAssignData::Validate() const
  177. {
  178. for (auto var : mAssignedLocals)
  179. {
  180. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  181. }
  182. }
  183. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  184. {
  185. BreakExtendChain();
  186. Validate();
  187. otherLocalAssignData.Validate();
  188. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  189. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  190. {
  191. if (!mAssignedLocals.Contains(*otherItr))
  192. mAssignedLocals.push_back(*otherItr);
  193. ++otherItr;
  194. }
  195. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  196. mLeftBlockUncond = mLeftBlockUncond || otherLocalAssignData.mLeftBlockUncond;
  197. }
  198. BfMethodState::~BfMethodState()
  199. {
  200. BF_ASSERT(mPendingNullConditional == NULL);
  201. if (mPrevMethodState != NULL)
  202. {
  203. BF_ASSERT(mCurAccessId == 1);
  204. BF_ASSERT(mCurLocalVarId <= 0);
  205. }
  206. for (auto local : mLocals)
  207. {
  208. if (local->mIsBumpAlloc)
  209. local->~BfLocalVariable();
  210. else
  211. delete local;
  212. }
  213. for (auto& kv : mLambdaCache)
  214. delete kv.mValue;
  215. }
  216. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  217. {
  218. auto checkMethodState = this;
  219. while (checkMethodState != NULL)
  220. {
  221. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  222. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  223. return checkMethodState;
  224. checkMethodState = checkMethodState->mPrevMethodState;
  225. }
  226. BF_FATAL("Failed to find method state for localvar");
  227. return NULL;
  228. }
  229. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  230. {
  231. auto localVarMethodState = GetMethodStateForLocal(localVar);
  232. if (localVarMethodState != this)
  233. {
  234. return;
  235. }
  236. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  237. {
  238. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  239. // 'a' is always defined, but 'b' isn't:
  240. // if (Check(out a) || Check(out b)) { } int z = a;
  241. auto deferredLocalAssignData = mDeferredLocalAssignData;
  242. if ((deferredLocalAssignData != NULL) &&
  243. (deferredLocalAssignData->mIsIfCondition) &&
  244. (!deferredLocalAssignData->mIfMayBeSkipped))
  245. {
  246. ifDeferredLocalAssignData = deferredLocalAssignData;
  247. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  248. }
  249. while ((deferredLocalAssignData != NULL) &&
  250. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  251. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  252. if (assignKind == BfLocalVarAssignKind_None)
  253. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  254. if (localVar->mAssignedKind >= assignKind)
  255. {
  256. // Leave it alone
  257. }
  258. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  259. {
  260. if (fieldIdx >= 0)
  261. {
  262. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  263. if (localVar->mResolvedType->IsUnion())
  264. {
  265. // We need more 'smarts' to determine assignment of unions
  266. localVar->mUnassignedFieldFlags = 0;
  267. }
  268. if (localVar->mUnassignedFieldFlags == 0)
  269. {
  270. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  271. localVar->mAssignedKind = assignKind;
  272. }
  273. }
  274. else
  275. {
  276. localVar->mAssignedKind = assignKind;
  277. }
  278. }
  279. else
  280. {
  281. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  282. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  283. if (!deferredLocalAssignData->Contains(defineVal))
  284. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  285. if (ifDeferredLocalAssignData != NULL)
  286. {
  287. if (!ifDeferredLocalAssignData->Contains(defineVal))
  288. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  289. }
  290. }
  291. }
  292. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  293. }
  294. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  295. {
  296. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  297. if (deferredLocalAssignData.mLeftBlockUncond)
  298. {
  299. for (int localIdx = 0; localIdx < (int)mLocals.size(); localIdx++)
  300. {
  301. auto localDef = mLocals[localIdx];
  302. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  303. {
  304. bool hadAssignment = false;
  305. if (mDeferredLocalAssignData != NULL)
  306. {
  307. for (auto& entry : mDeferredLocalAssignData->mAssignedLocals)
  308. if (entry.mLocalVar == localDef)
  309. hadAssignment = true;
  310. }
  311. if (!hadAssignment)
  312. {
  313. LocalDefined(localDef);
  314. }
  315. }
  316. }
  317. }
  318. else
  319. {
  320. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  321. {
  322. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  323. }
  324. }
  325. }
  326. void BfMethodState::Reset()
  327. {
  328. mHeadScope.mDeferredCallEntries.DeleteAll();
  329. }
  330. //////////////////////////////////////////////////////////////////////////
  331. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  332. {
  333. Entry* entry = NULL;
  334. if (mEntries.TryAdd(id, NULL, &entry))
  335. {
  336. entry->mInterfaceEntry = interfaceEntry;
  337. entry->mMethodIdx = methodIdx;
  338. }
  339. if (!entry->mCandidates.Contains(candidateA))
  340. entry->mCandidates.push_back(candidateA);
  341. if (!entry->mCandidates.Contains(candidateB))
  342. entry->mCandidates.push_back(candidateB);
  343. }
  344. void BfAmbiguityContext::Remove(int id)
  345. {
  346. mEntries.Remove(id);
  347. }
  348. void BfAmbiguityContext::Finish()
  349. {
  350. for (auto& entryPair : mEntries)
  351. {
  352. int id = entryPair.mKey;
  353. auto entry = &entryPair.mValue;
  354. if (id >= 0)
  355. {
  356. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  357. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  358. if (error != NULL)
  359. {
  360. for (auto candidate : entry->mCandidates)
  361. {
  362. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  363. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  364. }
  365. }
  366. }
  367. else
  368. {
  369. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  370. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  371. if (error != NULL)
  372. {
  373. for (auto candidate : entry->mCandidates)
  374. {
  375. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  376. mModule->MethodToString(candidate, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType)).c_str()), candidate->mMethodDef->GetRefNode());
  377. }
  378. }
  379. }
  380. }
  381. mEntries.Clear();
  382. }
  383. //////////////////////////////////////////////////////////////////////////
  384. class HasAppendAllocVisitor : BfElementVisitor
  385. {
  386. public:
  387. bool mHas;
  388. public:
  389. HasAppendAllocVisitor()
  390. {
  391. mHas = false;
  392. }
  393. void Visit(BfObjectCreateExpression* objCreateExpr)
  394. {
  395. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  396. {
  397. if (newToken->GetToken() == BfToken_Append)
  398. {
  399. mHas = true;
  400. }
  401. }
  402. }
  403. bool HasAppendAlloc(BfAstNode* node)
  404. {
  405. mHas = false;
  406. VisitChild(node);
  407. return mHas;
  408. }
  409. };
  410. class AppendAllocVisitor : public BfStructuralVisitor
  411. {
  412. public:
  413. BfModule* mModule;
  414. HasAppendAllocVisitor mHasAppendAllocVisitor;
  415. BfTypedValue mConstAccum;
  416. bool mFailed;
  417. bool mIsFirstConstPass;
  418. bool mHasAppendWantMark;
  419. int mCurAppendAlign;
  420. public:
  421. AppendAllocVisitor()
  422. {
  423. mFailed = false;
  424. mIsFirstConstPass = false;
  425. mHasAppendWantMark = false;
  426. mCurAppendAlign = 1;
  427. }
  428. void EmitAppendAlign(int align, int sizeMultiple = 0)
  429. {
  430. if (align <= 1)
  431. return;
  432. if (mIsFirstConstPass)
  433. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  434. if (sizeMultiple == 0)
  435. sizeMultiple = align;
  436. if (mCurAppendAlign == 0)
  437. mCurAppendAlign = sizeMultiple;
  438. else
  439. {
  440. if (sizeMultiple % align == 0)
  441. mCurAppendAlign = align;
  442. else
  443. mCurAppendAlign = sizeMultiple % align;
  444. }
  445. BF_ASSERT(mCurAppendAlign > 0);
  446. if (mConstAccum)
  447. {
  448. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  449. if (constant != NULL)
  450. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  451. else
  452. BF_ASSERT(mIsFirstConstPass);
  453. return;
  454. }
  455. mModule->EmitAppendAlign(align, sizeMultiple);
  456. }
  457. void Visit(BfAstNode* astNode) override
  458. {
  459. mModule->VisitChild(astNode);
  460. }
  461. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  462. {
  463. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  464. {
  465. if (newToken->GetToken() == BfToken_Append)
  466. {
  467. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  468. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  469. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  470. BfArrayType* arrayType = NULL;
  471. bool isArrayAlloc = false;
  472. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  473. SizedArray<BfIRValue, 2> dimLengthVals;
  474. BfType* origResolvedTypeRef = NULL;
  475. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  476. {
  477. if (variableDecl != NULL)
  478. {
  479. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  480. if (origResolvedTypeRef->IsObject())
  481. {
  482. if (origResolvedTypeRef->IsArray())
  483. {
  484. arrayType = (BfArrayType*)origResolvedTypeRef;
  485. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  486. isArrayAlloc = true;
  487. }
  488. }
  489. else if (origResolvedTypeRef->IsPointer())
  490. {
  491. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  492. }
  493. }
  494. }
  495. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  496. {
  497. isArrayAlloc = true;
  498. bool handled = false;
  499. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  500. {
  501. if (variableDecl->mTypeRef != NULL)
  502. {
  503. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  504. if (variableType != NULL)
  505. {
  506. if (variableType->IsArray())
  507. origResolvedTypeRef = variableType->GetUnderlyingType();
  508. }
  509. handled = true;
  510. }
  511. }
  512. if (!handled)
  513. {
  514. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration);
  515. }
  516. if (origResolvedTypeRef == NULL)
  517. {
  518. mModule->AssertErrorState();
  519. return;
  520. }
  521. int dimensions = 1;
  522. if (arrayTypeRef->mParams.size() != 0)
  523. {
  524. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  525. for (auto arg : arrayTypeRef->mParams)
  526. {
  527. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  528. {
  529. if (tokenNode->GetToken() == BfToken_Comma)
  530. {
  531. if (isRawArrayAlloc)
  532. {
  533. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  534. continue;
  535. }
  536. dimensions++;
  537. continue;
  538. }
  539. }
  540. auto expr = BfNodeDynCast<BfExpression>(arg);
  541. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  542. {
  543. mModule->CreateValueFromExpression(expr, intType);
  544. continue;
  545. }
  546. BfTypedValue dimLength;
  547. if (expr == NULL)
  548. {
  549. // Not specified
  550. dimLengthVals.push_back(BfIRValue());
  551. continue;
  552. }
  553. if (arg != NULL)
  554. dimLength = mModule->CreateValueFromExpression(expr, intType);
  555. if (!dimLength)
  556. {
  557. dimLength = mModule->GetDefaultTypedValue(intType);
  558. }
  559. dimLengthVals.push_back(dimLength.mValue);
  560. }
  561. }
  562. if (!isRawArrayAlloc)
  563. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  564. }
  565. if (origResolvedTypeRef == NULL)
  566. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  567. if (origResolvedTypeRef == NULL)
  568. {
  569. mModule->AssertErrorState();
  570. return;
  571. }
  572. if (origResolvedTypeRef->WantsGCMarking())
  573. mHasAppendWantMark = true;
  574. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  575. auto resolvedTypeRef = origResolvedTypeRef;
  576. auto resultType = resolvedTypeRef;
  577. BfIRValue sizeValue;
  578. int curAlign = 0;
  579. if (isArrayAlloc)
  580. {
  581. int dimensions = 1;
  582. if (arrayType != NULL)
  583. dimensions = arrayType->mDimensions;
  584. bool sizeFailed = false;
  585. //
  586. {
  587. BfAstNode* initNode = objCreateExpr;
  588. for (int dim = 0; dim < dimensions; dim++)
  589. {
  590. BfAstNode* nextInitNode = NULL;
  591. int dimSize = -1;
  592. if (initNode == objCreateExpr)
  593. {
  594. dimSize = objCreateExpr->mArguments.size();
  595. if (!objCreateExpr->mArguments.IsEmpty())
  596. nextInitNode = objCreateExpr->mArguments[0];
  597. }
  598. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  599. {
  600. dimSize = (int)tupleNode->mCommas.size() + 1;
  601. }
  602. if (dimSize >= 0)
  603. {
  604. if (dim >= dimLengthVals.size())
  605. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  606. }
  607. else
  608. {
  609. sizeFailed = true;
  610. }
  611. }
  612. }
  613. BfIRValue allocCount;
  614. if (!sizeFailed)
  615. {
  616. if (!dimLengthVals.IsEmpty())
  617. {
  618. allocCount = dimLengthVals[0];
  619. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  620. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  621. }
  622. }
  623. if (!allocCount)
  624. {
  625. mFailed = true;
  626. if (!mIsFirstConstPass)
  627. {
  628. if (!mConstAccum)
  629. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  630. return;
  631. }
  632. }
  633. mModule->PopulateType(resultType, resultType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  634. if (isRawArrayAlloc)
  635. {
  636. curAlign = resultType->mAlign;
  637. EmitAppendAlign(resultType->mAlign);
  638. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  639. }
  640. else
  641. {
  642. if (arrayType == NULL)
  643. arrayType = mModule->CreateArrayType(resultType, 1);
  644. // Array is a special case where the total size isn't aligned with mAlign
  645. // since we add arbitrary elements to the end without padding the end to align
  646. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  647. curAlign = arrayType->mAlign;
  648. auto firstElementField = &arrayType->mFieldInstances.back();
  649. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  650. sizeValue = mModule->GetConstValue(arrayClassSize);
  651. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  652. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  653. }
  654. }
  655. else
  656. {
  657. auto typeInst = resultType->ToTypeInstance();
  658. if (typeInst != NULL)
  659. {
  660. curAlign = typeInst->mInstAlign;
  661. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  662. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  663. }
  664. else
  665. {
  666. curAlign = resultType->mAlign;
  667. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  668. sizeValue = mModule->GetConstValue(resultType->mSize);
  669. }
  670. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  671. BfExprEvaluator exprEvaluator(mModule);
  672. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  673. BfFunctionBindResult bindResult;
  674. bindResult.mWantsArgs = true;
  675. exprEvaluator.mFunctionBindResult = &bindResult;
  676. SizedArray<BfExpression*, 8> copiedArgs;
  677. for (BfExpression* arg : objCreateExpr->mArguments)
  678. copiedArgs.push_back(arg);
  679. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  680. BfResolvedArgs argValues(&sizedArgExprs);
  681. if (typeInst != NULL)
  682. {
  683. exprEvaluator.ResolveArgValues(argValues);
  684. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  685. }
  686. exprEvaluator.mFunctionBindResult = NULL;
  687. if (bindResult.mMethodInstance != NULL)
  688. {
  689. if (bindResult.mMethodInstance->mMethodDef->HasAppend())
  690. {
  691. auto calcAppendArgs = bindResult.mIRArgs;
  692. BF_ASSERT(calcAppendArgs[0].IsFake());
  693. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  694. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  695. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  696. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  697. {
  698. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  699. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  700. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  701. }
  702. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  703. if ((!subDependSize) && (!mConstAccum))
  704. {
  705. BF_ASSERT(calcAppendMethodModule.mFunc);
  706. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  707. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  708. }
  709. if (subDependSize)
  710. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  711. else
  712. mFailed = true;
  713. }
  714. }
  715. }
  716. if (sizeValue)
  717. {
  718. if (mConstAccum)
  719. {
  720. if (!sizeValue.IsConst())
  721. {
  722. mFailed = true;
  723. if (!mIsFirstConstPass)
  724. return;
  725. }
  726. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  727. }
  728. else
  729. {
  730. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  731. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  732. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  733. }
  734. }
  735. }
  736. }
  737. }
  738. void Visit(BfObjectCreateExpression* objCreateExpr) override
  739. {
  740. DoObjectCreate(objCreateExpr, NULL);
  741. }
  742. void Visit(BfVariableDeclaration* varDecl) override
  743. {
  744. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  745. {
  746. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  747. DoObjectCreate(objectCreateExpr, varDecl);
  748. else
  749. VisitChild(varDecl->mInitializer);
  750. if (varDecl->mNameNode != NULL)
  751. {
  752. BfLocalVariable* localDef = new BfLocalVariable();
  753. localDef->mName = varDecl->mNameNode->ToString();
  754. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  755. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  756. localDef->mIsReadOnly = true;
  757. localDef->mParamFailed = true;
  758. localDef->mReadFromId = 0;
  759. mModule->AddLocalVariableDef(localDef);
  760. }
  761. }
  762. else
  763. {
  764. mModule->Visit(varDecl);
  765. }
  766. }
  767. void Visit(BfExpressionStatement* exprStatement) override
  768. {
  769. VisitChild(exprStatement->mExpression);
  770. }
  771. // void Visit(BfIfStatement* ifStmt) override
  772. // {
  773. // mModule->DoIfStatement(ifStmt,
  774. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  775. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  776. // }
  777. void Visit(BfBlock* block) override
  778. {
  779. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  780. return;
  781. int appendAllocIdx = -1;
  782. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  783. {
  784. auto child = block->mChildArr.mVals[childIdx];
  785. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  786. {
  787. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  788. {
  789. auto emitChild = block->mChildArr.mVals[emitIdx];
  790. mModule->UpdateSrcPos(emitChild);
  791. VisitChild(emitChild);
  792. if ((mFailed) && (!mIsFirstConstPass))
  793. break;
  794. }
  795. break;
  796. }
  797. }
  798. }
  799. };
  800. //////////////////////////////////////////////////////////////////////////
  801. BfModule* gLastCreatedModule = NULL;
  802. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  803. {
  804. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  805. gLastCreatedModule = this;
  806. mContext = context;
  807. mModuleName = moduleName;
  808. if (!moduleName.empty())
  809. {
  810. StringT<256> upperModuleName = moduleName;
  811. MakeUpper(upperModuleName);
  812. mContext->mUsedModuleNames.Add(upperModuleName);
  813. }
  814. mAddedToCount = false;
  815. mParentModule = NULL;
  816. mNextAltModule = NULL;
  817. mBfIRBuilder = NULL;
  818. mWantsIRIgnoreWrites = false;
  819. mModuleOptions = NULL;
  820. mLastUsedRevision = -1;
  821. mUsedSlotCount = -1;
  822. mIsReified = true;
  823. mGeneratesCode = true;
  824. mReifyQueued = false;
  825. mIsSpecialModule = false;
  826. mIsComptimeModule = false;
  827. mIsScratchModule = false;
  828. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  829. mHadBuildError = false;
  830. mHadBuildWarning = false;
  831. mIgnoreErrors = false;
  832. mHadIgnoredError = false;
  833. mIgnoreWarnings = false;
  834. mReportErrors = true;
  835. mIsInsideAutoComplete = false;
  836. mIsDeleting = false;
  837. mSkipInnerLookup = false;
  838. mIsHotModule = false;
  839. mSetIllegalSrcPosition = false;
  840. mNoResolveGenericParams = false;
  841. mWroteToLib = false;
  842. mContext = context;
  843. mCompiler = context->mCompiler;
  844. mSystem = mCompiler->mSystem;
  845. mProject = NULL;
  846. mCurMethodState = NULL;
  847. mAttributeState = NULL;
  848. mCurLocalMethodId = 0;
  849. mParentNodeEntry = NULL;
  850. mRevision = -1;
  851. mRebuildIdx = 0;
  852. mLastModuleWrittenRevision = 0;
  853. mIsModuleMutable = false;
  854. mExtensionCount = 0;
  855. mIncompleteMethodCount = 0;
  856. mOnDemandMethodCount = 0;
  857. mHasGenericMethods = false;
  858. mCurMethodInstance = NULL;
  859. mCurTypeInstance = NULL;
  860. mAwaitingInitFinish = false;
  861. mAwaitingFinish = false;
  862. mHasFullDebugInfo = false;
  863. mHadHotObjectWrites = false;
  864. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  865. mBuiltInFuncs[i] = BfIRFunction();
  866. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  867. }
  868. void BfReportMemory();
  869. BfModule::~BfModule()
  870. {
  871. mRevision = -2;
  872. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  873. if (!mIsDeleting)
  874. RemoveModuleData();
  875. }
  876. void BfModule::RemoveModuleData()
  877. {
  878. BF_ASSERT(!mIsDeleting);
  879. if (!mModuleName.empty())
  880. {
  881. // Note: module names not necessarily unique
  882. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  883. }
  884. CleanupFileInstances();
  885. delete mBfIRBuilder;
  886. mBfIRBuilder = NULL;
  887. //delete mCpu;
  888. for (auto prevModule : mPrevIRBuilders)
  889. delete prevModule;
  890. mPrevIRBuilders.Clear();
  891. for (auto& pairVal : mDeferredMethodCallData)
  892. delete pairVal.mValue;
  893. mDeferredMethodCallData.Clear();
  894. mDeferredMethodIds.Clear();
  895. for (auto& specModulePair : mSpecializedMethodModules)
  896. delete specModulePair.mValue;
  897. mSpecializedMethodModules.Clear();
  898. if (mNextAltModule != NULL)
  899. delete mNextAltModule;
  900. mNextAltModule = NULL;
  901. if (mModuleOptions != NULL)
  902. delete mModuleOptions;
  903. mModuleOptions = NULL;
  904. BfReportMemory();
  905. }
  906. void BfModule::Init(bool isFullRebuild)
  907. {
  908. mContext->mFinishedModuleWorkList.Remove(this);
  909. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  910. BF_ASSERT(mIsReified);
  911. if (!mIsScratchModule)
  912. {
  913. mCompiler->mStats.mModulesStarted++;
  914. if (mIsReified)
  915. mCompiler->mStats.mReifiedModuleCount++;
  916. mAddedToCount = true;
  917. }
  918. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  919. mFuncReferences.Clear();
  920. mClassVDataRefs.Clear();
  921. mClassVDataExtRefs.Clear();
  922. //mTypeDataRefs.Clear();
  923. mDbgRawAllocDataRefs.Clear();
  924. CleanupFileInstances();
  925. mStaticFieldRefs.Clear();
  926. //mInterfaceSlotRefs.Clear();
  927. // If we are just doing an extension then the ownede types aren't rebuilt.
  928. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  929. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  930. if (isFullRebuild)
  931. mRevision = mCompiler->mRevision;
  932. BF_ASSERT(mCurTypeInstance == NULL);
  933. mIsModuleMutable = true;
  934. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  935. if (!mIsComptimeModule)
  936. {
  937. #ifdef _DEBUG
  938. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  939. #else
  940. EnsureIRBuilder(false);
  941. #endif
  942. }
  943. mCurMethodState = NULL;
  944. mAwaitingInitFinish = true;
  945. mOnDemandMethodCount = 0;
  946. mAwaitingFinish = false;
  947. mHasForceLinkMarker = false;
  948. mUsedSlotCount = -1;
  949. }
  950. bool BfModule::WantsFinishModule()
  951. {
  952. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  953. }
  954. bool BfModule::IsHotCompile()
  955. {
  956. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  957. }
  958. void BfModule::FinishInit()
  959. {
  960. BfLogSysM("FinishInit %@ %s\n", this, mModuleName.c_str());
  961. BF_ASSERT(mAwaitingInitFinish);
  962. auto moduleOptions = GetModuleOptions();
  963. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  964. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  965. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  966. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  967. {
  968. // Og+ requires debug info
  969. moduleOptions.mEmitDebugInfo = 1;
  970. }
  971. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  972. if (mIsComptimeModule)
  973. mHasFullDebugInfo = true;
  974. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  975. (mIsComptimeModule))
  976. {
  977. mBfIRBuilder->DbgInit();
  978. }
  979. else
  980. mHasFullDebugInfo = false;
  981. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  982. ((moduleOptions.mEmitDebugInfo != 0)))
  983. {
  984. if (mCompiler->mOptions.IsCodeView())
  985. {
  986. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  987. }
  988. else
  989. {
  990. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  991. }
  992. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  993. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  994. }
  995. mAwaitingInitFinish = false;
  996. }
  997. void BfModule::CalcGeneratesCode()
  998. {
  999. if ((!mIsReified) || (mIsScratchModule))
  1000. {
  1001. mGeneratesCode = false;
  1002. return;
  1003. }
  1004. mGeneratesCode = false;
  1005. for (auto typeInst : mOwnedTypeInstances)
  1006. if (!typeInst->IsInterface())
  1007. mGeneratesCode = true;
  1008. }
  1009. void BfModule::ReifyModule()
  1010. {
  1011. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1012. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  1013. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1014. mIsReified = true;
  1015. CalcGeneratesCode();
  1016. mReifyQueued = false;
  1017. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  1018. mCompiler->mStats.mModulesReified++;
  1019. }
  1020. void BfModule::UnreifyModule()
  1021. {
  1022. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  1023. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  1024. mIsReified = false;
  1025. CalcGeneratesCode();
  1026. mReifyQueued = false;
  1027. StartNewRevision(RebuildKind_None, true);
  1028. mCompiler->mStats.mModulesUnreified++;
  1029. }
  1030. void BfModule::CleanupFileInstances()
  1031. {
  1032. for (auto& itr : mNamedFileInstanceMap)
  1033. {
  1034. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  1035. delete itr.mValue;
  1036. }
  1037. mCurFilePosition.mFileInstance = NULL;//
  1038. mFileInstanceMap.Clear();
  1039. mNamedFileInstanceMap.Clear();
  1040. }
  1041. void BfModule::Cleanup()
  1042. {
  1043. CleanupFileInstances();
  1044. }
  1045. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  1046. {
  1047. if (HasCompiledOutput())
  1048. {
  1049. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  1050. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  1051. {
  1052. StartExtension();
  1053. }
  1054. }
  1055. else
  1056. {
  1057. EnsureIRBuilder();
  1058. }
  1059. }
  1060. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  1061. {
  1062. if (mIsScratchModule)
  1063. {
  1064. mBfIRBuilder->mIgnoreWrites = true;
  1065. BF_ASSERT(!dbgVerifyCodeGen);
  1066. }
  1067. #ifdef _DEBUG
  1068. if (mCompiler->mIsResolveOnly)
  1069. {
  1070. // For "deep" verification testing
  1071. /*if (!mIsSpecialModule)
  1072. dbgVerifyCodeGen = true;*/
  1073. // We only want to turn this off on smaller builds for testing
  1074. mBfIRBuilder->mIgnoreWrites = true;
  1075. if (dbgVerifyCodeGen)
  1076. mBfIRBuilder->mIgnoreWrites = false;
  1077. if (!mBfIRBuilder->mIgnoreWrites)
  1078. {
  1079. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1080. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1081. }
  1082. }
  1083. else if (!mGeneratesCode)
  1084. {
  1085. mBfIRBuilder->mIgnoreWrites = true;
  1086. }
  1087. else
  1088. {
  1089. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1090. // code as we walk the AST
  1091. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1092. if (
  1093. (mModuleName == "-")
  1094. //|| (mModuleName == "")
  1095. //|| (mModuleName == "Tests_FuncRefs")
  1096. )
  1097. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1098. // Just for testing!
  1099. //mBfIRBuilder->mIgnoreWrites = true;
  1100. }
  1101. #else
  1102. if (mCompiler->mIsResolveOnly)
  1103. {
  1104. // Always ignore writes in resolveOnly for release builds
  1105. mBfIRBuilder->mIgnoreWrites = true;
  1106. }
  1107. else
  1108. {
  1109. // Just for memory testing! This breaks everything.
  1110. //mBfIRBuilder->mIgnoreWrites = true;
  1111. // For "deep" verification testing
  1112. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1113. }
  1114. #endif
  1115. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1116. }
  1117. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1118. {
  1119. BF_ASSERT(!mIsDeleting);
  1120. if (mBfIRBuilder == NULL)
  1121. {
  1122. if ((!mIsScratchModule) && (!mAddedToCount))
  1123. {
  1124. mCompiler->mStats.mModulesStarted++;
  1125. mAddedToCount = true;
  1126. }
  1127. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1128. /*if (mCompiler->mIsResolveOnly)
  1129. BF_ASSERT(mIsResolveOnly);*/
  1130. mBfIRBuilder = new BfIRBuilder(this);
  1131. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1132. SetupIRBuilder(dbgVerifyCodeGen);
  1133. }
  1134. }
  1135. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1136. {
  1137. String name = "FORCELINKMOD_" + module->mModuleName;
  1138. if (outName != NULL)
  1139. *outName = name;
  1140. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1141. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1142. }
  1143. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1144. {
  1145. BP_ZONE("BfModule::StartNewRevision");
  1146. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1147. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1148. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1149. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1150. {
  1151. // Cleaning up local methods may cause some necessary NewRevisions
  1152. force = true;
  1153. }
  1154. // Already on new revision?
  1155. if ((mRevision == mCompiler->mRevision) && (!force))
  1156. return;
  1157. mHadBuildError = false;
  1158. mHadBuildWarning = false;
  1159. mExtensionCount = 0;
  1160. mRevision = mCompiler->mRevision;
  1161. mRebuildIdx++;
  1162. ClearModuleData(!force);
  1163. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1164. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1165. {
  1166. mStringPoolRefs.Clear();
  1167. mUnreifiedStringPoolRefs.Clear();
  1168. }
  1169. mDllImportEntries.Clear();
  1170. mImportFileNames.Clear();
  1171. for (auto& pairVal : mDeferredMethodCallData)
  1172. delete pairVal.mValue;
  1173. mDeferredMethodCallData.Clear();
  1174. mDeferredMethodIds.Clear();
  1175. mModuleRefs.Clear();
  1176. mOutFileNames.Clear();
  1177. mTypeDataRefs.Clear();
  1178. mInterfaceSlotRefs.Clear();
  1179. if (rebuildKind == BfModule::RebuildKind_None)
  1180. {
  1181. for (auto& specPair : mSpecializedMethodModules)
  1182. {
  1183. auto specModule = specPair.mValue;
  1184. if (specModule->mIsReified != mIsReified)
  1185. {
  1186. if (mIsReified)
  1187. specModule->ReifyModule();
  1188. else
  1189. specModule->UnreifyModule();
  1190. }
  1191. }
  1192. }
  1193. else
  1194. {
  1195. for (auto& specPair : mSpecializedMethodModules)
  1196. {
  1197. auto specModule = specPair.mValue;
  1198. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1199. // This module is no longer needed
  1200. specModule->RemoveModuleData();
  1201. specModule->mIsDeleting = true;
  1202. mContext->mDeletingModules.Add(specModule);
  1203. }
  1204. }
  1205. mSpecializedMethodModules.Clear();
  1206. delete mNextAltModule;
  1207. mNextAltModule = NULL;
  1208. BF_ASSERT(mModuleOptions == NULL);
  1209. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1210. bool needsTypePopulated = false;
  1211. int oldOnDemandCount = 0;
  1212. // We don't have to rebuild types in the unspecialized module because there is no
  1213. // data that's needed -- their method instances are all NULL and the module
  1214. // doesn't get included in the build
  1215. if (this != mContext->mScratchModule)
  1216. {
  1217. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1218. {
  1219. auto typeInst = mOwnedTypeInstances[typeIdx];
  1220. if (!typeInst->IsDeleting())
  1221. {
  1222. typeInst->mIsReified = mIsReified;
  1223. if (rebuildKind != BfModule::RebuildKind_None)
  1224. {
  1225. if (typeInst->IsOnDemand())
  1226. {
  1227. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1228. if (rebuildKind == BfModule::RebuildKind_All)
  1229. mContext->DeleteType(typeInst);
  1230. else
  1231. {
  1232. RebuildMethods(typeInst);
  1233. }
  1234. }
  1235. else
  1236. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1237. mContext->RebuildType(typeInst, false, false, true);
  1238. //mContext->RebuildType(typeInst, false, false, false);
  1239. }
  1240. else
  1241. {
  1242. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1243. {
  1244. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1245. methodInstance->mDeclModule = this;
  1246. };
  1247. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1248. {
  1249. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1250. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1251. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1252. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1253. {
  1254. oldOnDemandCount++;
  1255. }
  1256. _HandleMethod(methodGroup.mDefault);
  1257. if (methodGroup.mMethodSpecializationMap != NULL)
  1258. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1259. _HandleMethod(kv.mValue);
  1260. }
  1261. }
  1262. if (typeInst->IsDeleting())
  1263. typeIdx--;
  1264. }
  1265. }
  1266. }
  1267. if (!mIsDeleting)
  1268. Init();
  1269. mOnDemandMethodCount += oldOnDemandCount;
  1270. VerifyOnDemandMethods();
  1271. }
  1272. void BfModule::StartExtension()
  1273. {
  1274. BF_ASSERT(!mIsModuleMutable);
  1275. BfLogSysM("Extension started of module %p\n", this);
  1276. mExtensionCount++;
  1277. if (mBfIRBuilder != NULL)
  1278. mPrevIRBuilders.push_back(mBfIRBuilder);
  1279. mBfIRBuilder = NULL;
  1280. mWantsIRIgnoreWrites = false;
  1281. mFuncReferences.Clear();
  1282. mClassVDataRefs.Clear();
  1283. mClassVDataExtRefs.Clear();
  1284. for (auto& kv : mTypeDataRefs)
  1285. kv.mValue = BfIRValue();
  1286. mDbgRawAllocDataRefs.Clear();
  1287. mStringCharPtrPool.Clear();
  1288. mStringObjectPool.Clear();
  1289. mStaticFieldRefs.Clear();
  1290. for (auto& kv : mInterfaceSlotRefs)
  1291. kv.mValue = BfIRValue();
  1292. for (auto& pairVal : mDeferredMethodCallData)
  1293. delete pairVal.mValue;
  1294. mDeferredMethodCallData.Clear();
  1295. mDeferredMethodIds.Clear();
  1296. DisownMethods();
  1297. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1298. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1299. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1300. Init(false);
  1301. if (!wasAwaitingInitFinish)
  1302. FinishInit();
  1303. mOnDemandMethodCount = prevOnDemandMethodCount;
  1304. }
  1305. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1306. {
  1307. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1308. BfIRValue vDataValue;
  1309. if (hasObjectDebugFlags)
  1310. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1311. else
  1312. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1313. typeValueParams.push_back(vDataValue);
  1314. if (hasObjectDebugFlags)
  1315. {
  1316. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1317. typeValueParams.push_back(GetDefaultValue(primType));
  1318. }
  1319. }
  1320. BfIRValue BfModule::GetConstValue(int64 val)
  1321. {
  1322. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1323. }
  1324. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1325. {
  1326. BfType* checkType = type;
  1327. if (type->IsTypedPrimitive())
  1328. {
  1329. checkType = type->GetUnderlyingType();
  1330. }
  1331. if (checkType->IsPrimitiveType())
  1332. {
  1333. auto primType = (BfPrimitiveType*)checkType;
  1334. if (checkType->IsFloat())
  1335. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1336. else
  1337. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1338. }
  1339. return BfIRValue();
  1340. }
  1341. BfIRValue BfModule::GetConstValue8(int val)
  1342. {
  1343. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1344. }
  1345. BfIRValue BfModule::GetConstValue32(int32 val)
  1346. {
  1347. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1348. }
  1349. BfIRValue BfModule::GetConstValue64(int64 val)
  1350. {
  1351. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1352. }
  1353. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1354. {
  1355. PopulateType(type, BfPopulateType_Data);
  1356. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1357. if (type->IsTypedPrimitive())
  1358. {
  1359. auto underlyingType = type->GetUnderlyingType();
  1360. if (underlyingType == NULL)
  1361. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1362. return GetDefaultValue(type->GetUnderlyingType());
  1363. }
  1364. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1365. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1366. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1367. if ((type->IsIntegral()) || (type->IsBoolean()))
  1368. {
  1369. auto primType = (BfPrimitiveType*)type;
  1370. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1371. }
  1372. if (type->IsFloat())
  1373. {
  1374. auto primType = (BfPrimitiveType*)type;
  1375. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1376. }
  1377. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1378. }
  1379. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1380. {
  1381. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1382. if (type->mSize == 0)
  1383. return BfTypedValue(BfIRValue::sValueless, type);
  1384. else if (mBfIRBuilder != NULL)
  1385. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1386. else
  1387. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1388. }
  1389. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1390. {
  1391. if (type->IsVar())
  1392. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1393. PopulateType(type, BfPopulateType_Data);
  1394. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1395. if (defaultValueKind == BfDefaultValueKind_Undef)
  1396. {
  1397. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1398. }
  1399. BfTypedValue typedValue;
  1400. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1401. {
  1402. if (type->IsRef())
  1403. {
  1404. BfRefType* refType = (BfRefType*)type;
  1405. BfType* underlyingType = refType->GetUnderlyingType();
  1406. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1407. }
  1408. else
  1409. {
  1410. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1411. }
  1412. if (!mBfIRBuilder->mIgnoreWrites)
  1413. {
  1414. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1415. GetConstValue(type->mSize), type->mAlign);
  1416. }
  1417. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1418. typedValue = LoadValue(typedValue);
  1419. return typedValue;
  1420. }
  1421. if ((type->IsRef()) && (!allowRef))
  1422. {
  1423. BfRefType* refType = (BfRefType*)type;
  1424. BfType* underlyingType = refType->GetUnderlyingType();
  1425. if (underlyingType->IsValuelessType())
  1426. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1427. else
  1428. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1429. }
  1430. else
  1431. {
  1432. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1433. }
  1434. return typedValue;
  1435. }
  1436. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1437. {
  1438. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1439. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1440. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1441. BfIRValue strConstant;
  1442. if (define)
  1443. {
  1444. strConstant = mBfIRBuilder->CreateConstString(str);
  1445. }
  1446. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1447. true, BfIRLinkageType_External,
  1448. strConstant, stringDataName);
  1449. if (define)
  1450. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1451. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1452. }
  1453. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1454. {
  1455. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1456. return;
  1457. int prevDataIdx = -1;
  1458. int usedDataIdx = 0;
  1459. int valueParamIdx = 0;
  1460. if (typeInst->mBaseType != NULL)
  1461. {
  1462. usedDataIdx++;
  1463. valueParamIdx++;
  1464. prevDataIdx++;
  1465. }
  1466. int startingParamsSize = (int)valueParams.mSize;
  1467. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1468. {
  1469. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1470. if (fieldInstance->mDataIdx < 0)
  1471. continue;
  1472. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1473. if (fillInPadding)
  1474. {
  1475. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1476. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1477. }
  1478. valueParamIdx++;
  1479. prevDataIdx = fieldInstance->mDataIdx;
  1480. usedDataIdx++;
  1481. if (usedDataIdx <= valueParams.mSize)
  1482. continue;
  1483. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1484. }
  1485. }
  1486. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1487. {
  1488. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1489. mBfIRBuilder->PopulateType(stringTypeInst);
  1490. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1491. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1492. BfIRValue stringValData;
  1493. if (define)
  1494. {
  1495. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1496. mStringCharPtrPool[stringId] = stringCharsVal;
  1497. SizedArray<BfIRValue, 8> typeValueParams;
  1498. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1499. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1500. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1501. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1502. typeValueParams.clear();
  1503. typeValueParams.push_back(objData);
  1504. if (lenByteCount == 4)
  1505. {
  1506. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1507. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1508. }
  1509. else
  1510. {
  1511. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1512. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1513. }
  1514. typeValueParams.push_back(stringCharsVal); // mPtr
  1515. FixConstValueParams(stringTypeInst, typeValueParams);
  1516. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1517. }
  1518. mBfIRBuilder->PopulateType(stringTypeInst);
  1519. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1520. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1521. true,
  1522. BfIRLinkageType_External,
  1523. define ? stringValData : BfIRValue(),
  1524. stringObjName);
  1525. return stringValLiteral;
  1526. }
  1527. bool BfModule::HasStringId(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1528. {
  1529. if (constHolder == NULL)
  1530. constHolder = mBfIRBuilder;
  1531. auto constant = constHolder->GetConstant(constantStr);
  1532. if (constant == NULL)
  1533. return false;
  1534. while (constant->mConstType == BfConstType_BitCast)
  1535. {
  1536. auto constBitCast = (BfConstantBitCast*)constant;
  1537. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1538. }
  1539. if (constant->mTypeCode == BfTypeCode_StringId)
  1540. {
  1541. return true;
  1542. }
  1543. return false;
  1544. }
  1545. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1546. {
  1547. if (constHolder == NULL)
  1548. constHolder = mBfIRBuilder;
  1549. auto constant = constHolder->GetConstant(constantStr);
  1550. if (constant == NULL)
  1551. return -1;
  1552. if ((constant->mTypeCode == BfTypeCode_StringId) || (constant->mTypeCode == BfTypeCode_CharPtr))
  1553. {
  1554. return constant->mInt32;
  1555. }
  1556. while (constant->mConstType == BfConstType_BitCast)
  1557. {
  1558. auto constBitCast = (BfConstantBitCast*)constant;
  1559. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1560. }
  1561. if (constant->mConstType == BfConstType_GEP32_2)
  1562. {
  1563. auto constGEP = (BfConstantGEP32_2*)constant;
  1564. constant = constHolder->GetConstantById(constGEP->mTarget);
  1565. }
  1566. if (constant->mConstType == BfConstType_GlobalVar)
  1567. {
  1568. auto constGV = (BfGlobalVar*)constant;
  1569. const char* strDataPrefix = "__bfStrData";
  1570. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1571. return atoi(constGV->mName + strlen(strDataPrefix));
  1572. const char* strObjPrefix = "__bfStrObj";
  1573. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1574. return atoi(constGV->mName + strlen(strObjPrefix));
  1575. }
  1576. return -1;
  1577. }
  1578. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1579. {
  1580. int strId = GetStringPoolIdx(constantStr, constHolder);
  1581. if (strId != -1)
  1582. {
  1583. auto& entry = mContext->mStringObjectIdMap[strId];
  1584. return &entry.mString;
  1585. }
  1586. return NULL;
  1587. }
  1588. CeDbgState* BfModule::GetCeDbgState()
  1589. {
  1590. if (!mIsComptimeModule)
  1591. return NULL;
  1592. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1593. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1594. return NULL;
  1595. }
  1596. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1597. {
  1598. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1599. {
  1600. mUnreifiedStringPoolRefs.Add(stringId);
  1601. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1602. }
  1603. BfIRValue* irValue = NULL;
  1604. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1605. return *irValue;
  1606. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1607. if (!mStringObjectPool.ContainsKey(stringId))
  1608. mStringPoolRefs.Add(stringId);
  1609. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1610. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1611. *irValue = strCharPtrConst;
  1612. return strCharPtrConst;
  1613. }
  1614. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1615. {
  1616. if (strValue.IsConst())
  1617. {
  1618. int stringId = GetStringPoolIdx(strValue);
  1619. BF_ASSERT(stringId != -1);
  1620. return GetStringCharPtr(stringId, force);
  1621. }
  1622. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1623. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1624. return charPtr;
  1625. }
  1626. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1627. {
  1628. auto result = GetStringCharPtr(GetStringObjectValue(str, force), force);
  1629. if (result.IsConst())
  1630. {
  1631. auto constant = mBfIRBuilder->GetConstant(result);
  1632. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  1633. return mBfIRBuilder->CreateConst(BfTypeCode_CharPtr, constant->mInt32);
  1634. }
  1635. return result;
  1636. }
  1637. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1638. {
  1639. BfIRValue* objValue;
  1640. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1641. return *objValue;
  1642. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1643. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1644. }
  1645. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1646. {
  1647. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1648. mBfIRBuilder->PopulateType(stringType);
  1649. int strId = mContext->GetStringLiteralId(str);
  1650. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1651. {
  1652. auto refModule = this;
  1653. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1654. refModule = mCurTypeInstance->mModule;
  1655. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1656. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1657. }
  1658. BfIRValue* irValuePtr = NULL;
  1659. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1660. return *irValuePtr;
  1661. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1662. if (!mStringCharPtrPool.ContainsKey(strId))
  1663. mStringPoolRefs.Add(strId);
  1664. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1665. mStringObjectPool[strId] = strObject;
  1666. mStringPoolRefs.Add(strId);
  1667. return strObject;
  1668. }
  1669. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1670. {
  1671. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1672. type,
  1673. true,
  1674. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1675. constant,
  1676. name.c_str());
  1677. return newConst;
  1678. }
  1679. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1680. {
  1681. auto curScope = mCurMethodState->mCurScope;
  1682. if (curScope->mLabelNode != NULL)
  1683. {
  1684. curScope->mLabelNode->ToString(curScope->mLabel);
  1685. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1686. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1687. auto autoComplete = mCompiler->GetAutoComplete();
  1688. if (autoComplete != NULL)
  1689. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1690. }
  1691. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1692. {
  1693. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1694. while (checkScope != NULL)
  1695. {
  1696. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1697. {
  1698. auto errorNode = Warn(0, StrFormat("Duplicate scope label '%s'", checkScope->mLabel.c_str()), curScope->mLabelNode);
  1699. if (errorNode != NULL)
  1700. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1701. break;
  1702. }
  1703. checkScope = checkScope->mPrevScope;
  1704. }
  1705. }
  1706. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1707. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1708. {
  1709. if (prevScope->mHadScopeValueRetain)
  1710. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1711. else
  1712. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1713. }
  1714. mCurMethodState->mBlockNestLevel++;
  1715. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1716. {
  1717. // DIScope could be NULL if we're in an unspecialized method (for example)
  1718. if (mCurMethodState->mCurScope->mDIScope)
  1719. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1720. }
  1721. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1722. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1723. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1724. }
  1725. void BfModule::RestoreScoreState_LocalVariables(int localVarStart)
  1726. {
  1727. while (localVarStart < (int)mCurMethodState->mLocals.size())
  1728. {
  1729. auto localVar = mCurMethodState->mLocals.back();
  1730. LocalVariableDone(localVar, false);
  1731. mCurMethodState->mLocals.pop_back();
  1732. if (localVar->mShadowedLocal != NULL)
  1733. {
  1734. BfLocalVarEntry* localVarEntryPtr;
  1735. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1736. {
  1737. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1738. }
  1739. }
  1740. else
  1741. {
  1742. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1743. }
  1744. if (localVar->mIsBumpAlloc)
  1745. localVar->~BfLocalVariable();
  1746. else
  1747. delete localVar;
  1748. }
  1749. }
  1750. void BfModule::RestoreScopeState()
  1751. {
  1752. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1753. mCurMethodState->mBlockNestLevel--;
  1754. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1755. {
  1756. BfIRBlock afterEndBlock;
  1757. if (!mCurMethodState->mLeftBlockUncond)
  1758. {
  1759. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1760. mBfIRBuilder->CreateBr(afterEndBlock);
  1761. mBfIRBuilder->ClearDebugLocation_Last();
  1762. }
  1763. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1764. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1765. if (afterEndBlock)
  1766. {
  1767. mBfIRBuilder->AddBlock(afterEndBlock);
  1768. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1769. }
  1770. }
  1771. mCurMethodState->mCurScope->mDone = true;
  1772. if (!mCurMethodState->mLeftBlockUncond)
  1773. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1774. EmitDeferredCallProcessorInstances(mCurMethodState->mCurScope);
  1775. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  1776. if (mCurMethodState->mCurScope->mValueScopeStart)
  1777. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1778. mCurMethodState->mCurScope = prevScopeData;
  1779. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1780. }
  1781. BfIRValue BfModule::CreateAlloca(BfIRType irType, int align, bool addLifetime, const char* name, BfIRValue arraySize)
  1782. {
  1783. if (mBfIRBuilder->mIgnoreWrites)
  1784. return mBfIRBuilder->GetFakeVal();
  1785. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1786. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1787. if (!mBfIRBuilder->mIgnoreWrites)
  1788. BF_ASSERT(!prevInsertBlock.IsFake());
  1789. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1790. BfIRValue allocaInst;
  1791. if (arraySize)
  1792. allocaInst = mBfIRBuilder->CreateAlloca(irType, arraySize);
  1793. else
  1794. allocaInst = mBfIRBuilder->CreateAlloca(irType);
  1795. if (align > 0)
  1796. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  1797. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1798. if (name != NULL)
  1799. mBfIRBuilder->SetName(allocaInst, name);
  1800. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1801. if ((addLifetime) && (WantsLifetimes()))
  1802. {
  1803. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1804. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1805. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1806. }
  1807. return allocaInst;
  1808. }
  1809. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1810. {
  1811. if (mBfIRBuilder->mIgnoreWrites)
  1812. return mBfIRBuilder->GetFakeVal();
  1813. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1814. mBfIRBuilder->PopulateType(type);
  1815. return CreateAlloca(mBfIRBuilder->MapType(type), type->mAlign, addLifetime, name, arraySize);
  1816. }
  1817. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1818. {
  1819. if (mBfIRBuilder->mIgnoreWrites)
  1820. return mBfIRBuilder->GetFakeVal();
  1821. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1822. mBfIRBuilder->PopulateType(typeInst);
  1823. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1824. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1825. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1826. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1827. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1828. if (name != NULL)
  1829. mBfIRBuilder->SetName(allocaInst, name);
  1830. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1831. if ((addLifetime) && (WantsLifetimes()))
  1832. {
  1833. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1834. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1835. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1836. }
  1837. return allocaInst;
  1838. }
  1839. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1840. {
  1841. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1842. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1843. /*if (mCurMethodState->mInHeadScope)
  1844. isScopeAlloc = true;*/
  1845. if (scopeData == NULL)
  1846. return NULL;
  1847. auto checkBaseType = val.mType->ToTypeInstance();
  1848. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1849. {
  1850. bool hadDtorCall = false;
  1851. while (checkBaseType != NULL)
  1852. {
  1853. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1854. if (dtorMethodDef != NULL)
  1855. {
  1856. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1857. if (dtorMethodInstance)
  1858. {
  1859. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1860. BfIRValue useVal = val.mValue;
  1861. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1862. if (valBlock)
  1863. mBfIRBuilder->SetInsertPoint(valBlock);
  1864. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1865. if (!useVal.IsConst())
  1866. mBfIRBuilder->ClearDebugLocation(useVal);
  1867. if (valBlock)
  1868. mBfIRBuilder->SetInsertPoint(prevBlock);
  1869. if (isDynAlloc)
  1870. {
  1871. //
  1872. }
  1873. else if (condAlloca)
  1874. {
  1875. BF_ASSERT(!IsTargetingBeefBackend());
  1876. BF_ASSERT(!isDynAlloc);
  1877. auto valPtr = CreateAlloca(checkBaseType);
  1878. mBfIRBuilder->ClearDebugLocation_Last();
  1879. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1880. mBfIRBuilder->ClearDebugLocation_Last();
  1881. useVal = valPtr;
  1882. }
  1883. SizedArray<BfIRValue, 1> llvmArgs;
  1884. llvmArgs.push_back(useVal);
  1885. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1886. if (deferredCall != NULL)
  1887. {
  1888. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1889. if (condAlloca)
  1890. deferredCall->mArgsNeedLoad = true;
  1891. }
  1892. hadDtorCall = true;
  1893. break;
  1894. }
  1895. }
  1896. checkBaseType = checkBaseType->mBaseType;
  1897. }
  1898. return NULL;
  1899. }
  1900. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1901. if (mayEscape)
  1902. {
  1903. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1904. {
  1905. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1906. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1907. if (!isDyn)
  1908. {
  1909. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1910. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1911. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1912. if (!dtorMethodInstance.mMethodInstance)
  1913. {
  1914. Fail(StrFormat("Unable to find %s", methodName));
  1915. }
  1916. else
  1917. {
  1918. SizedArray<BfIRValue, 1> llvmArgs;
  1919. if (IsTargetingBeefBackend())
  1920. {
  1921. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1922. //mBfIRBuilder->ClearDebugLocation_Last();
  1923. }
  1924. else
  1925. llvmArgs.push_back(val.mValue);
  1926. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1927. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1928. if (arraySize)
  1929. llvmArgs.push_back(arraySize);
  1930. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1931. }
  1932. }
  1933. else
  1934. {
  1935. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1936. {
  1937. BfIRValue clearSize = arraySize;
  1938. if (val.mType->GetStride() > 1)
  1939. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1940. const char* methodName = "SetDeletedX";
  1941. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1942. BF_ASSERT(dtorMethodInstance);
  1943. if (!dtorMethodInstance)
  1944. {
  1945. Fail(StrFormat("Unable to find %s", methodName));
  1946. }
  1947. else
  1948. {
  1949. SizedArray<BfIRValue, 1> llvmArgs;
  1950. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1951. //mBfIRBuilder->ClearDebugLocation_Last();
  1952. llvmArgs.push_back(clearSize);
  1953. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1954. }
  1955. }
  1956. else
  1957. {
  1958. intptr clearSize = val.mType->mSize;
  1959. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1960. if (constant != NULL)
  1961. clearSize = (intptr)(clearSize * constant->mInt64);
  1962. const char* funcName = "SetDeleted1";
  1963. if (clearSize >= 16)
  1964. funcName = "SetDeleted16";
  1965. else if (clearSize >= 8)
  1966. funcName = "SetDeleted8";
  1967. else if (clearSize >= 4)
  1968. funcName = "SetDeleted4";
  1969. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1970. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1971. if (!dtorMethodInstance)
  1972. {
  1973. Fail(StrFormat("Unable to find %s", funcName));
  1974. }
  1975. else
  1976. {
  1977. SizedArray<BfIRValue, 1> llvmArgs;
  1978. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1979. //mBfIRBuilder->ClearDebugLocation_Last();
  1980. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. }
  1986. return NULL;
  1987. }
  1988. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1989. {
  1990. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1991. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1992. return false;
  1993. auto checkTypeInstance = startTypeInstance;
  1994. while (checkTypeInstance != NULL)
  1995. {
  1996. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1997. {
  1998. if (fieldInstance.mMergedDataIdx != -1)
  1999. {
  2000. int64 checkMask = 1;
  2001. if (auto fieldTypeInst = fieldInstance.mResolvedType->ToTypeInstance())
  2002. {
  2003. if (fieldTypeInst->IsValueType())
  2004. checkMask = (1 << fieldTypeInst->mMergedFieldDataCount) - 1;
  2005. }
  2006. checkMask <<= fieldInstance.mMergedDataIdx;
  2007. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2008. {
  2009. // For fields added in extensions, we automatically initialize those if necessary
  2010. auto fieldDef = fieldInstance.GetFieldDef();
  2011. if (!fieldDef->mDeclaringType->IsExtension())
  2012. return false;
  2013. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  2014. {
  2015. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  2016. mBfIRBuilder->SaveDebugLocation();
  2017. if (localVar->IsParam())
  2018. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  2019. else
  2020. {
  2021. BF_ASSERT(localVar->mDeclBlock);
  2022. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  2023. }
  2024. mBfIRBuilder->ClearDebugLocation();
  2025. BfIRValue curVal;
  2026. if (localVar->mIsThis)
  2027. curVal = mBfIRBuilder->GetArgument(0);
  2028. else
  2029. curVal = localVar->mAddr;
  2030. auto subTypeInstance = startTypeInstance;
  2031. while (subTypeInstance != checkTypeInstance)
  2032. {
  2033. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  2034. subTypeInstance = subTypeInstance->mBaseType;
  2035. }
  2036. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  2037. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  2038. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  2039. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  2040. mBfIRBuilder->RestoreDebugLocation();
  2041. }
  2042. localVar->mUnassignedFieldFlags &= ~checkMask;
  2043. if (localVar->mUnassignedFieldFlags == 0)
  2044. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2045. }
  2046. }
  2047. }
  2048. checkTypeInstance = checkTypeInstance->mBaseType;
  2049. }
  2050. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  2051. }
  2052. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  2053. {
  2054. BfAstNode* localNameNode = localVar->mNameNode;
  2055. if ((localVar->mIsThis) && (mCurMethodInstance != NULL))
  2056. {
  2057. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  2058. }
  2059. if (localNameNode != NULL)
  2060. {
  2061. bool isOut = false;
  2062. if (localVar->mResolvedType->IsRef())
  2063. {
  2064. auto refType = (BfRefType*)localVar->mResolvedType;
  2065. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2066. }
  2067. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  2068. {
  2069. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  2070. TryLocalVariableInit(localVar);
  2071. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  2072. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  2073. // We may have init blocks that we aren't processing here...
  2074. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  2075. deferFullAnalysis = true;
  2076. //bool deferFullAnalysis = true;
  2077. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  2078. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  2079. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  2080. (!localVar->mIsImplicitParam))
  2081. {
  2082. if (deferUsageWarning)
  2083. {
  2084. // Ignore
  2085. }
  2086. else if (localVar->mIsThis)
  2087. {
  2088. bool foundFields = false;
  2089. auto checkTypeInstance = mCurTypeInstance;
  2090. while (checkTypeInstance != NULL)
  2091. {
  2092. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  2093. {
  2094. if (fieldInstance.mMergedDataIdx == -1)
  2095. continue;
  2096. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  2097. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  2098. {
  2099. auto fieldDef = fieldInstance.GetFieldDef();
  2100. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  2101. {
  2102. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  2103. {
  2104. // This extension is only responsible for its own fields
  2105. foundFields = true;
  2106. continue;
  2107. }
  2108. if (fieldDef->GetInitializer() != NULL)
  2109. {
  2110. // This initializer was handled in CtorNoBody
  2111. foundFields = true;
  2112. continue;
  2113. }
  2114. }
  2115. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2116. {
  2117. String propName;
  2118. if (propertyDeclaration->mNameNode != NULL)
  2119. propertyDeclaration->mNameNode->ToString(propName);
  2120. if (checkTypeInstance == mCurTypeInstance)
  2121. {
  2122. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2123. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2124. }
  2125. else
  2126. {
  2127. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2128. TypeToString(checkTypeInstance).c_str(),
  2129. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2130. }
  2131. }
  2132. else
  2133. {
  2134. if (checkTypeInstance == mCurTypeInstance)
  2135. {
  2136. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2137. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2138. }
  2139. else
  2140. {
  2141. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2142. TypeToString(checkTypeInstance).c_str(),
  2143. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2144. }
  2145. }
  2146. foundFields = true;
  2147. }
  2148. }
  2149. checkTypeInstance = checkTypeInstance->mBaseType;
  2150. }
  2151. if (!foundFields)
  2152. {
  2153. if (mCurTypeInstance->mInstSize > 0)
  2154. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2155. }
  2156. }
  2157. else if (localVar->IsParam())
  2158. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2159. else if (!deferUsageWarning)
  2160. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2161. }
  2162. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2163. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2164. }
  2165. }
  2166. }
  2167. void BfModule::CreateRetValLocal()
  2168. {
  2169. if (mCurMethodState->mRetVal)
  2170. {
  2171. BfLocalVariable* localDef = new BfLocalVariable();
  2172. localDef->mName = "return";
  2173. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2174. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2175. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2176. AddLocalVariableDef(localDef);
  2177. }
  2178. else if (mCurMethodState->mRetValAddr)
  2179. {
  2180. BfLocalVariable* localDef = new BfLocalVariable();
  2181. localDef->mName = "return";
  2182. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2183. localDef->mAddr = mCurMethodState->mRetValAddr;
  2184. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2185. AddLocalVariableDef(localDef);
  2186. }
  2187. }
  2188. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2189. {
  2190. auto checkScope = mCurMethodState->mCurScope;
  2191. while (true)
  2192. {
  2193. if (checkScope == scopeData)
  2194. break;
  2195. checkScope->mHadOuterDynStack = true;
  2196. checkScope = checkScope->mPrevScope;
  2197. }
  2198. }
  2199. void BfModule::SaveStackState(BfScopeData* scopeData)
  2200. {
  2201. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2202. // scopes within scopeData restore the stack
  2203. auto checkScope = mCurMethodState->mCurScope;
  2204. while (true)
  2205. {
  2206. if (checkScope == scopeData)
  2207. {
  2208. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2209. {
  2210. if (mBfIRBuilder->mHasDebugInfo)
  2211. mBfIRBuilder->SaveDebugLocation();
  2212. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2213. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2214. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2215. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2216. mBfIRBuilder->SetInsertPoint(prevPos);
  2217. if (mBfIRBuilder->mHasDebugInfo)
  2218. mBfIRBuilder->RestoreDebugLocation();
  2219. }
  2220. break;
  2221. }
  2222. if (checkScope->mSavedStack)
  2223. {
  2224. for (auto usage : checkScope->mSavedStackUses)
  2225. mBfIRBuilder->EraseInstFromParent(usage);
  2226. checkScope->mSavedStackUses.Clear();
  2227. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2228. checkScope->mSavedStack = BfIRValue();
  2229. }
  2230. checkScope = checkScope->mPrevScope;
  2231. }
  2232. }
  2233. BfIRValue BfModule::ValueScopeStart()
  2234. {
  2235. if (IsTargetingBeefBackend())
  2236. return mBfIRBuilder->CreateValueScopeStart();
  2237. return BfIRValue();
  2238. }
  2239. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2240. {
  2241. if (valueScopeStart)
  2242. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2243. }
  2244. BfProjectSet* BfModule::GetVisibleProjectSet()
  2245. {
  2246. if (mCurMethodState == NULL)
  2247. return NULL;
  2248. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2249. {
  2250. HashSet<BfType*> seenTypes;
  2251. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2252. {
  2253. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2254. {
  2255. for (auto dep : project->mDependencies)
  2256. _AddProject(dep);
  2257. }
  2258. };
  2259. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2260. {
  2261. auto typeInstance = type->ToTypeInstance();
  2262. if (typeInstance == NULL)
  2263. {
  2264. if (type->IsSizedArray())
  2265. _AddType(type->GetUnderlyingType());
  2266. return;
  2267. }
  2268. if (typeInstance->IsTuple())
  2269. {
  2270. for (auto& fieldInst : typeInstance->mFieldInstances)
  2271. {
  2272. if (fieldInst.mDataIdx != -1)
  2273. _AddType(fieldInst.mResolvedType);
  2274. }
  2275. }
  2276. _AddProject(typeInstance->mTypeDef->mProject);
  2277. if (typeInstance->mGenericTypeInfo == NULL)
  2278. return;
  2279. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2280. {
  2281. if (seenTypes.Add(type))
  2282. _AddType(type);
  2283. }
  2284. };
  2285. if (mCurTypeInstance != NULL)
  2286. {
  2287. _AddType(mCurTypeInstance);
  2288. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mType == mCurTypeInstance))
  2289. {
  2290. if (mContext->mCurTypeState->mCurTypeDef != NULL)
  2291. _AddProject(mContext->mCurTypeState->mCurTypeDef->mProject);
  2292. }
  2293. }
  2294. auto methodState = mCurMethodState;
  2295. while (methodState != NULL)
  2296. {
  2297. if (methodState->mMethodInstance != NULL)
  2298. {
  2299. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2300. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2301. {
  2302. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2303. _AddType(type);
  2304. }
  2305. }
  2306. methodState = methodState->mPrevMethodState;
  2307. }
  2308. }
  2309. return &mCurMethodState->mVisibleProjectSet;
  2310. }
  2311. bool BfModule::IsProjectVisible(BfProject* project)
  2312. {
  2313. auto visibleProjectSet = GetVisibleProjectSet();
  2314. if (visibleProjectSet != NULL)
  2315. return visibleProjectSet->Contains(project);
  2316. auto activeTypeDef = GetActiveTypeDef();
  2317. if (activeTypeDef != NULL)
  2318. {
  2319. if (activeTypeDef->mProject == project)
  2320. return true;
  2321. return activeTypeDef->mProject->HasDependency(project);
  2322. }
  2323. return false;
  2324. }
  2325. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2326. {
  2327. auto bfParser = astNode->GetSourceData()->ToParserData();
  2328. if (bfParser == NULL)
  2329. return NULL;
  2330. BfFileInstance** fileInstancePtr = NULL;
  2331. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2332. {
  2333. return *fileInstancePtr;
  2334. }
  2335. else
  2336. {
  2337. // It's possible two parsers have the same file name (ie: mNextRevision)
  2338. BfFileInstance** namedFileInstancePtr = NULL;
  2339. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2340. {
  2341. auto bfFileInstance = *namedFileInstancePtr;
  2342. *fileInstancePtr = bfFileInstance;
  2343. return bfFileInstance;
  2344. }
  2345. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2346. auto bfFileInstance = new BfFileInstance();
  2347. *fileInstancePtr = bfFileInstance;
  2348. *namedFileInstancePtr = bfFileInstance;
  2349. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2350. bfFileInstance->mParser = bfParser;
  2351. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2352. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2353. {
  2354. String fileName = bfParser->mFileName;
  2355. for (int i = 0; i < (int)fileName.length(); i++)
  2356. {
  2357. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2358. fileName[i] = DIR_SEP_CHAR;
  2359. }
  2360. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2361. }
  2362. return bfFileInstance;
  2363. }
  2364. }
  2365. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2366. {
  2367. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2368. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2369. return;
  2370. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2371. if (astNode == NULL)
  2372. return;
  2373. auto bfParser = astNode->GetSourceData()->ToParserData();
  2374. if (bfParser == NULL)
  2375. return;
  2376. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2377. {
  2378. if (mCurFilePosition.mFileInstance != NULL)
  2379. {
  2380. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2381. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2382. }
  2383. auto bfFileInstance = GetFileFromNode(astNode);
  2384. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2385. {
  2386. mCurFilePosition = bfFileInstance->mPrevPosition;
  2387. }
  2388. else
  2389. {
  2390. mCurFilePosition.mFileInstance = bfFileInstance;
  2391. mCurFilePosition.mCurLine = 0;
  2392. mCurFilePosition.mCurColumn = 0;
  2393. mCurFilePosition.mCurSrcPos = 0;
  2394. }
  2395. }
  2396. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2397. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2398. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2399. if (jumpEntry->mCharIdx > srcPos)
  2400. jumpEntry--;
  2401. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2402. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2403. mCurFilePosition.mCurColumn = 0;
  2404. while (mCurFilePosition.mCurSrcPos < srcPos)
  2405. {
  2406. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2407. {
  2408. mCurFilePosition.mCurLine++;
  2409. mCurFilePosition.mCurColumn = 0;
  2410. }
  2411. else
  2412. {
  2413. mCurFilePosition.mCurColumn++;
  2414. }
  2415. mCurFilePosition.mCurSrcPos++;
  2416. }
  2417. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2418. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2419. {
  2420. int column = mCurFilePosition.mCurColumn + 1;
  2421. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2422. {
  2423. // Set to illegal position
  2424. column = 0;
  2425. }
  2426. if (mSetIllegalSrcPosition)
  2427. column = 0;
  2428. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2429. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2430. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2431. {
  2432. // This is from a different scope...
  2433. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2434. {
  2435. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2436. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2437. }
  2438. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2439. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2440. }
  2441. else
  2442. {
  2443. if (mCurMethodState->mCurScope->mAltDIFile)
  2444. {
  2445. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2446. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2447. }
  2448. }
  2449. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2450. if (mCurMethodState->mCrossingMixin)
  2451. inlineAt = BfIRMDNode();
  2452. if ((!useDIScope) && (mIsComptimeModule))
  2453. useDIScope = wantDIFile;
  2454. if (!useDIScope)
  2455. mBfIRBuilder->ClearDebugLocation();
  2456. else
  2457. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2458. if ((flags & BfSrcPosFlag_Expression) == 0)
  2459. mBfIRBuilder->CreateStatementStart();
  2460. }
  2461. }
  2462. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2463. {
  2464. // We've turned off expr src pos (for now?)
  2465. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2466. }
  2467. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2468. {
  2469. if (mCompiler->mBfObjectTypeDef != NULL)
  2470. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2471. SetIllegalSrcPos();
  2472. }
  2473. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2474. {
  2475. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2476. {
  2477. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2478. if (curScope)
  2479. {
  2480. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2481. {
  2482. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2483. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2484. }
  2485. else
  2486. {
  2487. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2488. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2489. }
  2490. }
  2491. if ((flags & BfSrcPosFlag_Expression) == 0)
  2492. mBfIRBuilder->CreateStatementStart();
  2493. }
  2494. }
  2495. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2496. {
  2497. // We've turned off expr src pos (for now?)
  2498. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2499. }
  2500. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2501. {
  2502. if ((protection == BfProtection_Public) ||
  2503. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2504. ((protection == BfProtection_Private) && (allowPrivate)))
  2505. return true;
  2506. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2507. {
  2508. mAttributeState->mUsed = true;
  2509. return true;
  2510. }
  2511. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2512. {
  2513. if (CheckInternalProtection(checkType))
  2514. return true;
  2515. }
  2516. return false;
  2517. }
  2518. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2519. {
  2520. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2521. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2522. {
  2523. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2524. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2525. }
  2526. allowProtected = allowPrivate;
  2527. }
  2528. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2529. {
  2530. if ((memberOwner != NULL) && (mCurMethodState != NULL) && (mCurMethodState->mPrivateTypeInstance == memberOwner))
  2531. return true;
  2532. if (memberProtection == BfProtection_Hidden)
  2533. return false;
  2534. if (memberProtection == BfProtection_Public)
  2535. return true;
  2536. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2537. {
  2538. BfTypeInstance* curCheckType = mCurTypeInstance;
  2539. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2540. {
  2541. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2542. curCheckType = mixinOwner;
  2543. }
  2544. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2545. if (curCheckType != NULL)
  2546. {
  2547. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2548. if (memberOwner->mTypeDef->IsGlobalsContainer())
  2549. allowPrivate |= curCheckType->mTypeDef->mNamespace == memberOwner->mTypeDef->mNamespace;
  2550. }
  2551. if (allowPrivate)
  2552. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2553. else
  2554. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2555. }
  2556. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2557. return true;
  2558. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2559. {
  2560. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2561. {
  2562. bool allowProtected = false;
  2563. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2564. auto curCheckType = mCurTypeInstance;
  2565. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2566. {
  2567. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2568. curCheckType = mixinOwner;
  2569. }
  2570. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2571. {
  2572. auto lookupCheckType = lookupStartType;
  2573. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2574. {
  2575. if (lookupCheckType == curCheckType)
  2576. {
  2577. allowProtected = true;
  2578. break;
  2579. }
  2580. if (lookupCheckType == memberOwner)
  2581. break;
  2582. lookupCheckType = lookupCheckType->mBaseType;
  2583. if (lookupCheckType == NULL)
  2584. break;
  2585. }
  2586. }
  2587. else
  2588. {
  2589. auto lookupCheckType = curCheckType;
  2590. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2591. {
  2592. if (lookupCheckType == memberOwner)
  2593. {
  2594. allowProtected = true;
  2595. break;
  2596. }
  2597. lookupCheckType = lookupCheckType->mBaseType;
  2598. if (lookupCheckType == NULL)
  2599. break;
  2600. }
  2601. }
  2602. if (!allowProtected)
  2603. {
  2604. // It's possible our outer type is derived from 'memberOwner'
  2605. while (curCheckType->mTypeDef->mNestDepth > 0)
  2606. {
  2607. curCheckType = GetOuterType(curCheckType);
  2608. if (curCheckType == NULL)
  2609. break;
  2610. auto lookupCheckType = lookupStartType;
  2611. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2612. {
  2613. if (lookupCheckType == curCheckType)
  2614. {
  2615. allowProtected = true;
  2616. break;
  2617. }
  2618. if (lookupCheckType == memberOwner)
  2619. break;
  2620. lookupCheckType = lookupCheckType->mBaseType;
  2621. if (lookupCheckType == NULL)
  2622. break;
  2623. }
  2624. }
  2625. }
  2626. if (allowProtected)
  2627. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2628. else
  2629. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2630. }
  2631. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2632. return true;
  2633. }
  2634. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2635. {
  2636. mAttributeState->mUsed = true;
  2637. return true;
  2638. }
  2639. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2640. {
  2641. if (CheckInternalProtection(memberOwner->mTypeDef))
  2642. return true;
  2643. }
  2644. return false;
  2645. }
  2646. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2647. {
  2648. if (mCompiler->mResolvePassData != NULL)
  2649. {
  2650. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2651. sourceClassifier->SetElementType(astNode, elementType);
  2652. }
  2653. }
  2654. void BfModule::SetHighestElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2655. {
  2656. if (mCompiler->mResolvePassData != NULL)
  2657. {
  2658. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2659. sourceClassifier->SetHighestElementType(astNode, elementType);
  2660. }
  2661. }
  2662. bool BfModule::PreFail()
  2663. {
  2664. if (!mIgnoreErrors)
  2665. return true;
  2666. SetFail();
  2667. return false;
  2668. }
  2669. void BfModule::SetFail()
  2670. {
  2671. if (mIgnoreErrors)
  2672. {
  2673. if (mAttributeState != NULL)
  2674. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2675. }
  2676. }
  2677. void BfModule::VerifyOnDemandMethods()
  2678. {
  2679. #ifdef _DEBUG
  2680. // if (mParentModule != NULL)
  2681. // {
  2682. // BF_ASSERT(mOnDemandMethodCount == 0);
  2683. // mParentModule->VerifyOnDemandMethods();
  2684. // return;
  2685. // }
  2686. //
  2687. // int onDemandCount = 0;
  2688. // for (auto type : mOwnedTypeInstances)
  2689. // {
  2690. // auto typeInst = type->ToTypeInstance();
  2691. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2692. // {
  2693. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2694. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2695. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2696. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2697. // onDemandCount++;
  2698. // }
  2699. // }
  2700. //
  2701. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2702. #endif
  2703. }
  2704. bool BfModule::IsSkippingExtraResolveChecks()
  2705. {
  2706. if (mIsComptimeModule)
  2707. return false;
  2708. return mCompiler->IsSkippingExtraResolveChecks();
  2709. }
  2710. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2711. {
  2712. bool isWhileSpecializingMethod = false;
  2713. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2714. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2715. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2716. errorString += StrFormat("\n while generating append size calculating method");
  2717. else if (refNode == NULL)
  2718. {
  2719. if (mCurTypeInstance != NULL)
  2720. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2721. else if (mProject != NULL)
  2722. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2723. }
  2724. if (mCurTypeInstance != NULL)
  2725. {
  2726. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2727. {
  2728. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2729. if (isWarning)
  2730. methodInstance->mHasWarning = true;
  2731. else
  2732. methodInstance->mHasFailed = true;
  2733. if (!methodInstance->mHasStartedDeclaration)
  2734. StartMethodDeclaration(methodInstance, NULL);
  2735. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2736. if (isSpecializedMethod)
  2737. {
  2738. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2739. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2740. if (unspecializedMethod == methodInstance)
  2741. {
  2742. // This is a local method inside a generic method
  2743. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2744. }
  2745. else
  2746. {
  2747. if (isWarning)
  2748. {
  2749. if (unspecializedMethod->mHasWarning)
  2750. return false; // At least SOME error has already been reported
  2751. }
  2752. else
  2753. {
  2754. if (unspecializedMethod->mHasFailed)
  2755. return false; // At least SOME error has already been reported
  2756. }
  2757. }
  2758. }
  2759. if (isSpecializedMethod)
  2760. {
  2761. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2762. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2763. isWhileSpecializingMethod = true;
  2764. }
  2765. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2766. {
  2767. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2768. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2769. isWhileSpecializingMethod = true;
  2770. }
  2771. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2772. {
  2773. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2774. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2775. }
  2776. return true;
  2777. };
  2778. bool hadMethodInstance = false;
  2779. if (mCurMethodState != NULL)
  2780. {
  2781. auto checkMethodState = mCurMethodState;
  2782. while (checkMethodState != NULL)
  2783. {
  2784. auto methodInstance = checkMethodState->mMethodInstance;
  2785. if (methodInstance == NULL)
  2786. {
  2787. checkMethodState = checkMethodState->mPrevMethodState;
  2788. continue;
  2789. }
  2790. hadMethodInstance = true;
  2791. if (!_CheckMethodInstance(methodInstance))
  2792. return false;
  2793. checkMethodState = checkMethodState->mPrevMethodState;
  2794. }
  2795. }
  2796. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2797. {
  2798. if (!_CheckMethodInstance(mCurMethodInstance))
  2799. return false;
  2800. }
  2801. }
  2802. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2803. {
  2804. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2805. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2806. }
  2807. return true;
  2808. }
  2809. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2810. {
  2811. BP_ZONE("BfModule::Fail");
  2812. if (mIgnoreErrors)
  2813. {
  2814. mHadIgnoredError = true;
  2815. if (mAttributeState != NULL)
  2816. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2817. return NULL;
  2818. }
  2819. if (!mReportErrors)
  2820. {
  2821. mCompiler->mPassInstance->SilentFail();
  2822. return NULL;
  2823. }
  2824. if (refNode != NULL)
  2825. refNode = BfNodeToNonTemporary(refNode);
  2826. //BF_ASSERT(refNode != NULL);
  2827. if (mIsComptimeModule)
  2828. {
  2829. if (auto ceDbgState = GetCeDbgState())
  2830. {
  2831. // Follow normal fail path
  2832. }
  2833. else
  2834. {
  2835. mHadBuildError = true;
  2836. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2837. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2838. {
  2839. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2840. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2841. if (bfError != NULL)
  2842. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2843. return bfError;
  2844. }
  2845. return NULL;
  2846. }
  2847. }
  2848. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2849. {
  2850. mCurMethodState->mConstResolveState->mFailed = true;
  2851. return NULL;
  2852. }
  2853. if (mCurMethodInstance != NULL)
  2854. mCurMethodInstance->mHasFailed = true;
  2855. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2856. return NULL;
  2857. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2858. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2859. if (!mHadBuildError)
  2860. mHadBuildError = true;
  2861. if (mParentModule != NULL)
  2862. mParentModule->mHadBuildError = true;
  2863. if (mCurTypeInstance != NULL)
  2864. AddFailType(mCurTypeInstance);
  2865. BfLogSysM("BfModule::Fail module %p type %p %s @ %s\n", this, mCurTypeInstance, error.c_str(), (refNode != NULL) ? refNode->LocationToString().c_str() : "???");
  2866. String errorString = error;
  2867. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2868. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2869. return NULL;
  2870. BfError* bfError = NULL;
  2871. if (isWhileSpecializing)
  2872. deferError = true;
  2873. if (!mHadBuildError)
  2874. mHadBuildError = true;
  2875. // Check mixins
  2876. {
  2877. auto checkMethodState = mCurMethodState;
  2878. while (checkMethodState != NULL)
  2879. {
  2880. auto rootMixinState = checkMethodState->GetRootMixinState();
  2881. if (rootMixinState != NULL)
  2882. {
  2883. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2884. if (deferError)
  2885. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2886. else
  2887. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2888. if (bfError == NULL)
  2889. return NULL;
  2890. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2891. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2892. auto mixinState = checkMethodState->mMixinState;
  2893. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2894. {
  2895. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2896. mixinState = mixinState->mPrevMixinState;
  2897. }
  2898. return bfError;
  2899. }
  2900. checkMethodState = checkMethodState->mPrevMethodState;
  2901. }
  2902. }
  2903. if (deferError)
  2904. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2905. else if (refNode == NULL)
  2906. bfError = mCompiler->mPassInstance->Fail(errorString);
  2907. else
  2908. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2909. if (bfError != NULL)
  2910. {
  2911. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2912. bfError->mProject = mProject;
  2913. bfError->mIsPersistent = isPersistent;
  2914. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2915. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2916. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2917. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2918. }
  2919. return bfError;
  2920. }
  2921. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2922. {
  2923. if (mHadBuildError)
  2924. return NULL;
  2925. return Fail(error, refNode);
  2926. }
  2927. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2928. {
  2929. if (mIgnoreErrors)
  2930. return NULL;
  2931. if (refNode != NULL)
  2932. refNode = BfNodeToNonTemporary(refNode);
  2933. mHadBuildError = true;
  2934. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2935. if (bfError != NULL)
  2936. bfError->mProject = mProject;
  2937. return bfError;
  2938. }
  2939. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2940. {
  2941. if (mIgnoreErrors || mIgnoreWarnings)
  2942. return NULL;
  2943. if (!mReportErrors)
  2944. {
  2945. mCompiler->mPassInstance->SilentFail();
  2946. return NULL;
  2947. }
  2948. BfAstNode* unwarnNode = refNode;
  2949. //
  2950. {
  2951. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2952. while (parentNodeEntry != NULL)
  2953. {
  2954. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2955. break;
  2956. unwarnNode = parentNodeEntry->mNode;
  2957. parentNodeEntry = parentNodeEntry->mPrev;
  2958. }
  2959. }
  2960. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2961. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2962. {
  2963. return NULL;
  2964. }
  2965. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2966. if (mCurMethodInstance != NULL)
  2967. {
  2968. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2969. {
  2970. if (!showInSpecialized)
  2971. return NULL;
  2972. }
  2973. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2974. return NULL; // No ctorCalcAppend warnings
  2975. }
  2976. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2977. {
  2978. if (!showInSpecialized)
  2979. return NULL;
  2980. }
  2981. if (refNode != NULL)
  2982. refNode = BfNodeToNonTemporary(refNode);
  2983. String warningString = warning;
  2984. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2985. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2986. return NULL;
  2987. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2988. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2989. {
  2990. // We used to bubble up warnings into the mixin injection site, BUT
  2991. // we are now assuming any relevant warnings will be given at the declaration site
  2992. return NULL;
  2993. }
  2994. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2995. {
  2996. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2997. if (bfError != NULL)
  2998. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2999. return bfError;
  3000. }
  3001. BfError* bfError;
  3002. if (refNode != NULL)
  3003. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  3004. else
  3005. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  3006. if (bfError != NULL)
  3007. {
  3008. bfError->mIsWhileSpecializing = isWhileSpecializing;
  3009. bfError->mProject = mProject;
  3010. AddFailType(mCurTypeInstance);
  3011. mHadBuildWarning = true;
  3012. bfError->mIsPersistent = isPersistent;
  3013. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  3014. {
  3015. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  3016. if (parser != NULL)
  3017. {
  3018. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  3019. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  3020. if (warningNum != 0)
  3021. {
  3022. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  3023. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  3024. }
  3025. }
  3026. }
  3027. }
  3028. return bfError;
  3029. }
  3030. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  3031. {
  3032. if (customAttributes == NULL)
  3033. return;
  3034. auto _AddDeclarationMoreInfo = [&]()
  3035. {
  3036. if (methodInstance != NULL)
  3037. {
  3038. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  3039. mCompiler->mPassInstance->MoreInfo(
  3040. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  3041. methodInstance->mMethodDef->GetRefNode());
  3042. }
  3043. else
  3044. {
  3045. mCompiler->mPassInstance->MoreInfo(
  3046. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  3047. typeInstance->mTypeDef->GetRefNode());
  3048. }
  3049. };
  3050. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  3051. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  3052. if ((customAttribute != NULL) && (targetSrc != NULL))
  3053. {
  3054. String err;
  3055. if (fieldInstance != NULL)
  3056. err = StrFormat("'%s' is obsolete", FieldToString(fieldInstance).c_str());
  3057. else if (methodInstance != NULL)
  3058. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  3059. else
  3060. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3061. bool isError = false;
  3062. if (customAttribute->mCtorArgs.size() >= 1)
  3063. {
  3064. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3065. if (constant->mTypeCode == BfTypeCode_Boolean)
  3066. {
  3067. isError = constant->mBool;
  3068. }
  3069. else if (constant->mTypeCode == BfTypeCode_StringId)
  3070. {
  3071. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3072. if (str != NULL)
  3073. {
  3074. err += ":\n '";
  3075. err += *str;
  3076. err += "'";
  3077. }
  3078. if (customAttribute->mCtorArgs.size() >= 2)
  3079. {
  3080. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3081. isError = constant->mBool;
  3082. }
  3083. }
  3084. }
  3085. BfError* error = NULL;
  3086. if (isError)
  3087. error = Fail(err, targetSrc);
  3088. else
  3089. error = Warn(0, err, targetSrc, false, true);
  3090. if (error != NULL)
  3091. _AddDeclarationMoreInfo();
  3092. }
  3093. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  3094. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3095. {
  3096. String err;
  3097. if (fieldInstance != NULL)
  3098. err += StrFormat("Method error: '", FieldToString(fieldInstance).c_str());
  3099. else if (methodInstance != NULL)
  3100. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  3101. else
  3102. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3103. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3104. if (str != NULL)
  3105. err += *str;
  3106. err += "'";
  3107. if (Fail(err, targetSrc) != NULL)
  3108. _AddDeclarationMoreInfo();
  3109. }
  3110. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  3111. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  3112. {
  3113. String err;
  3114. if (fieldInstance != NULL)
  3115. err += StrFormat("Field warning: '", FieldToString(fieldInstance).c_str());
  3116. else if (methodInstance != NULL)
  3117. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  3118. else
  3119. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  3120. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3121. if (str != NULL)
  3122. err += *str;
  3123. err += "'";
  3124. if (Warn(0, err, targetSrc, false, true) != NULL)
  3125. _AddDeclarationMoreInfo();
  3126. }
  3127. }
  3128. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  3129. {
  3130. if (mBfIRBuilder->mOpFailed)
  3131. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  3132. }
  3133. void BfModule::FatalError(const StringImpl& error, const char* file, int line, int column)
  3134. {
  3135. static bool sHadFatalError = false;
  3136. static bool sHadReentrancy = false;
  3137. if (sHadFatalError)
  3138. {
  3139. return;
  3140. sHadReentrancy = true;
  3141. }
  3142. sHadFatalError = true;
  3143. String fullError = error;
  3144. if (file != NULL)
  3145. {
  3146. fullError += StrFormat(" at %s:%d", file, line);
  3147. if (column != -1)
  3148. fullError += StrFormat(":%d", column);
  3149. }
  3150. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3151. if (mCurTypeInstance != NULL)
  3152. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3153. if (mCurMethodInstance != NULL)
  3154. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3155. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3156. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3157. if (sHadReentrancy)
  3158. fullError += "\nError had reentrancy";
  3159. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3160. }
  3161. void BfModule::FatalError(const StringImpl& error, BfFailHandleKind failHandleKind)
  3162. {
  3163. if (failHandleKind == BfFailHandleKind_Normal)
  3164. FatalError(error);
  3165. else if (failHandleKind == BfFailHandleKind_Soft)
  3166. InternalError(error);
  3167. }
  3168. void BfModule::InternalError(const StringImpl& error, BfAstNode* refNode, const char* file, int line)
  3169. {
  3170. static bool isInside = false;
  3171. if (isInside)
  3172. return;
  3173. isInside = true;
  3174. String fullError = error;
  3175. if (file != NULL)
  3176. fullError += StrFormat(" at %s:%d", file, line);
  3177. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  3178. if (mCurTypeInstance != NULL)
  3179. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  3180. if (mCurMethodInstance != NULL)
  3181. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  3182. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  3183. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  3184. Fail(String("INTERNAL ERROR: ") + fullError, refNode);
  3185. isInside = false;
  3186. }
  3187. void BfModule::NotImpl(BfAstNode* astNode)
  3188. {
  3189. Fail("INTERNAL ERROR: Not implemented", astNode);
  3190. }
  3191. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3192. {
  3193. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3194. if (!allowPrivate)
  3195. allowPrivate |= memberType->IsInterface();
  3196. bool allowProtected = allowPrivate;
  3197. //TODO: We had this commented out, but this makes accessing protected properties fail
  3198. if (mCurTypeInstance != NULL)
  3199. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3200. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3201. {
  3202. return false;
  3203. }
  3204. return true;
  3205. }
  3206. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3207. {
  3208. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3209. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3210. auto memberTypeInstance = memberType->ToTypeInstance();
  3211. if (memberTypeInstance == NULL)
  3212. {
  3213. auto underlyingType = memberType->GetUnderlyingType();
  3214. if (underlyingType != NULL)
  3215. return CheckDefineMemberProtection(protection, underlyingType);
  3216. return true;
  3217. }
  3218. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3219. return false;
  3220. if (memberTypeInstance->IsGenericTypeInstance())
  3221. {
  3222. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3223. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3224. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3225. {
  3226. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3227. return false;
  3228. }
  3229. }
  3230. return true;
  3231. }
  3232. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3233. {
  3234. if (usedType == userType)
  3235. return;
  3236. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3237. {
  3238. // This can be an `int32[UsedType.cVal]` type reference
  3239. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3240. }
  3241. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3242. {
  3243. if (userType->IsMethodRef())
  3244. {
  3245. // We cannot short-circuit dependencies because of method group ref counting
  3246. }
  3247. else
  3248. return;
  3249. }
  3250. if (usedType->IsSpecializedByAutoCompleteMethod())
  3251. {
  3252. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_MethodGenericArg |
  3253. BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3254. return;
  3255. }
  3256. // if (usedType->IsBoxed())
  3257. // {
  3258. // NOP;
  3259. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3260. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3261. // {
  3262. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3263. // }
  3264. // }
  3265. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3266. // BfType* origUsedType = usedType;
  3267. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3268. // if (isDataAccess)
  3269. // {
  3270. // while (true)
  3271. // {
  3272. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3273. // usedType = usedType->GetUnderlyingType();
  3274. // else if (usedType->IsArray())
  3275. // {
  3276. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3277. // }
  3278. // else
  3279. // break;
  3280. // }
  3281. // }
  3282. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3283. {
  3284. bool addType = true;
  3285. auto checkType = usedType;
  3286. PopulateType(checkType, BfPopulateType_Data);
  3287. if (checkType->IsValuelessType())
  3288. addType = false;
  3289. else if (checkType->IsPrimitiveType())
  3290. addType = false;
  3291. else
  3292. {
  3293. auto checkTypeInst = checkType->ToTypeInstance();
  3294. if (checkTypeInst == NULL)
  3295. {
  3296. addType = false;
  3297. }
  3298. else
  3299. {
  3300. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3301. addType = false;
  3302. }
  3303. }
  3304. if (addType)
  3305. {
  3306. auto checkTypeInst = checkType->ToTypeInstance();
  3307. if (checkTypeInst->mHotTypeData != NULL)
  3308. {
  3309. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3310. BF_ASSERT(hotTypeVersion != NULL);
  3311. if (hotTypeVersion != NULL)
  3312. {
  3313. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3314. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3315. (checkType->IsComposite()))
  3316. isAllocation = true;
  3317. if (isAllocation)
  3318. {
  3319. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3320. }
  3321. else
  3322. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3323. }
  3324. }
  3325. }
  3326. }
  3327. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3328. {
  3329. auto usingModule = userType->GetModule();
  3330. BfModule* usedModule;
  3331. if (usedType->IsFunction())
  3332. {
  3333. if (mCompiler->mFunctionTypeDef != NULL)
  3334. {
  3335. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3336. usedModule = functionType->GetModule();
  3337. }
  3338. }
  3339. else
  3340. usedModule = usedType->GetModule();
  3341. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3342. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3343. {
  3344. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3345. {
  3346. // Not a 'use' dependency
  3347. }
  3348. else
  3349. {
  3350. usingModule->mModuleRefs.Add(usedModule);
  3351. }
  3352. }
  3353. }
  3354. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3355. {
  3356. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3357. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3358. if (genericArg == usedType)
  3359. return;
  3360. }
  3361. auto depFlag = flags;
  3362. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3363. {
  3364. if (usedType->IsDependendType())
  3365. {
  3366. // Cause a rebuild but not an outright deletion of the type
  3367. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3368. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3369. }
  3370. }
  3371. if (usedType->IsTypeAlias())
  3372. {
  3373. auto underlyingType = usedType->GetUnderlyingType();
  3374. if (underlyingType != NULL)
  3375. {
  3376. BfDepContext newDepContext;
  3377. if (depContext == NULL)
  3378. depContext = &newDepContext;
  3379. if (++depContext->mAliasDepth > 8)
  3380. {
  3381. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3382. return; // Circular!
  3383. }
  3384. AddDependency(underlyingType, userType, depFlag);
  3385. }
  3386. }
  3387. else if (!usedType->IsGenericTypeInstance())
  3388. {
  3389. auto underlyingType = usedType->GetUnderlyingType();
  3390. if (underlyingType != NULL)
  3391. AddDependency(underlyingType, userType, depFlag);
  3392. }
  3393. BfDependedType* checkDType = usedType->ToDependedType();
  3394. if (checkDType == NULL)
  3395. return;
  3396. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3397. mContext->MarkAsReferenced(checkDType);
  3398. #ifdef _DEBUG
  3399. // If a MethodRef depends ON US, that means it's a local method that we own
  3400. if (userType->IsMethodRef())
  3401. {
  3402. auto methodRefType = (BfMethodRefType*)userType;
  3403. BF_ASSERT(methodRefType->mOwner == checkDType);
  3404. }
  3405. #endif
  3406. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3407. return;
  3408. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3409. {
  3410. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3411. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3412. {
  3413. AddDependency(genericArg, userType, depFlag);
  3414. }
  3415. }
  3416. if (checkDType->IsTuple())
  3417. {
  3418. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3419. {
  3420. if (field.mDataIdx != -1)
  3421. AddDependency(field.mResolvedType, userType, depFlag);
  3422. }
  3423. }
  3424. }
  3425. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3426. {
  3427. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3428. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3429. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3430. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3431. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3432. {
  3433. if (operatorConstraint.mLeftType != NULL)
  3434. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3435. if (operatorConstraint.mRightType != NULL)
  3436. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3437. }
  3438. if (genericParam->mTypeConstraint != NULL)
  3439. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3440. }
  3441. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3442. {
  3443. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3444. {
  3445. if (methodInstance->mHotMethod == NULL)
  3446. CheckHotMethod(methodInstance, "");
  3447. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3448. if (devirtualized)
  3449. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3450. else
  3451. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3452. }
  3453. }
  3454. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3455. {
  3456. auto checkTypeInst = typeInst;
  3457. while (checkTypeInst != NULL)
  3458. {
  3459. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3460. return true;
  3461. checkTypeInst = checkTypeInst->mBaseType;
  3462. }
  3463. return false;
  3464. }
  3465. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3466. {
  3467. if (mContext->mCurTypeState == NULL)
  3468. return;
  3469. BP_ZONE("PopulateGlobalContainersList");
  3470. BfTypeDef* userTypeDef = GetActiveTypeDef();
  3471. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3472. {
  3473. mContext->mCurTypeState->mGlobalContainers.Clear();
  3474. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3475. {
  3476. BfAtomComposite findStr;
  3477. if (namespaceIdx != -1)
  3478. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3479. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3480. while (typeDefItr)
  3481. {
  3482. auto typeDef = *typeDefItr;
  3483. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3484. {
  3485. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3486. {
  3487. BfGlobalContainerEntry globalEntry;
  3488. globalEntry.mTypeDef = typeDef;
  3489. globalEntry.mTypeInst = NULL;
  3490. typeDef->PopulateMemberSets();
  3491. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3492. }
  3493. }
  3494. else if (!typeDef->mIsPartial)
  3495. {
  3496. //break;
  3497. }
  3498. typeDefItr.MoveToNextHashMatch();
  3499. }
  3500. }
  3501. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3502. }
  3503. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3504. // reifing types
  3505. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3506. {
  3507. if (globalEntry.mTypeInst == NULL)
  3508. {
  3509. bool include = false;
  3510. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3511. include = true;
  3512. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3513. {
  3514. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3515. include = true;
  3516. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3517. include = true;
  3518. }
  3519. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3520. {
  3521. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3522. include = true;
  3523. }
  3524. if (include)
  3525. {
  3526. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3527. if (type != NULL)
  3528. globalEntry.mTypeInst = type->ToTypeInstance();
  3529. }
  3530. }
  3531. }
  3532. }
  3533. BfStaticSearch* BfModule::GetStaticSearch()
  3534. {
  3535. auto activeTypeDef = GetActiveTypeDef();
  3536. BfStaticSearch* staticSearch = NULL;
  3537. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3538. return staticSearch;
  3539. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3540. return staticSearch;
  3541. return NULL;
  3542. }
  3543. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3544. {
  3545. auto activeTypeDef = GetActiveTypeDef();
  3546. BfInternalAccessSet* internalAccessSet = NULL;
  3547. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3548. return internalAccessSet;
  3549. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3550. return internalAccessSet;
  3551. return NULL;
  3552. }
  3553. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3554. {
  3555. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3556. return true;
  3557. if ((mCurMethodInstance != NULL) &&
  3558. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3559. return true;
  3560. auto internalAccessSet = GetInternalAccessSet();
  3561. if (internalAccessSet == NULL)
  3562. return false;
  3563. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3564. {
  3565. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3566. return true;
  3567. }
  3568. for (auto internalType : internalAccessSet->mTypes)
  3569. {
  3570. auto checkTypeDef = usingTypeDef->GetDefinition();
  3571. while (checkTypeDef != NULL)
  3572. {
  3573. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3574. return true;
  3575. checkTypeDef = checkTypeDef->mOuterType;
  3576. }
  3577. }
  3578. return false;
  3579. }
  3580. void PrintUsers(llvm::MDNode* md);
  3581. BfModuleOptions BfModule::GetModuleOptions()
  3582. {
  3583. if (mIsScratchModule)
  3584. return BfModuleOptions();
  3585. if (mModuleOptions != NULL)
  3586. return *mModuleOptions;
  3587. BfModuleOptions moduleOptions;
  3588. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3589. if (mProject != NULL)
  3590. {
  3591. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3592. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3593. }
  3594. auto headModule = this;
  3595. while (headModule->mParentModule != NULL)
  3596. headModule = headModule->mParentModule;
  3597. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3598. if (headModule->mOwnedTypeInstances.size() > 0)
  3599. {
  3600. auto typeInst = headModule->mOwnedTypeInstances[0];
  3601. if (typeInst->mTypeOptionsIdx == -2)
  3602. PopulateType(typeInst);
  3603. if (typeInst->mTypeOptionsIdx != -1)
  3604. {
  3605. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3606. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3607. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3608. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3609. }
  3610. }
  3611. return moduleOptions;
  3612. }
  3613. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3614. {
  3615. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3616. return BfCheckedKind_Unchecked;
  3617. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3618. auto typeOptions = GetTypeOptions();
  3619. if (typeOptions != NULL)
  3620. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3621. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3622. }
  3623. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3624. {
  3625. BF_ASSERT(typeInstance != NULL);
  3626. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3627. return;
  3628. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3629. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  3630. }
  3631. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3632. {
  3633. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3634. return;
  3635. mCompiler->mHasQueuedTypeRebuilds = true;
  3636. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3637. AddFailType(typeInstance);
  3638. }
  3639. void BfModule::CheckAddFailType()
  3640. {
  3641. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3642. // but we still need to add the owning type to the FailTypes list
  3643. //.. OLD:
  3644. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3645. /*if (mCurTypeInstance->mModule != this)
  3646. return;*/
  3647. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3648. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3649. // being recompiled. This forces types with warnings to be recompiled.
  3650. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3651. // constantly warning-aware
  3652. if ((mHadBuildError) ||
  3653. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3654. {
  3655. //mContext->mFailTypes.Add(mCurTypeInstance);
  3656. }
  3657. }
  3658. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3659. {
  3660. if (!mCompiler->IsHotCompile())
  3661. return;
  3662. typeInst->mDirty = true;
  3663. for (auto& dep : typeInst->mDependencyMap)
  3664. {
  3665. auto depType = dep.mKey;
  3666. auto depFlags = dep.mValue.mFlags;
  3667. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3668. {
  3669. MarkDerivedDirty(depType->ToTypeInstance());
  3670. }
  3671. }
  3672. }
  3673. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3674. {
  3675. auto fieldType = fieldInstance->GetResolvedType();
  3676. auto field = fieldInstance->GetFieldDef();
  3677. if (fieldType->IsVar())
  3678. return;
  3679. BfIRValue initValue;
  3680. if (field->mIsConst)
  3681. {
  3682. if (fieldType->IsPointer())
  3683. fieldType = fieldType->GetUnderlyingType();
  3684. }
  3685. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3686. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3687. storageKind = BfIRStorageKind_Export;
  3688. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3689. storageKind = BfIRStorageKind_Import;
  3690. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3691. initValue = GetDefaultValue(fieldType);
  3692. if (fieldInstance->mOwner->IsUnspecializedType())
  3693. {
  3694. // Placeholder
  3695. auto ptrVal = CreatePointerType(fieldType);
  3696. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3697. }
  3698. else
  3699. {
  3700. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3701. StringT<4096> staticVarName;
  3702. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3703. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3704. {
  3705. BfIRType irType;
  3706. if ((fieldInstance->IsAppendedObject()) && (!field->mIsStatic))
  3707. {
  3708. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3709. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3710. }
  3711. else
  3712. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3713. if (fieldType->mSize > 0)
  3714. {
  3715. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3716. irType,
  3717. false,
  3718. BfIRLinkageType_External,
  3719. initValue,
  3720. staticVarName,
  3721. isThreadLocal);
  3722. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3723. if (storageKind != BfIRStorageKind_Normal)
  3724. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3725. BF_ASSERT(globalVar);
  3726. mStaticFieldRefs[fieldInstance] = globalVar;
  3727. }
  3728. }
  3729. }
  3730. }
  3731. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3732. {
  3733. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3734. BfType* fieldType = NULL;
  3735. if (fieldInstance != NULL)
  3736. {
  3737. fieldType = fieldInstance->GetResolvedType();
  3738. if (fieldType == NULL)
  3739. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3740. }
  3741. else
  3742. {
  3743. BF_ASSERT(mCompiler->IsAutocomplete());
  3744. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3745. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3746. {
  3747. fieldType = typeInstance;
  3748. }
  3749. else
  3750. {
  3751. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3752. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3753. if (isLet || isVar)
  3754. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3755. else
  3756. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3757. if (fieldType == NULL)
  3758. fieldType = mContext->mBfObjectType;
  3759. }
  3760. }
  3761. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3762. return;
  3763. if (mContext->mFieldResolveReentrys.size() > 1)
  3764. {
  3765. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3766. {
  3767. String failStr = "Circular data reference detected between the following fields:";
  3768. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3769. {
  3770. if (i > 1)
  3771. failStr += ",";
  3772. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3773. }
  3774. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3775. if (err)
  3776. err->mIsPersistent = true;
  3777. return;
  3778. }
  3779. }
  3780. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3781. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3782. if (fieldInstance == NULL)
  3783. popTypeResolveReentry.Pop();
  3784. auto typeDef = typeInstance->mTypeDef;
  3785. BfIRValue constValue;
  3786. if (fieldDef->mIsExtern)
  3787. {
  3788. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3789. {
  3790. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3791. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3792. }
  3793. if (fieldDef->GetInitializer() != NULL)
  3794. {
  3795. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3796. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3797. }
  3798. }
  3799. else if (fieldDef->GetInitializer() == NULL)
  3800. {
  3801. if (fieldDef->IsEnumCaseEntry())
  3802. {
  3803. if (typeInstance->IsTypedPrimitive())
  3804. {
  3805. BfFieldInstance* prevFieldInstance = NULL;
  3806. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3807. {
  3808. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3809. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3810. {
  3811. prevFieldInstance = checkFieldInst;
  3812. break;
  3813. }
  3814. }
  3815. if (prevFieldInstance == NULL)
  3816. constValue = GetConstValue(0, typeInstance);
  3817. else
  3818. {
  3819. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3820. if (prevFieldInstance->mConstIdx == -1)
  3821. {
  3822. if (!mCompiler->IsAutocomplete())
  3823. AssertErrorState();
  3824. constValue = GetConstValue(0, typeInstance);
  3825. }
  3826. else
  3827. {
  3828. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3829. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3830. }
  3831. }
  3832. }
  3833. }
  3834. else
  3835. {
  3836. Fail("Const requires initializer", fieldDef->GetNameNode());
  3837. }
  3838. }
  3839. else if (mBfIRBuilder != NULL)
  3840. {
  3841. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3842. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3843. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3844. BfMethodState methodState;
  3845. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3846. methodState.mTempKind = BfMethodState::TempKind_Static;
  3847. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3848. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3849. {
  3850. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3851. if (!initValue)
  3852. {
  3853. AssertErrorState();
  3854. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3855. }
  3856. if (fieldInstance != NULL)
  3857. {
  3858. if (fieldType->IsUndefSizedArray())
  3859. {
  3860. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3861. {
  3862. fieldInstance->mResolvedType = initValue.mType;
  3863. }
  3864. }
  3865. else
  3866. fieldInstance->mResolvedType = initValue.mType;
  3867. }
  3868. constValue = initValue.mValue;
  3869. }
  3870. else
  3871. {
  3872. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3873. constValue = uncastedInitValue.mValue;
  3874. }
  3875. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3876. {
  3877. // Illegal
  3878. constValue = BfIRValue();
  3879. }
  3880. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3881. }
  3882. if (fieldInstance != NULL)
  3883. {
  3884. fieldType = fieldInstance->GetResolvedType();
  3885. if ((fieldType == NULL) || (fieldType->IsVar()))
  3886. {
  3887. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3888. AssertErrorState();
  3889. // Default const type is 'int'
  3890. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3891. if (fieldInstance != NULL)
  3892. {
  3893. fieldInstance->mResolvedType = initValue.mType;
  3894. }
  3895. constValue = initValue.mValue;
  3896. }
  3897. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3898. {
  3899. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3900. CurrentAddToConstHolder(constValue);
  3901. fieldInstance->mConstIdx = constValue.mId;
  3902. }
  3903. }
  3904. }
  3905. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3906. {
  3907. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3908. auto fieldType = fieldInstance->GetResolvedType();
  3909. if ((field->mIsConst) && (!isDeclType))
  3910. {
  3911. ResolveConstField(typeInstance, fieldInstance, field);
  3912. return fieldInstance->GetResolvedType();
  3913. }
  3914. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3915. if (!fieldInstance->mIsInferredType)
  3916. return fieldType;
  3917. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3918. return fieldType;
  3919. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3920. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3921. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3922. auto typeDef = typeInstance->mTypeDef;
  3923. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3924. {
  3925. AssertErrorState();
  3926. return fieldType;
  3927. }
  3928. bool hadInferenceCycle = false;
  3929. if (mContext->mFieldResolveReentrys.size() > 1)
  3930. {
  3931. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3932. {
  3933. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3934. {
  3935. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3936. auto fieldDef = fieldInst->GetFieldDef();
  3937. auto fieldOwner = fieldInst->mOwner;
  3938. auto fieldModule = fieldOwner->mModule;
  3939. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3940. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3941. }
  3942. return fieldType;
  3943. }
  3944. }
  3945. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3946. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3947. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3948. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3949. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3950. {
  3951. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3952. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3953. return fieldType;
  3954. }
  3955. BfType* resolvedType = NULL;
  3956. if (!hadInferenceCycle)
  3957. {
  3958. BfTypeState typeState;
  3959. typeState.mPrevState = mContext->mCurTypeState;
  3960. typeState.mType = typeInstance;
  3961. typeState.mCurFieldDef = field;
  3962. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3963. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3964. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3965. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3966. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3967. BfMethodState methodState;
  3968. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3969. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3970. if (!staticOnly)
  3971. {
  3972. //BfLocalVariable localVar;
  3973. //methodState.mLocals.push_back(localVar);
  3974. }
  3975. if (isDeclType)
  3976. {
  3977. auto fieldDef = fieldInstance->GetFieldDef();
  3978. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3979. }
  3980. else
  3981. {
  3982. BfTypedValue valueFromExpr;
  3983. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3984. FixIntUnknown(valueFromExpr);
  3985. if (fieldType->IsUndefSizedArray())
  3986. {
  3987. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3988. resolvedType = valueFromExpr.mType;
  3989. }
  3990. else
  3991. resolvedType = valueFromExpr.mType;
  3992. }
  3993. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3994. }
  3995. if (resolvedType == NULL)
  3996. return fieldType;
  3997. fieldInstance->SetResolvedType(resolvedType);
  3998. if (field->mIsStatic)
  3999. {
  4000. }
  4001. else if (fieldInstance->mDataIdx >= 0)
  4002. {
  4003. }
  4004. else
  4005. {
  4006. BF_ASSERT(typeInstance->IsIncomplete());
  4007. }
  4008. return resolvedType;
  4009. }
  4010. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  4011. {
  4012. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  4013. auto fieldType = fieldInstance->GetResolvedType();
  4014. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  4015. {
  4016. int fieldIdx = 0;
  4017. int fieldCount = 0;
  4018. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  4019. fieldIdx--;
  4020. int count = fieldCount;
  4021. if (fieldIdx == -1)
  4022. count = 1;
  4023. //TODO: Under what circumstances could 'thisVariable' be NULL?
  4024. auto thisVariable = GetThisVariable();
  4025. if (thisVariable != NULL)
  4026. {
  4027. for (int i = 0; i < count; i++)
  4028. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  4029. }
  4030. }
  4031. }
  4032. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  4033. {
  4034. if (fieldInstance->mCustomAttributes == NULL)
  4035. return false;
  4036. auto fieldDef = fieldInstance->GetFieldDef();
  4037. if (!fieldDef->mIsStatic)
  4038. return false;
  4039. bool isThreadLocal = false;
  4040. if (fieldInstance->mCustomAttributes != NULL)
  4041. {
  4042. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4043. {
  4044. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  4045. return true;
  4046. }
  4047. }
  4048. return false;
  4049. }
  4050. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  4051. {
  4052. if (fieldDef == NULL)
  4053. fieldDef = fieldInstance->GetFieldDef();
  4054. if (fieldType == NULL)
  4055. fieldType = fieldInstance->GetResolvedType();
  4056. if (initializer == NULL)
  4057. {
  4058. if (fieldDef == NULL)
  4059. return BfTypedValue();
  4060. initializer = fieldDef->GetInitializer();
  4061. }
  4062. BfTypedValue staticVarRef;
  4063. BfTypedValue result;
  4064. if (initializer == NULL)
  4065. {
  4066. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  4067. }
  4068. else
  4069. {
  4070. if (mCompiler->mIsResolveOnly)
  4071. {
  4072. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  4073. {
  4074. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  4075. sourceClassifier->VisitChildNoRef(initializer);
  4076. }
  4077. }
  4078. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  4079. {
  4080. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  4081. BfConstResolver constResolver(this);
  4082. constResolver.Resolve(initializer);
  4083. return GetDefaultTypedValue(fieldType);
  4084. }
  4085. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  4086. {
  4087. return GetDefaultTypedValue(fieldType);
  4088. }
  4089. else if (fieldDef->mIsConst)
  4090. {
  4091. int ceExecuteId = -1;
  4092. if (mCompiler->mCeMachine != NULL)
  4093. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  4094. BfTypeState typeState;
  4095. typeState.mType = mCurTypeInstance;
  4096. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  4097. typeState.mCurFieldDef = fieldDef;
  4098. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4099. BfConstResolver constResolver(this);
  4100. if (fieldType->IsVar())
  4101. return constResolver.Resolve(initializer);
  4102. else
  4103. {
  4104. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  4105. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  4106. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  4107. {
  4108. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  4109. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  4110. resolveFlags = BfConstResolveFlag_NoCast;
  4111. }
  4112. if ((mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()))
  4113. resolveFlags = (BfConstResolveFlags)(resolveFlags | BfConstResolveFlag_NoConversionOperator | BfConstResolveFlag_ExplicitCast);
  4114. UpdateSrcPos(initializer);
  4115. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  4116. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  4117. {
  4118. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  4119. fieldInstance->mHadConstEval = true;
  4120. }
  4121. if (auto autoComplete = mCompiler->GetAutoComplete())
  4122. autoComplete->CheckResult(initializer, result);
  4123. return result;
  4124. }
  4125. }
  4126. BfExprEvaluator exprEvaluator(this);
  4127. if (doStore)
  4128. {
  4129. staticVarRef = ReferenceStaticField(fieldInstance);
  4130. exprEvaluator.mReceivingValue = &staticVarRef;
  4131. }
  4132. if (fieldType->IsDeleting())
  4133. {
  4134. mCompiler->RequestExtraCompile();
  4135. InternalError("Field using deleted type", fieldDef->GetRefNode());
  4136. }
  4137. else if (fieldType->IsVar())
  4138. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4139. else
  4140. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  4141. if (doStore)
  4142. {
  4143. if (exprEvaluator.mReceivingValue == NULL)
  4144. doStore = false; // Already stored
  4145. }
  4146. }
  4147. if (fieldInstance != NULL)
  4148. MarkFieldInitialized(fieldInstance);
  4149. if ((doStore) && (result))
  4150. {
  4151. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  4152. {
  4153. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  4154. AssertErrorState();
  4155. }
  4156. else
  4157. {
  4158. result = LoadValue(result);
  4159. if (!result.mType->IsValuelessType())
  4160. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  4161. }
  4162. }
  4163. return result;
  4164. }
  4165. bool BfModule::TryGetAppendedObjectInfo(BfFieldInstance* fieldInstance, int& dataSize, int& alignSize)
  4166. {
  4167. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4168. auto fieldDef = fieldInstance->GetFieldDef();
  4169. BfAstNode* nameRefNode = NULL;
  4170. if (auto fieldDecl = fieldDef->GetFieldDeclaration())
  4171. nameRefNode = fieldDecl->mNameNode;
  4172. else if (auto paramDecl = fieldDef->GetParamDeclaration())
  4173. nameRefNode = paramDecl->mNameNode;
  4174. if (nameRefNode == NULL)
  4175. nameRefNode = fieldDef->mTypeRef;
  4176. dataSize = resolvedFieldType->mSize;
  4177. alignSize = resolvedFieldType->mAlign;
  4178. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4179. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_FieldType);
  4180. PopulateType(resolvedFieldType, BfPopulateType_Data);
  4181. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  4182. dataSize = BF_MAX(fieldTypeInst->mInstSize, 0);
  4183. alignSize = BF_MAX(fieldTypeInst->mInstAlign, 1);
  4184. if (fieldTypeInst->mTypeFailed)
  4185. {
  4186. TypeFailed(fieldTypeInst);
  4187. fieldInstance->mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  4188. return false;
  4189. }
  4190. if ((fieldTypeInst != NULL) && (fieldTypeInst->mTypeDef->mIsAbstract))
  4191. {
  4192. Fail("Cannot create an instance of an abstract class", nameRefNode);
  4193. }
  4194. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  4195. BfMethodState methodState;
  4196. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4197. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  4198. BfTypedValue appendIndexValue;
  4199. BfExprEvaluator exprEvaluator(this);
  4200. BfResolvedArgs resolvedArgs;
  4201. auto fieldDecl = fieldDef->GetFieldDeclaration();
  4202. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(fieldDecl->mInitializer))
  4203. {
  4204. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4205. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4206. }
  4207. BfFunctionBindResult bindResult;
  4208. bindResult.mSkipThis = true;
  4209. bindResult.mWantsArgs = true;
  4210. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  4211. BfTypedValue emptyThis(mBfIRBuilder->GetFakeVal(), mCurTypeInstance, mCurTypeInstance->IsStruct());
  4212. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_Comptime;
  4213. auto ctorResult = exprEvaluator.MatchConstructor(nameRefNode, NULL, emptyThis, fieldTypeInst, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer);
  4214. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->HasAppend()))
  4215. {
  4216. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  4217. SizedArray<BfIRValue, 2> irArgs;
  4218. if (bindResult.mIRArgs.size() > 1)
  4219. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  4220. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs, true);
  4221. if (appendSizeTypedValue)
  4222. {
  4223. int appendAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  4224. dataSize = BF_ALIGN(dataSize, appendAlign);
  4225. alignSize = BF_MAX(alignSize, appendAlign);
  4226. auto constant = mBfIRBuilder->GetConstant(appendSizeTypedValue.mValue);
  4227. if (constant != NULL)
  4228. {
  4229. dataSize += constant->mInt32;
  4230. }
  4231. }
  4232. else
  4233. {
  4234. Fail(StrFormat("Append constructor '%s' does not result in a constant size", MethodToString(bindResult.mMethodInstance).c_str()), nameRefNode);
  4235. }
  4236. }
  4237. return true;
  4238. }
  4239. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  4240. {
  4241. BfExprEvaluator exprEvaluator(this);
  4242. bool failed = false;
  4243. auto fieldDef = fieldInst->GetFieldDef();
  4244. auto initializer = fieldDef->GetInitializer();
  4245. BfResolvedArgs resolvedArgs;
  4246. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  4247. {
  4248. bool isDot = false;
  4249. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4250. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  4251. if (!isDot)
  4252. {
  4253. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  4254. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  4255. failed = true;
  4256. }
  4257. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  4258. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4259. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4260. }
  4261. else if (initializer != NULL)
  4262. {
  4263. GetFieldInitializerValue(fieldInst);
  4264. failed = true;
  4265. }
  4266. if (failed)
  4267. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  4268. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4269. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4270. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4271. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4272. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4273. BfIRValue fieldAddr;
  4274. if (fieldDef->mIsStatic)
  4275. {
  4276. auto fieldTypedValue = ReferenceStaticField(fieldInst);
  4277. int dataSize = 1;
  4278. int alignSize = 1;
  4279. TryGetAppendedObjectInfo(fieldInst, dataSize, alignSize);
  4280. String dataName;
  4281. BfMangler::MangleStaticFieldName(dataName, mCompiler->GetMangleKind(), mCurTypeInstance, fieldDef->mName, fieldInst->mResolvedType);
  4282. dataName += "__DATA";
  4283. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize);
  4284. auto globalVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8), dataSize), false,
  4285. BfIRLinkageType_Internal, mBfIRBuilder->CreateConstArrayZero(dataSize), dataName);
  4286. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, alignSize);
  4287. auto castedVal = mBfIRBuilder->CreateBitCast(globalVar, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  4288. mBfIRBuilder->CreateStore(castedVal, fieldTypedValue.mValue);
  4289. fieldTypedValue = LoadValue(fieldTypedValue);
  4290. fieldAddr = fieldTypedValue.mValue;
  4291. }
  4292. else
  4293. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4294. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4295. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4296. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4297. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4298. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4299. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4300. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4301. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4302. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4303. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4304. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4305. {
  4306. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4307. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4308. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4309. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4310. }
  4311. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_Infer, &indexVal);
  4312. }
  4313. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4314. {
  4315. }
  4316. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4317. {
  4318. PopulateType(classType);
  4319. if (isInterfacePass)
  4320. {
  4321. for (auto ifaceInst : classType->mInterfaces)
  4322. {
  4323. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4324. continue;
  4325. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4326. continue;
  4327. if (ifaceInst.mDeclaringType->IsExtension())
  4328. {
  4329. bool needsExCheck = false;
  4330. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4331. {
  4332. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4333. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4334. {
  4335. exChecks->push_back(ifaceInst.mInterfaceType);
  4336. continue;
  4337. }
  4338. else
  4339. {
  4340. // We can only do an 'exCheck' if we're actually going to slot this interface
  4341. }
  4342. }
  4343. }
  4344. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4345. }
  4346. }
  4347. else
  4348. {
  4349. outVals->push_back(classType->mTypeId);
  4350. }
  4351. if (classType->mBaseType != NULL)
  4352. {
  4353. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4354. }
  4355. }
  4356. void BfModule::CreateDynamicCastMethod()
  4357. {
  4358. auto objType = mContext->mBfObjectType;
  4359. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4360. {
  4361. // The main reason to punt on this method for ResolveOnly is because types can be created
  4362. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4363. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4364. // remove this punt when we recycle typeId's
  4365. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4366. mCurMethodState->mHadReturn = true;
  4367. return;
  4368. }
  4369. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4370. auto func = mCurMethodState->mIRFunction;
  4371. auto thisValue = mBfIRBuilder->GetArgument(0);
  4372. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4373. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4374. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4375. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4376. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4377. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4378. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4379. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4380. SizedArray<int, 8> typeMatches;
  4381. SizedArray<BfTypeInstance*, 8> exChecks;
  4382. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4383. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4384. {
  4385. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4386. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4387. BfTypeVector genericArgs;
  4388. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4389. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4390. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4391. typeMatches.push_back(unboundType->mTypeId);
  4392. }
  4393. if (mCurTypeInstance->IsBoxed())
  4394. {
  4395. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4396. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4397. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4398. if (innerType->IsTypedPrimitive())
  4399. {
  4400. auto underlyingType = innerType->GetUnderlyingType();
  4401. typeMatches.push_back(underlyingType->mTypeId);
  4402. }
  4403. auto innerTypeInst = innerType->ToTypeInstance();
  4404. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4405. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4406. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4407. {
  4408. PopulateType(innerTypeInst);
  4409. //TODO: What case was this supposed to handle?
  4410. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4411. }
  4412. }
  4413. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4414. BfIRValue vDataPtr;
  4415. if (!exChecks.empty())
  4416. {
  4417. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4418. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4419. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4420. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4421. }
  4422. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4423. for (auto typeMatch : typeMatches)
  4424. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4425. Array<BfIRValue> incomingFalses;
  4426. for (auto ifaceTypeInst : exChecks)
  4427. {
  4428. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4429. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4430. mBfIRBuilder->SetInsertPoint(nextBB);
  4431. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4432. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4433. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4434. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4435. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4436. incomingFalses.push_back(nextBB);
  4437. }
  4438. mBfIRBuilder->AddBlock(trueBB);
  4439. mBfIRBuilder->SetInsertPoint(trueBB);
  4440. mBfIRBuilder->CreateBr(exitBB);
  4441. mBfIRBuilder->AddBlock(exitBB);
  4442. mBfIRBuilder->SetInsertPoint(exitBB);
  4443. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4444. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4445. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4446. for (auto incomingFalseBlock : incomingFalses)
  4447. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4448. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4449. mBfIRBuilder->CreateRet(phi);
  4450. mCurMethodState->mHadReturn = true;
  4451. }
  4452. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4453. {
  4454. BfExprEvaluator exprEvaluator(this);
  4455. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4456. auto typeInst = rightValue.mType->ToTypeInstance();
  4457. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4458. BfTypedValue result = exprEvaluator.GetResult();
  4459. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4460. {
  4461. // Fail?
  4462. }
  4463. if ((result) && (!result.mType->IsVar()))
  4464. {
  4465. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4466. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4467. mBfIRBuilder->AddBlock(nextBB);
  4468. mBfIRBuilder->SetInsertPoint(nextBB);
  4469. }
  4470. }
  4471. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4472. {
  4473. if (mCurMethodInstance->mHasFailed)
  4474. return;
  4475. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4476. return;
  4477. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4478. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4479. SizedArray<BfIRType, 4> paramTypes;
  4480. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4481. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4482. mBfIRBuilder->SetActiveFunction(func);
  4483. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4484. mBfIRBuilder->SetInsertPoint(entryBlock);
  4485. BfMethodState methodState;
  4486. methodState.mIRHeadBlock = entryBlock;
  4487. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4488. SizedArray<BfIRValue, 8> args;
  4489. BfExprEvaluator exprEvaluator(this);
  4490. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4491. {
  4492. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4493. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4494. }
  4495. if (mCurMethodInstance->HasThis())
  4496. {
  4497. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4498. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4499. }
  4500. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4501. {
  4502. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4503. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4504. }
  4505. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4506. {
  4507. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4508. if (paramType->IsValuelessType())
  4509. continue;
  4510. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4511. }
  4512. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4513. mBfIRBuilder->CreateRetVoid();
  4514. }
  4515. void BfModule::CreateDelegateEqualsMethod()
  4516. {
  4517. if (mBfIRBuilder->mIgnoreWrites)
  4518. return;
  4519. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4520. if (refNode == NULL)
  4521. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4522. UpdateSrcPos(refNode);
  4523. SetIllegalSrcPos();
  4524. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4525. auto resultVal = CreateAlloca(boolType);
  4526. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4527. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4528. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4529. mBfIRBuilder->PopulateType(delegateType);
  4530. BfExprEvaluator exprEvaluator(this);
  4531. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4532. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4533. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4534. rhsDelegate = LoadValue(rhsDelegate);
  4535. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4536. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4537. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4538. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4539. leftValue = LoadValue(leftValue);
  4540. rightValue = LoadValue(rightValue);
  4541. EmitEquals(leftValue, rightValue, exitBB, false);
  4542. bool hadComparison = false;
  4543. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4544. {
  4545. BfFieldInstance* fieldInstance = &fieldRef;
  4546. if (fieldInstance->mDataOffset == -1)
  4547. continue;
  4548. auto fieldType = fieldInstance->mResolvedType;
  4549. if (fieldType->IsValuelessType())
  4550. continue;
  4551. if (fieldType->IsVar())
  4552. continue;
  4553. if (fieldType->IsMethodRef())
  4554. continue;
  4555. if (fieldType->IsRef())
  4556. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4557. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4558. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4559. if (!fieldInstance->mResolvedType->IsComposite())
  4560. {
  4561. leftValue = LoadValue(leftValue);
  4562. rightValue = LoadValue(rightValue);
  4563. }
  4564. EmitEquals(leftValue, rightValue, exitBB, false);
  4565. }
  4566. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4567. mBfIRBuilder->CreateBr(exitBB);
  4568. mBfIRBuilder->AddBlock(exitBB);
  4569. mBfIRBuilder->SetInsertPoint(exitBB);
  4570. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4571. ClearLifetimeEnds();
  4572. mBfIRBuilder->CreateRet(loadedResult);
  4573. mCurMethodState->mHadReturn = true;
  4574. }
  4575. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4576. {
  4577. if (mCurMethodInstance->mIsUnspecialized)
  4578. return;
  4579. if (mBfIRBuilder->mIgnoreWrites)
  4580. return;
  4581. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4582. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4583. bool isValid = true;
  4584. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4585. if (compareType->IsValuelessType())
  4586. {
  4587. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4588. return;
  4589. }
  4590. if (compareType->IsTypedPrimitive())
  4591. {
  4592. BfExprEvaluator exprEvaluator(this);
  4593. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4594. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4595. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4596. mBfIRBuilder->CreateRet(cmpResult);
  4597. return;
  4598. }
  4599. auto compareDType = compareType->ToDependedType();
  4600. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4601. if (compareTypeInst != NULL)
  4602. {
  4603. if (compareType->IsPrimitiveType())
  4604. compareTypeInst = GetWrappedStructType(compareType);
  4605. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4606. {
  4607. isValid = false;
  4608. }
  4609. mBfIRBuilder->PopulateType(compareTypeInst);
  4610. }
  4611. if (!isValid)
  4612. {
  4613. ClearLifetimeEnds();
  4614. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4615. return;
  4616. }
  4617. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4618. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4619. if (refNode == NULL)
  4620. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4621. UpdateSrcPos(refNode);
  4622. SetIllegalSrcPos();
  4623. auto resultVal = CreateAlloca(boolType);
  4624. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4625. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4626. if (compareType->IsValuelessType())
  4627. {
  4628. // Always equal, nothing to do
  4629. }
  4630. else if (compareType->IsSizedArray())
  4631. {
  4632. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4633. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4634. {
  4635. BfTypedValue result;
  4636. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4637. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4638. if (!result.mType->IsValueType())
  4639. result = LoadValue(result);
  4640. return result;
  4641. };
  4642. if (sizedArrayType->mElementCount > 6)
  4643. {
  4644. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4645. auto itr = CreateAlloca(intPtrType);
  4646. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4647. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4648. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4649. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4650. mBfIRBuilder->CreateBr(loopBB);
  4651. mBfIRBuilder->SetInsertPoint(loopBB);
  4652. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4653. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4654. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4655. mBfIRBuilder->SetInsertPoint(bodyBB);
  4656. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4657. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4658. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4659. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4660. mBfIRBuilder->CreateStore(incValue, itr);
  4661. mBfIRBuilder->CreateBr(loopBB);
  4662. mBfIRBuilder->SetInsertPoint(doneBB);
  4663. }
  4664. else
  4665. {
  4666. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4667. {
  4668. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4669. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4670. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4671. }
  4672. }
  4673. }
  4674. else if (compareType->IsMethodRef())
  4675. {
  4676. auto methodRefType = (BfMethodRefType*)compareType;
  4677. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4678. BfExprEvaluator exprEvaluator(this);
  4679. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4680. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4681. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4682. // values for the same method reference -- they will always refer back to the same local variables.
  4683. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4684. if (dataIdx != -1)
  4685. {
  4686. bool failed = false;
  4687. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4688. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4689. BF_ASSERT(!failed);
  4690. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4691. }
  4692. }
  4693. else if (compareTypeInst->IsEnum())
  4694. {
  4695. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4696. BfExprEvaluator exprEvaluator(this);
  4697. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4698. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4699. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4700. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4701. leftValue = LoadValue(leftValue);
  4702. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4703. rightValue = LoadValue(rightValue);
  4704. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4705. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4706. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4707. int enumCount = 0;
  4708. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4709. {
  4710. BfFieldInstance* fieldInstance = &fieldRef;
  4711. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4712. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4713. {
  4714. enumCount = -fieldInstance->mDataIdx;
  4715. }
  4716. }
  4717. if (enumCount > 0)
  4718. {
  4719. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4720. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4721. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4722. {
  4723. BfFieldInstance* fieldInstance = &fieldRef;
  4724. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4725. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4726. {
  4727. int enumIdx = -fieldInstance->mDataIdx - 1;
  4728. if (fieldInstance->mResolvedType->mSize == 0)
  4729. {
  4730. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4731. }
  4732. else
  4733. {
  4734. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4735. mBfIRBuilder->SetInsertPoint(caseBlock);
  4736. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4737. BfTypedValue leftTuple;
  4738. BfTypedValue rightTuple;
  4739. if (leftPayload.IsAddr())
  4740. {
  4741. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4742. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4743. }
  4744. else
  4745. {
  4746. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4747. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4748. }
  4749. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4750. mBfIRBuilder->CreateBr(matchedBlock);
  4751. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4752. }
  4753. }
  4754. }
  4755. mBfIRBuilder->AddBlock(matchedBlock);
  4756. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4757. }
  4758. }
  4759. else if (compareTypeInst->IsUnion())
  4760. {
  4761. auto innerType = compareTypeInst->GetUnionInnerType();
  4762. if (!innerType->IsValuelessType())
  4763. {
  4764. BfExprEvaluator exprEvaluator(this);
  4765. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4766. leftTypedVal = AggregateSplat(leftTypedVal);
  4767. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4768. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4769. rightTypedVal = AggregateSplat(rightTypedVal);
  4770. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4771. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4772. }
  4773. }
  4774. else
  4775. {
  4776. BfExprEvaluator exprEvaluator(this);
  4777. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4778. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4779. bool hadComparison = false;
  4780. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4781. {
  4782. BfFieldInstance* fieldInstance = &fieldRef;
  4783. if (fieldInstance->mDataOffset == -1)
  4784. continue;
  4785. if (fieldInstance->mResolvedType->IsValuelessType())
  4786. continue;
  4787. if (fieldInstance->mResolvedType->IsVar())
  4788. continue;
  4789. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4790. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4791. if (!fieldInstance->mResolvedType->IsComposite())
  4792. {
  4793. leftValue = LoadValue(leftValue);
  4794. rightValue = LoadValue(rightValue);
  4795. }
  4796. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4797. }
  4798. auto baseTypeInst = compareTypeInst->mBaseType;
  4799. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4800. {
  4801. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4802. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4803. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4804. }
  4805. }
  4806. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4807. mBfIRBuilder->CreateBr(exitBB);
  4808. mBfIRBuilder->AddBlock(exitBB);
  4809. mBfIRBuilder->SetInsertPoint(exitBB);
  4810. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4811. ClearLifetimeEnds();
  4812. mBfIRBuilder->CreateRet(loadedResult);
  4813. mCurMethodState->mHadReturn = true;
  4814. }
  4815. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4816. {
  4817. if (mBfIRBuilder->mIgnoreWrites)
  4818. return mBfIRBuilder->GetFakeVal();
  4819. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4820. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4821. if (mIsComptimeModule)
  4822. {
  4823. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4824. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4825. }
  4826. BfIRValue* globalVariablePtr = NULL;
  4827. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4828. int numElements = 1;
  4829. if (mSystem->mPtrSize == 4)
  4830. numElements++;
  4831. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4832. {
  4833. numElements += mCompiler->mMaxInterfaceSlots;
  4834. auto maxIFaceVirtIdx = 0;
  4835. if (!typeInstance->IsInterface())
  4836. {
  4837. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4838. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4839. numElements += typeInstance->GetOrigVTableSize();
  4840. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4841. if (typeInstance->mHotTypeData != NULL)
  4842. {
  4843. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4844. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4845. }
  4846. numElements += ifaceMethodLen;
  4847. }
  4848. if (outNumElements != NULL)
  4849. *outNumElements = numElements;
  4850. }
  4851. StringT<128> classVDataName;
  4852. String memberName = "sBfClassVData";
  4853. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4854. {
  4855. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4856. memberName += "_";
  4857. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4858. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4859. }
  4860. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4861. if (outMangledName != NULL)
  4862. *outMangledName = classVDataName;
  4863. BfIRValue globalVariable;
  4864. if (globalVariablePtr != NULL)
  4865. {
  4866. globalVariable = *globalVariablePtr;
  4867. }
  4868. else
  4869. {
  4870. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4871. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4872. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4873. arrayType,
  4874. true,
  4875. BfIRLinkageType_External,
  4876. BfIRValue(),
  4877. classVDataName);
  4878. mClassVDataRefs[typeInstance] = globalVariable;
  4879. }
  4880. return globalVariable;
  4881. }
  4882. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4883. {
  4884. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4885. if (mIsComptimeModule)
  4886. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4887. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4888. }
  4889. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4890. {
  4891. if (mBfIRBuilder->mIgnoreWrites)
  4892. return mBfIRBuilder->GetFakeVal();
  4893. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4894. if (numElements < 0)
  4895. InternalError("CreateClassVDataExtGlobal numElements < 0");
  4896. if (numElements <= 0)
  4897. return BfIRValue();
  4898. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4899. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4900. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4901. BF_ASSERT(declTypeInst == implTypeInst);
  4902. else
  4903. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4904. if (declTypeInst != implTypeInst)
  4905. {
  4906. BfTypeInstance* highestImpl = declTypeInst;
  4907. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4908. {
  4909. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4910. break; // Start of an ext entry for another type
  4911. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4912. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4913. highestImpl = checkImplTypeInst;
  4914. }
  4915. if (highestImpl != implTypeInst)
  4916. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4917. }
  4918. BfVDataExtEntry mapEntry;
  4919. mapEntry.mDeclTypeInst = declTypeInst;
  4920. mapEntry.mImplTypeInst = implTypeInst;
  4921. BfIRValue* irValuePtr = NULL;
  4922. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4923. return *irValuePtr;
  4924. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4925. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4926. StringT<512> classVDataName;
  4927. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4928. if (declTypeInst != implTypeInst)
  4929. {
  4930. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4931. }
  4932. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4933. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4934. SizedArray<BfIRValue, 32> vData;
  4935. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4936. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4937. {
  4938. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4939. break; // Start of an ext entry for another type
  4940. BfIRValue vValue;
  4941. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4942. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4943. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4944. {
  4945. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4946. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4947. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4948. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4949. {
  4950. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4951. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4952. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4953. vValue = funcPtr;
  4954. }
  4955. }
  4956. if (!vValue)
  4957. vValue = voidPtrNull;
  4958. vData.Add(vValue);
  4959. }
  4960. BF_ASSERT((int)vData.size() == numElements);
  4961. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4962. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4963. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4964. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4965. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4966. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4967. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4968. mClassVDataExtRefs[mapEntry] = globalVariable;
  4969. return globalVariable;
  4970. }
  4971. BfIRValue BfModule::CreateTypeDataRef(BfType* type, bool forceConstant)
  4972. {
  4973. if (mBfIRBuilder->mIgnoreWrites)
  4974. {
  4975. return mBfIRBuilder->CreateTypeOf(type);
  4976. }
  4977. if (mIsComptimeModule)
  4978. {
  4979. if (forceConstant)
  4980. return mBfIRBuilder->CreateTypeOfComptime(type);
  4981. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4982. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4983. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4984. }
  4985. PopulateType(type);
  4986. BfIRValue globalVariable;
  4987. BfIRValue* globalVariablePtr = NULL;
  4988. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4989. {
  4990. if (*globalVariablePtr)
  4991. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4992. }
  4993. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4994. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4995. auto typeInstance = type->ToTypeInstance();
  4996. StringT<4096> typeDataName;
  4997. if (typeInstance != NULL)
  4998. {
  4999. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5000. }
  5001. else
  5002. {
  5003. typeDataName += "sBfTypeData.";
  5004. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  5005. }
  5006. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  5007. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  5008. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  5009. mTypeDataRefs[type] = globalVariable;
  5010. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  5011. }
  5012. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  5013. {
  5014. #define PUSH_INT8(val) data.push_back((uint8)val)
  5015. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5016. #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); }
  5017. #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); \
  5018. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  5019. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  5020. bool handled = false;
  5021. if (constant == NULL)
  5022. {
  5023. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5024. return;
  5025. }
  5026. if (argType->IsObject())
  5027. {
  5028. if ((argType->IsInstanceOf(mCompiler->mStringTypeDef)) || (argType == mContext->mBfObjectType))
  5029. {
  5030. if (constant->mTypeCode == BfTypeCode_StringId)
  5031. {
  5032. int stringId = constant->mInt32;
  5033. int* orderedIdPtr;
  5034. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5035. {
  5036. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5037. }
  5038. GetStringObjectValue(stringId, true, true);
  5039. PUSH_INT8(0xFF); // String
  5040. PUSH_INT32(*orderedIdPtr);
  5041. return;
  5042. }
  5043. }
  5044. }
  5045. if (argType->IsPointer())
  5046. {
  5047. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  5048. {
  5049. if (constant->mTypeCode == BfTypeCode_StringId)
  5050. {
  5051. int stringId = constant->mInt32;
  5052. int* orderedIdPtr;
  5053. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5054. {
  5055. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5056. }
  5057. GetStringObjectValue(stringId, true, true);
  5058. PUSH_INT8(0xFF); // String
  5059. PUSH_INT32(*orderedIdPtr);
  5060. return;
  5061. }
  5062. }
  5063. }
  5064. if (constant->mConstType == BfConstType_BitCastNull)
  5065. {
  5066. PUSH_INT8(BfTypeCode_NullPtr);
  5067. return;
  5068. }
  5069. if (constant->mConstType == BfConstType_BitCast)
  5070. {
  5071. auto bitcast = (BfConstantBitCast*)constant;
  5072. EncodeAttributeData(typeInstance, argType, BfIRValue(BfIRValueFlags_Const, bitcast->mTarget), data, usedStringIdMap);
  5073. return;
  5074. }
  5075. PUSH_INT8(constant->mTypeCode);
  5076. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  5077. (constant->mTypeCode == BfTypeCode_UInt64) ||
  5078. (constant->mTypeCode == BfTypeCode_Double))
  5079. {
  5080. PUSH_INT64(constant->mInt64);
  5081. }
  5082. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5083. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5084. (constant->mTypeCode == BfTypeCode_Char32))
  5085. {
  5086. PUSH_INT32(constant->mInt32);
  5087. }
  5088. else if (constant->mTypeCode == BfTypeCode_Float)
  5089. {
  5090. float val = (float)constant->mDouble;
  5091. PUSH_INT32(*(int*)&val);
  5092. }
  5093. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5094. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5095. (constant->mTypeCode == BfTypeCode_Char16))
  5096. {
  5097. PUSH_INT16(constant->mInt16);
  5098. }
  5099. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5100. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5101. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5102. (constant->mTypeCode == BfTypeCode_Char8))
  5103. {
  5104. PUSH_INT8(constant->mInt8);
  5105. }
  5106. else if (constant->mConstType == BfConstType_TypeOf)
  5107. {
  5108. auto typeOf = (BfTypeOf_Const*)constant;
  5109. PUSH_INT32(typeOf->mType->mTypeId);
  5110. }
  5111. else if (constant->mConstType == BfConstType_AggZero)
  5112. {
  5113. for (int i = 0; i < argType->mSize; i++)
  5114. data.Add(0);
  5115. }
  5116. else if (constant->mConstType == BfConstType_Box)
  5117. {
  5118. auto box = (BfConstantBox*)constant;
  5119. PUSH_INT32(box->mToType.mId);
  5120. BfType* resultType = NULL;
  5121. if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5122. resultType = mContext->FindTypeById(box->mToType.mId);
  5123. if ((resultType != NULL) && (resultType->IsBoxed()))
  5124. {
  5125. auto boxedType = (BfBoxedType*)resultType;
  5126. int dataOffset = 0;
  5127. if (!boxedType->mFieldInstances.IsEmpty())
  5128. dataOffset = BF_MAX(boxedType->mFieldInstances.back().mDataOffset, 0);
  5129. int dataSize = boxedType->mInstSize - dataOffset;
  5130. for (int i = 0; i < dataSize; i++)
  5131. data.Add(0);
  5132. typeInstance->mConstHolder->WriteConstant(BfIRValue(BfIRValueFlags_Const, box->mTarget), &data[data.mSize - dataSize], boxedType->GetUnderlyingType());
  5133. return;
  5134. }
  5135. //int dataOffset =
  5136. //mBfIRBuilder->WriteConstant()
  5137. // BfType* resultType = NULL;
  5138. // if (box->mToType.mKind == BfIRTypeData::TypeKind_TypeId)
  5139. // resultType = mContext->FindTypeById(box->mToType.mId);
  5140. //
  5141. // if ((resultType != NULL) && (resultType->IsBoxed()))
  5142. // {
  5143. // auto boxedType = (BfBoxedType*)resultType;
  5144. // EncodeAttributeData(typeInstance, boxedType->GetUnderlyingType(), BfIRValue(BfIRValueFlags_Const, box->mTarget), data, usedStringIdMap);
  5145. // return;
  5146. // }
  5147. Fail(StrFormat("Unhandled constant box in '%s'", TypeToString(typeInstance).c_str()));
  5148. }
  5149. // else if (constant->mConstType == BfConstType_Agg)
  5150. // {
  5151. // BF_ASSERT(argType->IsComposite());
  5152. // if (argType->IsSizedArray())
  5153. // {
  5154. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  5155. // }
  5156. // else
  5157. // {
  5158. // auto argTypeInstance = argType->ToTypeInstance();
  5159. // }
  5160. // }
  5161. else
  5162. {
  5163. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  5164. }
  5165. }
  5166. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  5167. {
  5168. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  5169. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5170. auto typeInstance = fieldInstance->mOwner;
  5171. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5172. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5173. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5174. BfType* typeIdType = intType;
  5175. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  5176. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  5177. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  5178. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  5179. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  5180. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5181. int typeId = 0;
  5182. auto fieldType = fieldInstance->GetResolvedType();
  5183. if (fieldType->IsGenericParam())
  5184. {
  5185. //TODO:
  5186. }
  5187. else
  5188. typeId = fieldType->mTypeId;
  5189. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  5190. if (fieldDef->mProtection == BfProtection_Protected)
  5191. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  5192. if (fieldDef->mProtection == BfProtection_Public)
  5193. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  5194. if (fieldDef->mIsStatic)
  5195. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  5196. if (fieldDef->mIsConst)
  5197. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  5198. if (fieldDef->IsEnumCaseEntry())
  5199. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  5200. if (fieldDef->mIsReadOnly)
  5201. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  5202. if (fieldInstance->IsAppendedObject())
  5203. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  5204. BfIRValue constValue;
  5205. BfIRValue constValue2;
  5206. if (fieldInstance->mIsEnumPayloadCase)
  5207. {
  5208. int tagId = -fieldInstance->mDataIdx - 1;
  5209. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, tagId);
  5210. }
  5211. else if (fieldInstance->GetFieldDef()->mIsConst)
  5212. {
  5213. if (fieldInstance->mConstIdx != -1)
  5214. {
  5215. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5216. uint64 val = constant->mUInt64;
  5217. if (constant->mTypeCode == BfTypeCode_Float)
  5218. {
  5219. float f = (float)*(double*)&val;
  5220. val = *(uint32*)&f;
  5221. }
  5222. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5223. if (is32Bit)
  5224. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  5225. }
  5226. }
  5227. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5228. {
  5229. BfTypedValue refVal;
  5230. if (mIsComptimeModule)
  5231. {
  5232. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mFieldIdx);
  5233. }
  5234. else
  5235. {
  5236. refVal = ReferenceStaticField(fieldInstance);
  5237. }
  5238. if (refVal.mValue.IsConst())
  5239. {
  5240. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5241. if (constant->mConstType == BfConstType_GlobalVar)
  5242. {
  5243. auto globalVar = (BfGlobalVar*)constant;
  5244. if (globalVar->mName[0] == '#')
  5245. refVal = BfTypedValue();
  5246. }
  5247. }
  5248. if (!isComptimeArg)
  5249. {
  5250. if (refVal.IsAddr())
  5251. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5252. else if ((fieldInstance->IsAppendedObject()) && (refVal))
  5253. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5254. }
  5255. }
  5256. if (!constValue)
  5257. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5258. BfIRValue result;
  5259. if (is32Bit)
  5260. {
  5261. if (!constValue2)
  5262. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  5263. SizedArray<BfIRValue, 8> fieldVals =
  5264. {
  5265. emptyValueType,
  5266. fieldNameConst, // mName
  5267. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5268. constValue, // mData
  5269. constValue2, // mDataHi
  5270. GetConstValue(fieldFlags, shortType), // mFlags
  5271. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5272. };
  5273. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5274. result = isComptimeArg ?
  5275. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5276. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5277. }
  5278. else
  5279. {
  5280. SizedArray<BfIRValue, 8> fieldVals =
  5281. {
  5282. emptyValueType,
  5283. fieldNameConst, // mName
  5284. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5285. constValue, // mData
  5286. GetConstValue(fieldFlags, shortType), // mFlags
  5287. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  5288. };
  5289. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  5290. result = isComptimeArg ?
  5291. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  5292. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  5293. }
  5294. return result;
  5295. }
  5296. void BfModule::CreateSlotOfs(BfTypeInstance* typeInstance)
  5297. {
  5298. int virtSlotIdx = -1;
  5299. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5300. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5301. // For interfaces we ONLY emit the slot num
  5302. StringT<512> slotVarName;
  5303. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5304. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5305. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5306. GetConstValue32(virtSlotIdx), slotVarName);
  5307. }
  5308. BfIRValue BfModule::GetTypeTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool needsTypeData, bool wantsTypeDecl, bool needsTypeNames, int& typeFlags, int& typeCode)
  5309. {
  5310. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5311. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5312. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5313. BfIRValue typeTypeData;
  5314. if (needsTypeData)
  5315. {
  5316. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  5317. BfTypeInstance* typeDataSource = NULL;
  5318. if (typeInstance != NULL)
  5319. {
  5320. if (typeInstance->IsUnspecializedType())
  5321. {
  5322. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  5323. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  5324. }
  5325. else if (typeInstance->IsArray())
  5326. {
  5327. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  5328. typeFlags |= BfTypeFlags_Array;
  5329. }
  5330. else if (typeInstance->IsGenericTypeInstance())
  5331. {
  5332. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  5333. typeFlags |= BfTypeFlags_SpecializedGeneric;
  5334. }
  5335. else
  5336. typeDataSource = typeInstanceTypeInstance;
  5337. }
  5338. else if (type->IsPointer())
  5339. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5340. else if (type->IsRef())
  5341. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5342. else if (type->IsSizedArray())
  5343. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5344. else if (type->IsConstExprValue())
  5345. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5346. else if (type->IsGenericParam())
  5347. {
  5348. typeFlags |= BfTypeFlags_GenericParam;
  5349. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5350. }
  5351. else
  5352. typeDataSource = mContext->mBfTypeType;
  5353. if (wantsTypeDecl)
  5354. {
  5355. typeDataSource = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5356. }
  5357. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5358. {
  5359. CreateTypeData(typeDataSource, ctx, false, true, needsTypeNames, true);
  5360. }
  5361. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5362. ctx.mReflectTypeSet.Add(typeDataSource);
  5363. }
  5364. else
  5365. {
  5366. //typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5367. typeTypeData = mBfIRBuilder->CreateConstNull();
  5368. }
  5369. if (typeInstance != NULL)
  5370. {
  5371. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5372. typeCode = typeInstance->mTypeDef->mTypeCode;
  5373. if (typeInstance->IsBoxed())
  5374. typeCode = BfTypeCode_Object;
  5375. }
  5376. else if (type->IsPrimitiveType())
  5377. {
  5378. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5379. typeCode = primType->mTypeDef->mTypeCode;
  5380. }
  5381. else if (type->IsPointer())
  5382. {
  5383. typeCode = BfTypeCode_Pointer;
  5384. typeFlags |= BfTypeFlags_Pointer;
  5385. }
  5386. else if (type->IsRef())
  5387. {
  5388. typeCode = BfTypeCode_Pointer;
  5389. typeFlags |= BfTypeFlags_Pointer;
  5390. }
  5391. if (type->IsObject())
  5392. {
  5393. typeFlags |= BfTypeFlags_Object;
  5394. if ((!wantsTypeDecl) && (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted))
  5395. {
  5396. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5397. if ((methodInstance != NULL) && (methodInstance->GetOwner() != mContext->mBfObjectType))
  5398. typeFlags |= BfTypeFlags_HasDestructor;
  5399. }
  5400. }
  5401. if (type->IsStruct())
  5402. typeFlags |= BfTypeFlags_Struct;
  5403. if (type->IsInterface())
  5404. typeFlags |= BfTypeFlags_Interface;
  5405. if (type->IsBoxed())
  5406. {
  5407. typeFlags |= BfTypeFlags_Boxed;
  5408. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5409. typeFlags |= BfTypeFlags_Pointer;
  5410. }
  5411. if (type->IsPrimitiveType())
  5412. typeFlags |= BfTypeFlags_Primitive;
  5413. if (type->IsTypedPrimitive())
  5414. typeFlags |= BfTypeFlags_TypedPrimitive;
  5415. if (type->IsTuple())
  5416. typeFlags |= BfTypeFlags_Tuple;
  5417. if (type->IsNullable())
  5418. typeFlags |= BfTypeFlags_Nullable;
  5419. if (type->IsSizedArray())
  5420. typeFlags |= BfTypeFlags_SizedArray;
  5421. if (type->IsConstExprValue())
  5422. typeFlags |= BfTypeFlags_ConstExpr;
  5423. if ((!wantsTypeDecl) && (type->IsSplattable()))
  5424. typeFlags |= BfTypeFlags_Splattable;
  5425. if (type->IsUnion())
  5426. typeFlags |= BfTypeFlags_Union;
  5427. if (type->IsDelegate())
  5428. typeFlags |= BfTypeFlags_Delegate;
  5429. if (type->IsFunction())
  5430. typeFlags |= BfTypeFlags_Function;
  5431. if ((!wantsTypeDecl) && (type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5432. typeFlags |= BfTypeFlags_WantsMarking;
  5433. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsStatic))
  5434. typeFlags |= BfTypeFlags_Static;
  5435. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  5436. typeFlags |= BfTypeFlags_Abstract;
  5437. if ((typeInstance != NULL) && (typeInstance->mHasAppendWantMark))
  5438. typeFlags |= BfTypeFlags_HasAppendWantMark;
  5439. return typeTypeData;
  5440. }
  5441. BfIRValue BfModule::CreateTypeDeclData(BfType* type, BfProject* curProject)
  5442. {
  5443. auto typeDeclType = ResolveTypeDef(mCompiler->mTypeTypeDeclDef)->ToTypeInstance();
  5444. int typeCode = 0;
  5445. int typeFlags = 0;
  5446. BfCreateTypeDataContext createTypeDataCtx;
  5447. BfIRValue typeTypeData = GetTypeTypeData(type, createTypeDataCtx, true, true, true, typeFlags, typeCode);
  5448. SizedArray<BfIRValue, 4> typeValueParams;
  5449. GetConstClassValueParam(typeTypeData, typeValueParams);
  5450. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5451. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5452. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5453. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5454. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5455. BfType* typeIdType = intType;
  5456. auto typeInst = type->ToTypeInstance();
  5457. auto outerType = GetOuterType(type);
  5458. BfType* baseType = NULL;
  5459. if (typeInst != NULL)
  5460. baseType = typeInst->mBaseType;
  5461. enum BfTypeDeclFlags
  5462. {
  5463. BfTypeDeclFlag_DeclaredInDependency = 1,
  5464. BfTypeDeclFlag_DeclaredInDependent = 2,
  5465. BfTypeDeclFlag_DeclaredInCurrent = 4,
  5466. BfTypeDeclFlag_AlwaysVisible = 8,
  5467. BfTypeDeclFlag_SometimesVisible = 0x10
  5468. };
  5469. int flags = 0;
  5470. if (typeInst != NULL)
  5471. {
  5472. auto declProject = typeInst->mTypeDef->mProject;
  5473. auto depKind = curProject->GetDependencyKind(declProject);
  5474. if (depKind == BfProject::DependencyKind_Identity)
  5475. {
  5476. flags |= BfTypeDeclFlag_DeclaredInCurrent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5477. }
  5478. else if (depKind == BfProject::DependencyKind_Dependency)
  5479. {
  5480. flags |= BfTypeDeclFlag_DeclaredInDependency | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5481. }
  5482. else if (depKind == BfProject::DependencyKind_Dependent_Exclusive)
  5483. {
  5484. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_AlwaysVisible | BfTypeDeclFlag_SometimesVisible;
  5485. }
  5486. else if (depKind == BfProject::DependencyKind_Dependent_Shared)
  5487. {
  5488. flags |= BfTypeDeclFlag_DeclaredInDependent | BfTypeDeclFlag_SometimesVisible;
  5489. }
  5490. }
  5491. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5492. SizedArray<BfIRValue, 9> typeDataParams =
  5493. {
  5494. objectData,
  5495. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5496. GetConstValue((outerType != NULL) ? outerType->mTypeId : 0, typeIdType), // mOuterTypeId
  5497. GetConstValue(typeFlags, intType), // mTypeFlags
  5498. GetConstValue(flags, byteType), // mFlags
  5499. GetConstValue(typeCode, byteType), // mTypeCode
  5500. };
  5501. FixConstValueParams(typeDeclType, typeDataParams);
  5502. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(typeDeclType, BfIRPopulateType_Full), typeDataParams);
  5503. String typeDataName = StrFormat("sBfTypeDeclData.%d", type->mTypeId);
  5504. BfIRValue typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeDeclType), true,
  5505. BfIRLinkageType_External, typeData, typeDataName);
  5506. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5507. return typeDataVar;
  5508. }
  5509. BfIRValue BfModule::CreateTypeData(BfType* type, BfCreateTypeDataContext& ctx, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  5510. {
  5511. if ((IsHotCompile()) && (!type->mDirty))
  5512. return BfIRValue();
  5513. BfIRValue* irValuePtr = NULL;
  5514. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  5515. {
  5516. return *irValuePtr;
  5517. }
  5518. BfTypeInstance* typeInstance = type->ToTypeInstance();
  5519. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  5520. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  5521. if (typeInstanceType == NULL)
  5522. {
  5523. AssertErrorState();
  5524. return BfIRValue();
  5525. }
  5526. int typeCode = BfTypeCode_None;
  5527. int typeFlags = 0;
  5528. BfIRValue typeTypeData = GetTypeTypeData(type, ctx, needsTypeData, false, needsTypeNames, typeFlags, typeCode);
  5529. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5530. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5531. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5532. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5533. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5534. BfType* typeIdType = intType;
  5535. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5536. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5537. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5538. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5539. SizedArray<BfIRValue, 4> typeValueParams;
  5540. GetConstClassValueParam(typeTypeData, typeValueParams);
  5541. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5542. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5543. StringT<512> typeDataName;
  5544. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5545. {
  5546. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5547. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5548. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5549. }
  5550. else
  5551. {
  5552. typeDataName += "sBfTypeData.";
  5553. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5554. }
  5555. int virtSlotIdx = -1;
  5556. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5557. virtSlotIdx = typeInstance->mSlotNum + mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount();
  5558. int memberDataOffset = 0;
  5559. if (type->IsInterface())
  5560. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5561. else if (typeInstance != NULL)
  5562. {
  5563. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5564. {
  5565. if (fieldInstance.mDataOffset != -1)
  5566. {
  5567. memberDataOffset = fieldInstance.mDataOffset;
  5568. break;
  5569. }
  5570. }
  5571. }
  5572. int boxedTypeId = 0;
  5573. if ((type->IsValueType()) || (type->IsWrappableType()))
  5574. {
  5575. auto boxedType = CreateBoxedType(type, false);
  5576. if ((boxedType != NULL) && (boxedType->mIsReified))
  5577. boxedTypeId = boxedType->mTypeId;
  5578. }
  5579. int stackCount = 0;
  5580. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5581. {
  5582. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5583. if (typeOptions->mAllocStackTraceDepth != -1)
  5584. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5585. }
  5586. SizedArray<BfIRValue, 9> typeDataParams =
  5587. {
  5588. objectData,
  5589. GetConstValue(type->mSize, intType), // mSize
  5590. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5591. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5592. GetConstValue(typeFlags, intType), // mTypeFlags
  5593. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5594. GetConstValue(typeCode, byteType), // mTypeCode
  5595. GetConstValue(type->mAlign, byteType), // mAlign
  5596. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5597. };
  5598. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5599. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5600. if (typeInstance == NULL)
  5601. {
  5602. BfIRValue typeDataVar;
  5603. if (needsTypeData)
  5604. {
  5605. if (type->IsPointer())
  5606. {
  5607. auto pointerType = (BfPointerType*)type;
  5608. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5609. {
  5610. typeData,
  5611. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5612. };
  5613. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5614. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5615. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5616. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5617. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5618. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5619. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5620. }
  5621. else if (type->IsRef())
  5622. {
  5623. auto refType = (BfRefType*)type;
  5624. SizedArray<BfIRValue, 3> refTypeDataParms =
  5625. {
  5626. typeData,
  5627. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5628. GetConstValue((int8)refType->mRefKind, byteType),
  5629. };
  5630. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5631. FixConstValueParams(reflectRefType, refTypeDataParms);
  5632. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5633. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5634. BfIRLinkageType_External, refTypeData, typeDataName);
  5635. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5636. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5637. }
  5638. else if (type->IsSizedArray())
  5639. {
  5640. auto sizedArrayType = (BfSizedArrayType*)type;
  5641. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5642. {
  5643. typeData,
  5644. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5645. GetConstValue(sizedArrayType->mElementCount, intType)
  5646. };
  5647. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5648. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5649. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5650. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5651. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5652. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5653. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5654. }
  5655. else if (type->IsConstExprValue())
  5656. {
  5657. auto constExprType = (BfConstExprValueType*)type;
  5658. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5659. {
  5660. typeData,
  5661. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5662. GetConstValue(constExprType->mValue.mInt64, longType)
  5663. };
  5664. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5665. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5666. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5667. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5668. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5669. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5670. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5671. }
  5672. else if (type->IsGenericParam())
  5673. {
  5674. auto genericParamType = (BfGenericParamType*)type;
  5675. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5676. {
  5677. typeData
  5678. };
  5679. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5680. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5681. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5682. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5683. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5684. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5685. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5686. }
  5687. else
  5688. {
  5689. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5690. BfIRLinkageType_External, typeData, typeDataName);
  5691. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5692. }
  5693. }
  5694. else
  5695. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5696. mTypeDataRefs[type] = typeDataVar;
  5697. return typeDataVar;
  5698. }
  5699. // Reserve position
  5700. mTypeDataRefs[typeInstance] = BfIRValue();
  5701. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5702. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5703. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5704. StringT<512> mangledName;
  5705. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5706. if (!mIsComptimeModule)
  5707. {
  5708. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5709. {
  5710. auto methodDef = typeDef->mMethods[methodIdx];
  5711. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5712. if (methodInstance == NULL)
  5713. continue;
  5714. if (typeInstance->IsUnspecializedType())
  5715. continue;
  5716. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5717. {
  5718. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5719. {
  5720. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5721. // We need to create an empty thunk for this chained method
  5722. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5723. mBfIRBuilder->SetActiveFunction(func);
  5724. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5725. mBfIRBuilder->SetInsertPoint(block);
  5726. mBfIRBuilder->CreateRetVoid();
  5727. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5728. }
  5729. }
  5730. }
  5731. }
  5732. SizedArray<BfIRValue, 32> vData;
  5733. BfIRValue classVDataVar;
  5734. String classVDataName;
  5735. if (typeInstance->mSlotNum >= 0)
  5736. {
  5737. CreateSlotOfs(typeInstance);
  5738. }
  5739. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5740. {
  5741. int dynCastDataElems = 0;
  5742. int numElements = 1;
  5743. int vDataOfs = mCompiler->GetVDataPrefixDataCount(); // The number of intptrs before the iface slot map
  5744. numElements += mCompiler->mMaxInterfaceSlots;
  5745. if (!typeInstance->IsInterface())
  5746. {
  5747. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5748. numElements += mCompiler->GetDynCastVDataCount();
  5749. numElements += typeInstance->mVirtualMethodTableSize;
  5750. }
  5751. int expectNumElements = 0;
  5752. if (!typeDef->mIsStatic)
  5753. {
  5754. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5755. }
  5756. for (int i = 0; i < mCompiler->GetVDataPrefixDataCount(); i++)
  5757. vData.push_back(BfIRValue()); // Type
  5758. SizedArray<BfIRValue, 1> extVTableData;
  5759. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5760. if (!typeInstance->IsInterface())
  5761. {
  5762. Array<int32> dynCastData;
  5763. if (typeInstance->IsBoxed())
  5764. {
  5765. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5766. dynCastData.Add(underlyingType->mInheritanceId);
  5767. }
  5768. else
  5769. dynCastData.Add(typeInstance->mInheritanceId);
  5770. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5771. dynCastData.Add(0);
  5772. dynCastData.Add(0);
  5773. auto checkTypeInst = typeInstance;
  5774. while (checkTypeInst != NULL)
  5775. {
  5776. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5777. {
  5778. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5779. {
  5780. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5781. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5782. }
  5783. }
  5784. checkTypeInst = checkTypeInst->GetImplBaseType();
  5785. }
  5786. if (mSystem->mPtrSize == 8)
  5787. {
  5788. int intPtrCount = (dynCastDataElems + 1) / 2;
  5789. vDataOfs += intPtrCount;
  5790. uint64* intPtrData = (uint64*)&dynCastData[0];
  5791. for (int i = 0; i < intPtrCount; i++)
  5792. {
  5793. uint64 val = intPtrData[i];
  5794. if (val == 0)
  5795. {
  5796. vData.push_back(voidPtrNull);
  5797. }
  5798. else
  5799. {
  5800. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5801. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5802. }
  5803. }
  5804. }
  5805. else
  5806. {
  5807. int intPtrCount = dynCastDataElems;
  5808. vDataOfs += intPtrCount;
  5809. uint32* intPtrData = (uint32*)&dynCastData[0];
  5810. for (int i = 0; i < intPtrCount; i++)
  5811. {
  5812. uint32 val = intPtrData[i];
  5813. if (val == 0)
  5814. {
  5815. vData.push_back(voidPtrNull);
  5816. }
  5817. else
  5818. {
  5819. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5820. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5821. }
  5822. }
  5823. }
  5824. }
  5825. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5826. vData.push_back(voidPtrNull);
  5827. struct _InterfaceMatchEntry
  5828. {
  5829. BfTypeInterfaceEntry* mEntry;
  5830. BfTypeInstance* mEntrySource;
  5831. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5832. };
  5833. int highestIFaceVirtIdx = 0;
  5834. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5835. auto checkTypeInst = typeInstance;
  5836. bool forceInterfaceSet = false;
  5837. while (checkTypeInst != NULL)
  5838. {
  5839. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5840. {
  5841. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5842. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5843. continue;
  5844. _InterfaceMatchEntry* matchEntry = NULL;
  5845. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5846. {
  5847. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5848. if (compareCheckTypeInst->IsBoxed())
  5849. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5850. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5851. if (compareEntrySource->IsBoxed())
  5852. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5853. auto prevEntry = matchEntry->mEntry;
  5854. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5855. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5856. if ((!isBetter) && (!isWorse))
  5857. {
  5858. // Unboxed comparison to Object fix
  5859. if (compareCheckTypeInst == mContext->mBfObjectType)
  5860. isWorse = true;
  5861. else if (compareEntrySource == mContext->mBfObjectType)
  5862. isBetter = true;
  5863. }
  5864. if (forceInterfaceSet)
  5865. {
  5866. isBetter = true;
  5867. isWorse = false;
  5868. }
  5869. if (isBetter == isWorse)
  5870. CompareDeclTypes(checkTypeInst, interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5871. if (isBetter == isWorse)
  5872. {
  5873. if (matchEntry->mAmbiguousEntries.empty())
  5874. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5875. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5876. continue;
  5877. }
  5878. else if (isBetter)
  5879. {
  5880. matchEntry->mEntry = &interfaceEntry;
  5881. matchEntry->mEntrySource = checkTypeInst;
  5882. matchEntry->mAmbiguousEntries.Clear();
  5883. }
  5884. else
  5885. continue;
  5886. }
  5887. else
  5888. {
  5889. _InterfaceMatchEntry matchEntry;
  5890. matchEntry.mEntry = &interfaceEntry;
  5891. matchEntry.mEntrySource = checkTypeInst;
  5892. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5893. }
  5894. }
  5895. checkTypeInst = checkTypeInst->GetImplBaseType();
  5896. }
  5897. for (auto interfacePair : interfaceMap)
  5898. {
  5899. auto& interfaceMatchEntry = interfacePair.mValue;
  5900. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5901. {
  5902. 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());
  5903. if (error != NULL)
  5904. {
  5905. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5906. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5907. }
  5908. }
  5909. }
  5910. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5911. {
  5912. int startTabIdx = (int)vData.size();
  5913. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5914. BfTypeInstance* checkTypeInst = typeInstance;
  5915. while (checkTypeInst != NULL)
  5916. {
  5917. origVirtTypeStack.push_back(checkTypeInst);
  5918. checkTypeInst = checkTypeInst->GetImplBaseType();
  5919. }
  5920. Array<BfVirtualMethodEntry> origVTable;
  5921. int origVirtIdx = 0;
  5922. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5923. {
  5924. HashSet<String> reslotNames;
  5925. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5926. {
  5927. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5928. if (entry.mDeclaringMethod.mMethodNum == -1)
  5929. continue;
  5930. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5931. if ((methodInstance == NULL) ||
  5932. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5933. {
  5934. if (origVTable.empty())
  5935. origVTable = typeInstance->mVirtualMethodTable;
  5936. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5937. if (declMethodInstance != NULL)
  5938. {
  5939. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5940. {
  5941. // Prepare to reslot...
  5942. entry.mImplementingMethod = entry.mDeclaringMethod;
  5943. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5944. }
  5945. else
  5946. {
  5947. // Decl isn't accessible, null out entry
  5948. entry.mImplementingMethod = BfMethodRef();
  5949. }
  5950. }
  5951. }
  5952. }
  5953. if (!reslotNames.IsEmpty())
  5954. {
  5955. BfAmbiguityContext ambiguityContext;
  5956. ambiguityContext.mTypeInstance = typeInstance;
  5957. ambiguityContext.mModule = this;
  5958. ambiguityContext.mIsProjectSpecific = true;
  5959. ambiguityContext.mIsReslotting = true;
  5960. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5961. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5962. {
  5963. auto methodInstance = methodGroup.mDefault;
  5964. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5965. continue;
  5966. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5967. continue;
  5968. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5969. continue;
  5970. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5971. continue;
  5972. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5973. }
  5974. ambiguityContext.Finish();
  5975. }
  5976. }
  5977. bool isInExts = false;
  5978. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5979. {
  5980. BfIRValue vValue = voidPtrNull;
  5981. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5982. BfModuleMethodInstance moduleMethodInst;
  5983. if (entry.mDeclaringMethod.mMethodNum == -1)
  5984. {
  5985. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5986. isInExts = true;
  5987. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5988. if (vExt)
  5989. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5990. }
  5991. else
  5992. {
  5993. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5994. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5995. {
  5996. if (entry.mImplementingMethod.mMethodNum >= 0)
  5997. {
  5998. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5999. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  6000. }
  6001. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  6002. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  6003. {
  6004. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  6005. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6006. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6007. vValue = funcPtr;
  6008. }
  6009. }
  6010. }
  6011. while (origVirtTypeStack.size() != 0)
  6012. {
  6013. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  6014. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  6015. {
  6016. // Moved past current base vtable size
  6017. origVirtTypeStack.pop_back();
  6018. continue;
  6019. }
  6020. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  6021. {
  6022. // We are within the original vtable size
  6023. int idx = startTabIdx + origVirtIdx;
  6024. origVirtIdx++;
  6025. vData.push_back(vValue);
  6026. }
  6027. else
  6028. {
  6029. // This is a new entry, it only gets added to the ext
  6030. BF_ASSERT(isInExts);
  6031. }
  6032. break;
  6033. }
  6034. }
  6035. if (!origVTable.empty())
  6036. typeInstance->mVirtualMethodTable = origVTable;
  6037. }
  6038. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  6039. if (typeInstance->mHotTypeData != NULL)
  6040. {
  6041. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  6042. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  6043. }
  6044. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  6045. int iFaceMethodStartIdx = (int)vData.size();
  6046. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  6047. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  6048. vData[i] = voidPtrNull;
  6049. if (expectNumElements != 0)
  6050. BF_ASSERT(expectNumElements == vData.size());
  6051. //BF_ASSERT(vData.size() == expectNumElements);
  6052. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  6053. // ifaceMethodExtData.Add(voidPtrNull);
  6054. int ifaceEntryIdx = iFaceMethodStartIdx;
  6055. for (auto& interfacePair : interfaceMap)
  6056. {
  6057. auto interfaceEntry = interfacePair.mValue.mEntry;
  6058. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  6059. {
  6060. BF_ASSERT(mIsComptimeModule);
  6061. break;
  6062. }
  6063. bool makeEmpty = false;
  6064. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  6065. makeEmpty = true;
  6066. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6067. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  6068. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6069. {
  6070. BfIRValue pushValue;
  6071. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6072. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6073. continue;
  6074. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6075. continue;
  6076. if (makeEmpty)
  6077. {
  6078. pushValue = voidPtrNull;
  6079. }
  6080. else
  6081. {
  6082. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6083. auto methodInstance = (BfMethodInstance*)methodRef;
  6084. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  6085. {
  6086. BF_ASSERT(methodInstance->mIsReified);
  6087. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6088. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6089. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6090. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6091. pushValue = funcPtr;
  6092. }
  6093. else
  6094. {
  6095. pushValue = voidPtrNull;
  6096. }
  6097. }
  6098. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6099. if (idx < ifaceMethodExtStart)
  6100. {
  6101. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  6102. vData[iFaceMethodStartIdx + idx] = pushValue;
  6103. }
  6104. else
  6105. {
  6106. BF_ASSERT(useExt);
  6107. int extIdx = idx - ifaceMethodExtStart;
  6108. while (extIdx >= ifaceMethodExtData.size())
  6109. ifaceMethodExtData.Add(voidPtrNull);
  6110. ifaceMethodExtData[extIdx] = pushValue;
  6111. }
  6112. }
  6113. }
  6114. if (typeInstance->IsBoxed())
  6115. {
  6116. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  6117. if (boxedType->IsBoxedStructPtr())
  6118. {
  6119. // Force override of GetHashCode so we use the pointer address as the hash code
  6120. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  6121. // Force override of GetHashCode so we use the pointer address as the hash code
  6122. for (auto& checkIFace : checkTypeInst->mInterfaces)
  6123. {
  6124. if (checkIFace.mStartVirtualIdx < 0)
  6125. continue;
  6126. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6127. {
  6128. BfIRValue pushValue;
  6129. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  6130. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  6131. continue;
  6132. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  6133. continue;
  6134. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  6135. auto methodInstance = (BfMethodInstance*)methodRef;
  6136. BF_ASSERT(methodInstance->mIsReified);
  6137. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  6138. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  6139. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  6140. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  6141. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  6142. vData[iFaceMethodStartIdx + idx] = funcPtr;
  6143. }
  6144. }
  6145. }
  6146. }
  6147. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  6148. {
  6149. BfIRValue ifaceMethodExtVar;
  6150. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  6151. {
  6152. StringT<512> classVDataName;
  6153. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  6154. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  6155. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  6156. BfIRLinkageType_External, BfIRValue(), classVDataName);
  6157. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  6158. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  6159. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  6160. }
  6161. for (auto& ifaceInstPair : interfaceMap)
  6162. {
  6163. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  6164. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  6165. if (slotNum >= 0)
  6166. {
  6167. BfIRValue vtablePtr;
  6168. int idx = interfaceEntry->mStartVirtualIdx;
  6169. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  6170. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  6171. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  6172. else
  6173. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  6174. int slotVirtIdx = slotNum + vDataOfs;
  6175. if (vData[slotVirtIdx] == voidPtrNull)
  6176. {
  6177. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  6178. }
  6179. else
  6180. {
  6181. if (mCompiler->IsHotCompile())
  6182. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  6183. else
  6184. Fail("Interface slot collision error", typeDef->GetRefNode());
  6185. }
  6186. }
  6187. }
  6188. }
  6189. }
  6190. BfIRValue typeNameConst;
  6191. BfIRValue namespaceConst;
  6192. if (needsTypeNames)
  6193. {
  6194. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  6195. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  6196. }
  6197. else
  6198. {
  6199. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  6200. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6201. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  6202. }
  6203. int baseTypeId = 0;
  6204. if (typeInstance->mBaseType != NULL)
  6205. {
  6206. baseTypeId = typeInstance->mBaseType->mTypeId;
  6207. }
  6208. BfTypeOptions* typeOptions = NULL;
  6209. if (typeInstance->mTypeOptionsIdx >= 0)
  6210. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6211. SizedArray<BfIRValue, 16> customAttrs;
  6212. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  6213. BfIRValue castedClassVData;
  6214. if (classVDataVar)
  6215. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  6216. else
  6217. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  6218. bool freflectIncludeTypeData = false;
  6219. bool reflectIncludeAllFields = false;
  6220. bool reflectIncludeAllMethods = false;
  6221. if (TypeIsSubTypeOf(typeInstance, attributeType))
  6222. {
  6223. reflectIncludeAllFields = true;
  6224. reflectIncludeAllMethods = true;
  6225. }
  6226. if (typeInstance->IsTuple())
  6227. {
  6228. // Required to generate tuple name at runtime
  6229. reflectIncludeAllFields = true;
  6230. }
  6231. BfReflectKind reflectKind = BfReflectKind_Type;
  6232. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  6233. {
  6234. BfReflectKind reflectKind = BfReflectKind_None;
  6235. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  6236. if (customAttrs != NULL)
  6237. {
  6238. for (auto& attr : customAttrs->mAttributes)
  6239. {
  6240. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  6241. }
  6242. delete customAttrs;
  6243. }
  6244. return reflectKind;
  6245. };
  6246. reflectKind = GetReflectKind(reflectKind, typeInstance);
  6247. // Fields
  6248. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  6249. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  6250. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  6251. {
  6252. if (customAttributes == NULL)
  6253. return -1;
  6254. Array<BfCustomAttribute*> reflectAttributes;
  6255. for (auto& attr : customAttributes->mAttributes)
  6256. {
  6257. bool wantAttribute = false;
  6258. if (attr.mType->mCustomAttributes != NULL)
  6259. {
  6260. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  6261. if (usageAttribute != NULL)
  6262. {
  6263. // Check for Flags arg
  6264. if (usageAttribute->mCtorArgs.size() < 2)
  6265. continue;
  6266. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  6267. if (constant == NULL)
  6268. continue;
  6269. if (constant->mTypeCode == BfTypeCode_Boolean)
  6270. continue;
  6271. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  6272. wantAttribute = true;
  6273. }
  6274. }
  6275. if ((wantAttribute) && (attr.mType->mIsReified))
  6276. {
  6277. reflectAttributes.Add(&attr);
  6278. }
  6279. }
  6280. if (reflectAttributes.size() == 0)
  6281. return -1;
  6282. #define PUSH_INT8(val) data.push_back((uint8)val)
  6283. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  6284. #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); }
  6285. SizedArray<uint8, 16> data;
  6286. int customAttrIdx = (int)customAttrs.size();
  6287. data.push_back((uint8)reflectAttributes.size());
  6288. for (auto attr : reflectAttributes)
  6289. {
  6290. // Size prefix
  6291. int sizeIdx = (int)data.size();
  6292. PUSH_INT16(0); // mSize
  6293. PUSH_INT32(attr->mType->mTypeId); // mType
  6294. int ctorIdx = -1;
  6295. int ctorCount = 0;
  6296. attr->mType->mTypeDef->PopulateMemberSets();
  6297. BfMemberSetEntry* entry;
  6298. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  6299. {
  6300. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6301. while (nextMethodDef != NULL)
  6302. {
  6303. if (nextMethodDef == attr->mCtor)
  6304. ctorIdx = ctorCount;
  6305. nextMethodDef = nextMethodDef->mNextWithSameName;
  6306. ctorCount++;
  6307. }
  6308. }
  6309. BF_ASSERT(ctorIdx != -1);
  6310. if (ctorIdx != -1)
  6311. ctorIdx = (ctorCount - 1) - ctorIdx;
  6312. PUSH_INT16(ctorIdx);
  6313. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  6314. int argIdx = 0;
  6315. for (auto arg : attr->mCtorArgs)
  6316. {
  6317. auto argType = ctorMethodInstance->GetParamType(argIdx);
  6318. EncodeAttributeData(typeInstance, argType, arg, data, ctx.mUsedStringIdMap);
  6319. argIdx++;
  6320. }
  6321. int size = (int)data.size() - sizeIdx;
  6322. *((uint16*)&data[sizeIdx]) = size;
  6323. }
  6324. #undef PUSH_INT8
  6325. #undef PUSH_INT16
  6326. #undef PUSH_INT32
  6327. SizedArray<BfIRValue, 16> dataValues;
  6328. for (uint8 val : data)
  6329. dataValues.push_back(GetConstValue8(val));
  6330. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  6331. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  6332. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  6333. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  6334. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  6335. customAttrs.push_back(customAttrArrayPtr);
  6336. return customAttrIdx;
  6337. };
  6338. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  6339. SizedArray<int, 16> reflectFieldIndices;
  6340. for (int pass = 0; pass < 2; pass++)
  6341. {
  6342. bool skippedField = false;
  6343. reflectFieldIndices.clear();
  6344. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  6345. {
  6346. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6347. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  6348. if (fieldDef == NULL)
  6349. continue;
  6350. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6351. bool includeField = reflectIncludeAllFields;
  6352. if (fieldInstance->mCustomAttributes != NULL)
  6353. {
  6354. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  6355. {
  6356. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6357. {
  6358. includeField = true;
  6359. }
  6360. else
  6361. {
  6362. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6363. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  6364. }
  6365. }
  6366. }
  6367. if ((fieldReflectKind & BfReflectKind_User) != 0)
  6368. includeField = true;
  6369. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  6370. includeField = true;
  6371. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  6372. includeField = true;
  6373. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  6374. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  6375. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  6376. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  6377. includeField |= forceReflectFields;
  6378. if (!includeField)
  6379. {
  6380. skippedField = true;
  6381. continue;
  6382. }
  6383. reflectFieldIndices.Add(fieldIdx);
  6384. }
  6385. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  6386. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  6387. // possible because we write out a SplatData structure containing just TypeIds in that case
  6388. if (pass == 0)
  6389. {
  6390. if (!typeInstance->IsSplattable())
  6391. break;
  6392. if (!skippedField)
  6393. break;
  6394. if (reflectFieldIndices.size() == 0)
  6395. break;
  6396. }
  6397. }
  6398. SizedArray<BfIRValue, 16> fieldTypes;
  6399. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  6400. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  6401. {
  6402. BfType* payloadType = typeInstance->GetUnionInnerType();
  6403. if (!payloadType->IsValuelessType())
  6404. {
  6405. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  6406. SizedArray<BfIRValue, 8> payloadFieldVals;
  6407. if (is32Bit)
  6408. {
  6409. payloadFieldVals =
  6410. {
  6411. emptyValueType,
  6412. payloadNameConst, // mName
  6413. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6414. GetConstValue(0, intPtrType), // mData
  6415. GetConstValue(0, intPtrType), // mDataHi
  6416. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6417. GetConstValue(-1, intType), // mCustomAttributesIdx
  6418. };
  6419. }
  6420. else
  6421. {
  6422. payloadFieldVals =
  6423. {
  6424. emptyValueType,
  6425. payloadNameConst, // mName
  6426. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  6427. GetConstValue(0, intPtrType), // mData
  6428. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  6429. GetConstValue(-1, intType), // mCustomAttributesIdx
  6430. };
  6431. }
  6432. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  6433. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  6434. fieldTypes.push_back(payloadFieldData);
  6435. }
  6436. BfType* dscrType = typeInstance->GetDiscriminatorType();
  6437. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  6438. SizedArray<BfIRValue, 8> dscrFieldVals;
  6439. if (is32Bit)
  6440. {
  6441. dscrFieldVals =
  6442. {
  6443. emptyValueType,
  6444. dscrNameConst, // mName
  6445. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6446. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6447. GetConstValue(0, intPtrType), // mDataHi
  6448. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6449. GetConstValue(-1, intType), // mCustomAttributesIdx
  6450. };
  6451. }
  6452. else
  6453. {
  6454. dscrFieldVals =
  6455. {
  6456. emptyValueType,
  6457. dscrNameConst, // mName
  6458. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6459. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6460. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6461. GetConstValue(-1, intType), // mCustomAttributesIdx
  6462. };
  6463. }
  6464. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6465. fieldTypes.push_back(dscrFieldData);
  6466. }
  6467. for (auto fieldIdx : reflectFieldIndices)
  6468. {
  6469. if (!needsTypeData)
  6470. break;
  6471. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6472. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6473. }
  6474. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6475. BfIRValue fieldDataPtr;
  6476. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6477. if (fieldTypes.size() == 0)
  6478. {
  6479. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6480. {
  6481. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6482. SizedArray<BfIRValue, 3> splatTypes;
  6483. SizedArray<BfIRValue, 3> splatOffsets;
  6484. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6485. {
  6486. auto checkTypeInstance = checkType->ToTypeInstance();
  6487. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6488. PopulateType(checkTypeInstance);
  6489. if (checkType->IsStruct())
  6490. {
  6491. int dataEnd = offset;
  6492. if (checkTypeInstance->mBaseType != NULL)
  6493. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6494. if (checkTypeInstance->mIsUnion)
  6495. {
  6496. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6497. _CheckSplat(unionInnerType, offset);
  6498. }
  6499. else
  6500. {
  6501. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6502. {
  6503. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6504. if (fieldInstance->mDataIdx >= 0)
  6505. {
  6506. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6507. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6508. }
  6509. }
  6510. }
  6511. if (checkTypeInstance->IsEnum())
  6512. {
  6513. // Add discriminator
  6514. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6515. if (checkTypeInstance->mPacking > 0)
  6516. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6517. _CheckSplat(dscrType, dataEnd);
  6518. }
  6519. }
  6520. else if (checkType->IsMethodRef())
  6521. {
  6522. // auto methodRefType = (BfMethodRefType*)checkType;
  6523. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6524. // {
  6525. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6526. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6527. // else
  6528. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6529. // }
  6530. }
  6531. else if (!checkType->IsValuelessType())
  6532. {
  6533. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6534. splatOffsets.Add(GetConstValue(offset, intType));
  6535. }
  6536. };
  6537. _CheckSplat(type, 0);
  6538. while (splatTypes.size() < 3)
  6539. {
  6540. splatTypes.Add(GetConstValue(0, typeIdType));
  6541. splatOffsets.Add(GetConstValue(0, intType));
  6542. }
  6543. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6544. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6545. SizedArray<BfIRValue, 8> splatVals =
  6546. {
  6547. emptyValueType,
  6548. splatTypesConst,
  6549. splatOffsetsConst
  6550. };
  6551. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6552. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6553. fieldSplatData, typeDataName + ".splats");
  6554. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6555. }
  6556. else
  6557. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6558. }
  6559. else
  6560. {
  6561. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6562. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6563. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6564. fieldDataConst, "fields." + typeDataName);
  6565. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6566. }
  6567. /// Methods
  6568. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6569. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6570. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6571. struct _SortedMethodInfo
  6572. {
  6573. BfMethodDef* mMethodDef;
  6574. BfMethodCustomAttributes* mMethodCustomAttributes;
  6575. };
  6576. Array<_SortedMethodInfo> sortedMethodList;
  6577. SizedArray<BfIRValue, 16> methodTypes;
  6578. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6579. {
  6580. if (!needsTypeData)
  6581. break;
  6582. // Disable const method reflection info for now
  6583. if (mIsComptimeModule)
  6584. break;
  6585. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6586. if (!methodInstanceGroup->IsImplemented())
  6587. continue;
  6588. auto methodDef = typeDef->mMethods[methodIdx];
  6589. if (methodDef->mIsNoReflect)
  6590. continue;
  6591. if (methodDef->mHasComptime)
  6592. continue;
  6593. auto defaultMethod = methodInstanceGroup->mDefault;
  6594. if (defaultMethod == NULL)
  6595. continue;
  6596. if (defaultMethod->mIsUnspecialized)
  6597. continue;
  6598. if (!defaultMethod->mIsReified)
  6599. continue;
  6600. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6601. continue;
  6602. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6603. continue;
  6604. if (!defaultMethod->mMethodDef->CanReflect())
  6605. continue;
  6606. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6607. bool includeMethod = reflectIncludeAllMethods;
  6608. if (typeInstance->IsDelegateOrFunction())
  6609. includeMethod = true;
  6610. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6611. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6612. {
  6613. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6614. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6615. {
  6616. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6617. {
  6618. includeMethod = true;
  6619. }
  6620. else
  6621. {
  6622. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6623. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6624. }
  6625. }
  6626. }
  6627. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6628. continue;
  6629. //
  6630. {
  6631. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6632. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6633. {
  6634. BfTypeState typeState;
  6635. typeState.mPrevState = mContext->mCurTypeState;
  6636. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  6637. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6638. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6639. {
  6640. if (paramDecl->mAttributes != NULL)
  6641. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6642. }
  6643. }
  6644. }
  6645. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6646. includeMethod = true;
  6647. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6648. includeMethod = true;
  6649. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6650. {
  6651. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6652. includeMethod = true;
  6653. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6654. includeMethod = true;
  6655. }
  6656. if ((!includeMethod) && (typeOptions != NULL))
  6657. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6658. if (!includeMethod)
  6659. continue;
  6660. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6661. }
  6662. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6663. {
  6664. if (methodDef->mMethodType == BfMethodType_Ctor)
  6665. return 0;
  6666. return 1;
  6667. };
  6668. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6669. {
  6670. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6671. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6672. if (lhsKind != rhsKind)
  6673. return lhsKind < rhsKind;
  6674. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6675. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6676. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6677. });
  6678. for (auto& methodInfo : sortedMethodList)
  6679. {
  6680. auto methodDef = methodInfo.mMethodDef;
  6681. int methodIdx = methodDef->mIdx;
  6682. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6683. auto defaultMethod = methodInstanceGroup->mDefault;
  6684. BfModuleMethodInstance moduleMethodInstance;
  6685. BfIRValue funcVal = voidPtrNull;
  6686. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6687. (!typeInstance->IsUnspecializedType()) &&
  6688. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6689. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6690. (!methodDef->mIsAbstract) &&
  6691. (methodDef->mGenericParams.size() == 0))
  6692. {
  6693. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6694. if (moduleMethodInstance.mFunc)
  6695. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6696. }
  6697. BfIRValue methodNameConst = GetStringObjectValue(methodDef->GetReflectName(), !mIsComptimeModule);
  6698. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6699. int customAttrIdx = -1;
  6700. int returnCustomAttrIdx = -1;
  6701. if (methodInfo.mMethodCustomAttributes != NULL)
  6702. {
  6703. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6704. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6705. }
  6706. enum ParamFlags
  6707. {
  6708. ParamFlag_None = 0,
  6709. ParamFlag_Splat = 1,
  6710. ParamFlag_Implicit = 2,
  6711. ParamFlag_AppendIdx = 4,
  6712. ParamFlag_Params = 8
  6713. };
  6714. SizedArray<BfIRValue, 8> paramVals;
  6715. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6716. {
  6717. String paramName = defaultMethod->GetParamName(paramIdx);
  6718. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6719. ParamFlags paramFlags = ParamFlag_None;
  6720. if (defaultMethod->GetParamIsSplat(paramIdx))
  6721. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6722. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6723. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6724. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6725. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6726. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6727. int paramCustomAttrIdx = -1;
  6728. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6729. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6730. SizedArray<BfIRValue, 8> paramDataVals =
  6731. {
  6732. emptyValueType,
  6733. paramNameConst,
  6734. GetConstValue(paramType->mTypeId, typeIdType),
  6735. GetConstValue((int32)paramFlags, shortType),
  6736. GetConstValue(-1, intType), // defaultIdx
  6737. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6738. };
  6739. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6740. paramVals.Add(paramData);
  6741. }
  6742. BfIRValue paramsVal;
  6743. if (paramVals.size() > 0)
  6744. {
  6745. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6746. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6747. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6748. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6749. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6750. }
  6751. else
  6752. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6753. int vDataVal = -1;
  6754. if (defaultMethod->mVirtualTableIdx != -1)
  6755. {
  6756. int vDataIdx = -1;
  6757. if (type->IsInterface())
  6758. {
  6759. vDataIdx = defaultMethod->mVirtualTableIdx;
  6760. }
  6761. else
  6762. {
  6763. vDataIdx = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6764. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6765. {
  6766. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6767. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6768. if (extMethodIdx >= 0)
  6769. {
  6770. // Extension?
  6771. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6772. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6773. }
  6774. else
  6775. {
  6776. // Map this new virtual index back to the original index
  6777. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6778. }
  6779. }
  6780. else
  6781. {
  6782. vDataIdx += defaultMethod->mVirtualTableIdx;
  6783. }
  6784. }
  6785. if (vDataVal == -1)
  6786. vDataVal = vDataIdx * mSystem->mPtrSize;
  6787. }
  6788. SizedArray<BfIRValue, 8> methodDataVals =
  6789. {
  6790. emptyValueType,
  6791. methodNameConst, // mName
  6792. funcVal, // mFuncPtr
  6793. paramsVal,
  6794. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6795. GetConstValue((int)paramVals.size(), shortType),
  6796. GetConstValue(methodFlags, intType),
  6797. GetConstValue(methodIdx, intType),
  6798. GetConstValue(vDataVal, intType),
  6799. GetConstValue(customAttrIdx, intType),
  6800. GetConstValue(returnCustomAttrIdx, intType),
  6801. };
  6802. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6803. methodTypes.push_back(methodData);
  6804. }
  6805. BfIRValue methodDataPtr;
  6806. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6807. if (methodTypes.size() == 0)
  6808. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6809. else
  6810. {
  6811. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6812. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6813. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6814. methodDataConst, "methods." + typeDataName);
  6815. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6816. }
  6817. /////
  6818. int interfaceCount = 0;
  6819. BfIRValue interfaceDataPtr;
  6820. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6821. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6822. Array<bool> wantsIfaceMethod;
  6823. bool wantsIfaceMethods = false;
  6824. if ((typeInstance->mInterfaces.IsEmpty()) || (!needsTypeData))
  6825. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6826. else
  6827. {
  6828. SizedArray<BfIRValue, 16> interfaces;
  6829. for (auto& interface : typeInstance->mInterfaces)
  6830. {
  6831. SizedArray<BfIRValue, 8> interfaceDataVals =
  6832. {
  6833. emptyValueType,
  6834. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6835. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6836. GetConstValue(interface.mStartVirtualIdx, intType),
  6837. };
  6838. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6839. interfaces.push_back(interfaceData);
  6840. if (!mIsComptimeModule)
  6841. {
  6842. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6843. {
  6844. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6845. if (ifaceMethodGroup->mExplicitlyReflected)
  6846. {
  6847. wantsIfaceMethods = true;
  6848. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6849. while (tableIdx >= wantsIfaceMethod.size())
  6850. wantsIfaceMethod.Add(false);
  6851. wantsIfaceMethod[tableIdx] = true;
  6852. }
  6853. }
  6854. }
  6855. }
  6856. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6857. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6858. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6859. interfaceDataConst, "interfaces." + typeDataName);
  6860. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6861. interfaceCount = (int)interfaces.size();
  6862. }
  6863. BfIRValue interfaceMethodTable;
  6864. int ifaceMethodTableSize = 0;
  6865. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6866. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6867. {
  6868. SizedArray<BfIRValue, 16> methods;
  6869. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6870. {
  6871. BfIRValue funcVal = voidPtrNull;
  6872. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6873. {
  6874. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6875. if (!methodEntry.mMethodRef.IsNull())
  6876. {
  6877. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6878. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6879. (!methodInstance->mMethodDef->mIsAbstract))
  6880. {
  6881. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6882. if (moduleMethodInstance.mFunc)
  6883. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6884. }
  6885. }
  6886. }
  6887. methods.Add(funcVal);
  6888. }
  6889. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6890. methods.pop_back();
  6891. if (!methods.IsEmpty())
  6892. {
  6893. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6894. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6895. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6896. methodDataConst, "imethods." + typeDataName);
  6897. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6898. ifaceMethodTableSize = (int)methods.size();
  6899. }
  6900. }
  6901. if (!interfaceMethodTable)
  6902. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6903. /////
  6904. int underlyingType = 0;
  6905. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6906. {
  6907. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6908. }
  6909. int outerTypeId = 0;
  6910. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6911. if (outerType != NULL)
  6912. {
  6913. outerTypeId = outerType->mTypeId;
  6914. }
  6915. //
  6916. BfIRValue customAttrDataPtr;
  6917. if (customAttrs.size() > 0)
  6918. {
  6919. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6920. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6921. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6922. customAttrsConst, "customAttrs." + typeDataName);
  6923. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6924. }
  6925. else
  6926. {
  6927. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6928. }
  6929. SizedArray<BfIRValue, 32> typeDataVals =
  6930. {
  6931. typeData,
  6932. castedClassVData, // mTypeClassVData
  6933. typeNameConst, // mName
  6934. namespaceConst, // mNamespace
  6935. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6936. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6937. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6938. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6939. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6940. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6941. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6942. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6943. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6944. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6945. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6946. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6947. GetConstValue(0, shortType), // mPropertyDataCount
  6948. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6949. interfaceDataPtr, // mInterfaceDataPtr
  6950. interfaceMethodTable, // mInterfaceMethodTable
  6951. methodDataPtr, // mMethodDataPtr
  6952. voidPtrNull, // mPropertyDataPtr
  6953. fieldDataPtr, // mFieldDataPtr
  6954. customAttrDataPtr, // mCustomAttrDataPtr
  6955. };
  6956. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6957. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6958. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6959. if (!needsTypeData)
  6960. {
  6961. // No need for anything beyond typeInstanceData
  6962. }
  6963. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6964. {
  6965. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6966. SizedArray<BfIRValue, 4> unspecializedData =
  6967. {
  6968. typeInstanceData,
  6969. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6970. };
  6971. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6972. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6973. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6974. }
  6975. else if (typeInstance->IsGenericTypeInstance())
  6976. {
  6977. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6978. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6979. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6980. SizedArray<BfIRValue, 4> resolvedTypes;
  6981. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6982. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6983. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6984. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6985. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6986. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6987. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6988. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6989. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6990. SizedArray<BfIRValue, 3> specGenericData =
  6991. {
  6992. typeInstanceData,
  6993. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6994. resovledTypesPtr, // mFieldDataPtr
  6995. };
  6996. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6997. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6998. if (typeInstance->IsArray())
  6999. {
  7000. auto arrayType = (BfArrayType*)typeInstance;
  7001. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  7002. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  7003. SizedArray<BfIRValue, 4> arrayData =
  7004. {
  7005. typeInstanceData,
  7006. GetConstValue(elementType->mSize, intType), // mElementSize
  7007. GetConstValue(1, byteType), // mRank
  7008. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  7009. };
  7010. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  7011. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  7012. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  7013. }
  7014. }
  7015. BfIRValue typeDataVar;
  7016. if (needsTypeData)
  7017. {
  7018. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  7019. BfIRLinkageType_External, typeInstanceData, typeDataName);
  7020. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  7021. if (mBfIRBuilder->DbgHasInfo())
  7022. {
  7023. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  7024. }
  7025. }
  7026. else
  7027. {
  7028. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  7029. }
  7030. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  7031. mTypeDataRefs[typeInstance] = typeDataVar;
  7032. if ((!mIsComptimeModule) && (classVDataVar))
  7033. {
  7034. BF_ASSERT(!classVDataName.IsEmpty());
  7035. //vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  7036. int unboxedTypeId = type->mTypeId;
  7037. if (type->IsBoxed())
  7038. unboxedTypeId = type->GetUnderlyingType()->mTypeId;
  7039. if (mSystem->mPtrSize == 4)
  7040. {
  7041. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(type->mTypeId, intPtrType), voidPtrIRType);
  7042. vData[1] = mBfIRBuilder->CreateIntToPtr(GetConstValue(unboxedTypeId, intPtrType), voidPtrIRType);
  7043. }
  7044. else
  7045. {
  7046. vData[0] = mBfIRBuilder->CreateIntToPtr(GetConstValue(((int64)unboxedTypeId << 32) | type->mTypeId, intPtrType), voidPtrIRType);
  7047. }
  7048. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  7049. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  7050. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  7051. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7052. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  7053. else
  7054. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  7055. if (mBfIRBuilder->DbgHasInfo())
  7056. {
  7057. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7058. BfType* voidPtrType = CreatePointerType(voidType);
  7059. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7060. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  7061. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  7062. }
  7063. }
  7064. return typeDataVar;
  7065. }
  7066. BfIRValue BfModule::FixClassVData(BfIRValue value)
  7067. {
  7068. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  7069. return value;
  7070. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  7071. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7072. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  7073. }
  7074. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  7075. {
  7076. // Note: this is not just for perf, it fixes a field var-type resolution issue
  7077. if (mBfIRBuilder->mIgnoreWrites)
  7078. return;
  7079. if (mIsComptimeModule)
  7080. return;
  7081. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7082. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  7083. // When we access classes with static constructors FROM a static constructor,
  7084. // we call that other class's static constructor first. Recursion cannot occur, since
  7085. // we simply ignore subsequent attempts to re-enter the constructor
  7086. if (!typeInstance->mHasStaticInitMethod)
  7087. return;
  7088. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  7089. return;
  7090. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  7091. return;
  7092. auto checkTypeDef = typeInstance->mTypeDef;
  7093. checkTypeDef->PopulateMemberSets();
  7094. BfMethodDef* nextMethodDef = NULL;
  7095. BfMemberSetEntry* entry;
  7096. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  7097. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  7098. while (nextMethodDef != NULL)
  7099. {
  7100. auto checkMethod = nextMethodDef;
  7101. nextMethodDef = nextMethodDef->mNextWithSameName;
  7102. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  7103. if (methodModule)
  7104. {
  7105. auto methodInstance = methodModule.mMethodInstance;
  7106. if ((methodInstance != NULL) &&
  7107. (methodInstance->mMethodDef->mIsStatic) &&
  7108. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  7109. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  7110. {
  7111. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  7112. break;
  7113. }
  7114. }
  7115. }
  7116. }
  7117. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  7118. {
  7119. if (!methodInstance->mIsIntrinsic)
  7120. return BfIRFunction();
  7121. auto methodOwner = methodInstance->GetOwner();
  7122. auto methodDef = methodInstance->mMethodDef;
  7123. auto methodDeclaration = methodDef->GetMethodDeclaration();
  7124. if (!methodDef->mIsExtern)
  7125. return BfIRFunction();
  7126. if (methodInstance->GetCustomAttributes() == NULL)
  7127. return BfIRFunction();
  7128. auto customAttribute = methodInstance->GetCustomAttributes()->Get(mCompiler->mIntrinsicAttributeTypeDef);
  7129. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute->mCtorArgs[0]);
  7130. String error;
  7131. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  7132. {
  7133. int stringId = constant->mInt32;
  7134. auto entry = mContext->mStringObjectIdMap[stringId];
  7135. String intrinName = entry.mString;
  7136. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  7137. if (intrinId != -1)
  7138. {
  7139. if (intrinId == BfIRIntrinsic_Malloc)
  7140. {
  7141. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7142. }
  7143. else if (intrinId == BfIRIntrinsic_Free)
  7144. {
  7145. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  7146. }
  7147. SizedArray<BfIRType, 2> paramTypes;
  7148. for (auto& param : methodInstance->mParams)
  7149. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  7150. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  7151. }
  7152. else if (reportFailure)
  7153. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  7154. }
  7155. else if (reportFailure)
  7156. error = "Intrinsic name must be a constant string";
  7157. if (reportFailure)
  7158. {
  7159. Fail(error, customAttribute->mRef);
  7160. }
  7161. return BfIRFunction();
  7162. }
  7163. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  7164. {
  7165. if (mBfIRBuilder->mIgnoreWrites)
  7166. return mBfIRBuilder->GetFakeFunction();
  7167. if (!mBuiltInFuncs[(int)funcTypeId])
  7168. {
  7169. SizedArray<BfIRType, 4> paramTypes;
  7170. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  7171. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7172. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  7173. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  7174. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  7175. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  7176. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  7177. BfIRFunctionType funcType;
  7178. BfIRFunction func;
  7179. switch (funcTypeId)
  7180. {
  7181. case BfBuiltInFuncType_PrintF:
  7182. paramTypes.Add(nullPtrType);
  7183. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  7184. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  7185. break;
  7186. case BfBuiltInFuncType_Malloc:
  7187. {
  7188. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7189. {
  7190. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  7191. }
  7192. else
  7193. {
  7194. String funcName = mCompiler->mOptions.mMallocLinkName;
  7195. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7196. funcName = "malloc";
  7197. func = mBfIRBuilder->GetFunction(funcName);
  7198. if (!func)
  7199. {
  7200. paramTypes.clear();
  7201. paramTypes.push_back(intType);
  7202. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  7203. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7204. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  7205. }
  7206. }
  7207. }
  7208. break;
  7209. case BfBuiltInFuncType_Free:
  7210. {
  7211. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7212. {
  7213. func = GetInternalMethod("Dbg_RawFree").mFunc;
  7214. }
  7215. else
  7216. {
  7217. String funcName = mCompiler->mOptions.mFreeLinkName;
  7218. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  7219. funcName = "free";
  7220. func = mBfIRBuilder->GetFunction(funcName);
  7221. if (!func)
  7222. {
  7223. paramTypes.clear();
  7224. paramTypes.push_back(nullPtrType);
  7225. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7226. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  7227. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  7228. }
  7229. }
  7230. }
  7231. break;
  7232. case BfBuiltInFuncType_LoadSharedLibraries:
  7233. paramTypes.clear();
  7234. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  7235. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  7236. break;
  7237. default: break;
  7238. }
  7239. mBuiltInFuncs[(int)funcTypeId] = func;
  7240. return func;
  7241. }
  7242. return mBuiltInFuncs[(int)funcTypeId];
  7243. }
  7244. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  7245. {
  7246. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  7247. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  7248. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  7249. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  7250. BfAutoComplete* bfAutocomplete = NULL;
  7251. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  7252. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  7253. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  7254. {
  7255. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  7256. {
  7257. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  7258. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  7259. {
  7260. String filter = nameNode->ToString();
  7261. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  7262. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  7263. if (nameIdx != 0)
  7264. {
  7265. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  7266. }
  7267. }
  7268. }
  7269. }
  7270. for (auto constraint : constraintDef->mConstraints)
  7271. {
  7272. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  7273. {
  7274. BfGenericOperatorConstraintInstance opConstraintInstance;
  7275. if (opConstraint->mLeftType != NULL)
  7276. {
  7277. if (bfAutocomplete != NULL)
  7278. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  7279. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  7280. if (opConstraintInstance.mLeftType == NULL)
  7281. continue;
  7282. }
  7283. if (opConstraint->mRightType == NULL)
  7284. {
  7285. // We had a failure in parsing
  7286. continue;
  7287. }
  7288. if (opConstraint->mRightType != NULL)
  7289. {
  7290. if (bfAutocomplete != NULL)
  7291. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  7292. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  7293. if (opConstraintInstance.mRightType == NULL)
  7294. continue;
  7295. }
  7296. if (opConstraint->mOpToken == NULL)
  7297. {
  7298. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  7299. continue;
  7300. }
  7301. if (opConstraint->mLeftType != NULL)
  7302. {
  7303. if (opConstraint->mRightType == NULL)
  7304. {
  7305. // Parse should have failed
  7306. continue;
  7307. }
  7308. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  7309. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  7310. {
  7311. Fail("Invalid binary operator", opConstraint->mOpToken);
  7312. continue;
  7313. }
  7314. }
  7315. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  7316. {
  7317. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  7318. }
  7319. else
  7320. {
  7321. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  7322. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  7323. {
  7324. Fail("Invalid unary operator", opConstraint->mOpToken);
  7325. continue;
  7326. }
  7327. }
  7328. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  7329. continue;
  7330. }
  7331. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  7332. if (bfAutocomplete != NULL)
  7333. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  7334. //TODO: Constraints may refer to other generic params (of either type or method)
  7335. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  7336. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  7337. if (isUnspecialized)
  7338. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  7339. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  7340. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  7341. BfType* constraintType;
  7342. if (constraintTypeRef->IsA<BfVarTypeReference>())
  7343. constraintType = GetPrimitiveType(BfTypeCode_Var);
  7344. else
  7345. constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  7346. if (constraintType != NULL)
  7347. {
  7348. if (deferredResolveTypes != NULL)
  7349. {
  7350. PopulateType(constraintType, BfPopulateType_Declaration);
  7351. if (constraintType->IsUnspecializedTypeVariation())
  7352. deferredResolveTypes->Add(constraintTypeRef);
  7353. }
  7354. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7355. {
  7356. bool isValidTypeCode = false;
  7357. BfTypeCode typeCode = BfTypeCode_None;
  7358. if (constraintType->IsTypedPrimitive())
  7359. {
  7360. auto underlyingType = constraintType->GetUnderlyingType();
  7361. if (underlyingType->IsPrimitiveType())
  7362. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  7363. }
  7364. if (constraintType->IsPrimitiveType())
  7365. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  7366. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  7367. isValidTypeCode = true;
  7368. if (constraintType->IsValueType())
  7369. isValidTypeCode = true;
  7370. if (constraintType->IsVar())
  7371. isValidTypeCode = true;
  7372. switch (typeCode)
  7373. {
  7374. case BfTypeCode_StringId:
  7375. case BfTypeCode_Boolean:
  7376. case BfTypeCode_Int8:
  7377. case BfTypeCode_UInt8:
  7378. case BfTypeCode_Int16:
  7379. case BfTypeCode_UInt16:
  7380. case BfTypeCode_Int32:
  7381. case BfTypeCode_UInt32:
  7382. case BfTypeCode_Int64:
  7383. case BfTypeCode_UInt64:
  7384. case BfTypeCode_IntPtr:
  7385. case BfTypeCode_UIntPtr:
  7386. case BfTypeCode_IntUnknown:
  7387. case BfTypeCode_UIntUnknown:
  7388. case BfTypeCode_Float:
  7389. case BfTypeCode_Double:
  7390. case BfTypeCode_Char8:
  7391. case BfTypeCode_Char16:
  7392. case BfTypeCode_Char32:
  7393. isValidTypeCode = true;
  7394. break;
  7395. default: break;
  7396. }
  7397. if (isValidTypeCode)
  7398. {
  7399. genericParamInstance->mTypeConstraint = constraintType;
  7400. }
  7401. else
  7402. {
  7403. Fail("Const constraint must be a valuetype or string", constraintTypeRef);
  7404. }
  7405. }
  7406. else
  7407. {
  7408. bool checkEquality = false;
  7409. if (constraintType->IsVar())
  7410. {
  7411. // From a `comptype` generic undef resolution. Ignore.
  7412. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  7413. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  7414. continue;
  7415. }
  7416. else if (constraintType->IsPrimitiveType())
  7417. {
  7418. checkEquality = true;
  7419. }
  7420. if (constraintType->IsArray())
  7421. {
  7422. if (isUnspecialized)
  7423. {
  7424. 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);
  7425. continue;
  7426. }
  7427. checkEquality = true;
  7428. }
  7429. if (constraintType->IsGenericParam())
  7430. {
  7431. checkEquality = true;
  7432. }
  7433. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  7434. {
  7435. checkEquality = true;
  7436. }
  7437. if (checkEquality)
  7438. {
  7439. genericParamInstance->mTypeConstraint = constraintType;
  7440. }
  7441. else if (constraintType->IsInterface())
  7442. {
  7443. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  7444. }
  7445. else
  7446. {
  7447. auto constraintTypeInst = constraintType->ToTypeInstance();
  7448. if (genericParamInstance->mTypeConstraint != NULL)
  7449. {
  7450. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  7451. {
  7452. // Allow more specific type
  7453. genericParamInstance->mTypeConstraint = constraintTypeInst;
  7454. }
  7455. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  7456. {
  7457. // Silently ignore less-specific type
  7458. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7459. {
  7460. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7461. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7462. }
  7463. }
  7464. else
  7465. {
  7466. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7467. return;
  7468. }
  7469. }
  7470. else
  7471. genericParamInstance->mTypeConstraint = constraintType;
  7472. }
  7473. }
  7474. }
  7475. }
  7476. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7477. (genericParamInstance->mTypeConstraint == NULL))
  7478. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7479. }
  7480. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7481. {
  7482. if (genericParamSource.mMethodInstance != NULL)
  7483. {
  7484. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7485. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7486. return MethodToString(genericParamSource.mMethodInstance);
  7487. }
  7488. else
  7489. {
  7490. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7491. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7492. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7493. return TypeToString(typeInst);
  7494. }
  7495. }
  7496. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7497. {
  7498. Array<String> methodParamNameOverrides;
  7499. auto _TypeToString = [&](BfType* type)
  7500. {
  7501. if (genericParamSource.mMethodInstance != NULL)
  7502. {
  7503. if (methodParamNameOverrides.IsEmpty())
  7504. {
  7505. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7506. methodParamNameOverrides.Add(genericParam->mName);
  7507. }
  7508. return TypeToString(type, &methodParamNameOverrides);
  7509. }
  7510. return TypeToString(type);
  7511. };
  7512. bool ignoreErrors = (errorOut == NULL) ||
  7513. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7514. if (checkArgType->IsVar())
  7515. return true;
  7516. BfType* origCheckArgType = checkArgType;
  7517. if (origCheckArgType->IsRef())
  7518. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7519. bool argIsReferenceType = false;
  7520. int checkGenericParamFlags = 0;
  7521. if (checkArgType->IsGenericParam())
  7522. {
  7523. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7524. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7525. if (checkGenericParamInst->mTypeConstraint != NULL)
  7526. checkArgType = checkGenericParamInst->mTypeConstraint;
  7527. if (checkGenericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7528. checkArgType = GetPrimitiveType(BfTypeCode_Var);
  7529. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7530. // {
  7531. // argMayBeReferenceType = false;
  7532. // }
  7533. // else
  7534. // {
  7535. // argMayBeReferenceType = true;
  7536. // }
  7537. }
  7538. if (checkArgType->IsObjectOrInterface())
  7539. argIsReferenceType = true;
  7540. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  7541. {
  7542. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  7543. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  7544. {
  7545. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  7546. if ((genericParamInst->mExternType == checkArgType) && (checkArgType->IsUnspecializedType()))
  7547. {
  7548. checkGenericParamFlags |= genericParamInst->mGenericParamFlags;
  7549. }
  7550. }
  7551. }
  7552. BfTypeInstance* typeConstraintInst = NULL;
  7553. if (genericParamInst->mTypeConstraint != NULL)
  7554. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7555. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7556. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7557. {
  7558. if ((!ignoreErrors) && (PreFail()))
  7559. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7560. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7561. return false;
  7562. }
  7563. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7564. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7565. {
  7566. if ((!ignoreErrors) && (PreFail()))
  7567. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7568. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7569. return false;
  7570. }
  7571. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7572. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7573. {
  7574. if ((!ignoreErrors) && (PreFail()))
  7575. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7576. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7577. return false;
  7578. }
  7579. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7580. {
  7581. bool isEnum = checkArgType->IsEnum();
  7582. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7583. isEnum = true;
  7584. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7585. {
  7586. if ((!ignoreErrors) && (PreFail()))
  7587. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7588. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7589. return false;
  7590. }
  7591. }
  7592. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7593. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7594. {
  7595. if ((!ignoreErrors) && (PreFail()))
  7596. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7597. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7598. return false;
  7599. }
  7600. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7601. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7602. {
  7603. if ((!ignoreErrors) && (PreFail()))
  7604. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7605. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7606. return false;
  7607. }
  7608. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7609. {
  7610. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7611. {
  7612. if ((!ignoreErrors) && (PreFail()))
  7613. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7614. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7615. return false;
  7616. }
  7617. }
  7618. else
  7619. {
  7620. if (checkArgType->IsConstExprValue())
  7621. {
  7622. if ((!ignoreErrors) && (PreFail()))
  7623. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7624. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7625. return false;
  7626. }
  7627. }
  7628. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7629. {
  7630. bool canDelete = false;
  7631. if (checkArgType->IsPointer())
  7632. canDelete = true;
  7633. else if (checkArgType->IsObjectOrInterface())
  7634. canDelete = true;
  7635. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7636. canDelete = true;
  7637. if (!canDelete)
  7638. {
  7639. if ((!ignoreErrors) && (PreFail()))
  7640. {
  7641. if (checkArgType->IsGenericParam())
  7642. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7643. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7644. else
  7645. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7646. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7647. }
  7648. return false;
  7649. }
  7650. }
  7651. auto checkArgElementType = checkArgType;
  7652. if (checkArgElementType->IsPointer())
  7653. {
  7654. auto ptrType = (BfPointerType*)checkArgElementType;
  7655. checkArgElementType = ptrType->mElementType;
  7656. }
  7657. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7658. {
  7659. bool canAlloc = false;
  7660. if (auto checkTypeInst = checkArgElementType->ToTypeInstance())
  7661. {
  7662. if (checkTypeInst->IsObjectOrStruct())
  7663. {
  7664. checkTypeInst->mTypeDef->PopulateMemberSets();
  7665. BfMemberSetEntry* entry = NULL;
  7666. BfMethodDef* checkMethodDef = NULL;
  7667. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7668. if (entry != NULL)
  7669. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7670. bool hadProtected = false;
  7671. while (checkMethodDef != NULL)
  7672. {
  7673. if (!checkMethodDef->mParams.IsEmpty())
  7674. {
  7675. auto firstParam = checkMethodDef->mParams[0];
  7676. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7677. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7678. {
  7679. // Allow all-default params
  7680. }
  7681. else
  7682. {
  7683. checkMethodDef = checkMethodDef->mNextWithSameName;
  7684. continue;
  7685. }
  7686. }
  7687. if (checkMethodDef->mProtection == BfProtection_Public)
  7688. {
  7689. canAlloc = true;
  7690. break;
  7691. }
  7692. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7693. hadProtected = true;
  7694. checkMethodDef = checkMethodDef->mNextWithSameName;
  7695. }
  7696. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7697. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7698. }
  7699. }
  7700. else if (checkArgElementType->IsGenericParam())
  7701. {
  7702. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7703. }
  7704. else if (checkArgElementType->IsPrimitiveType())
  7705. {
  7706. // Any primitive types and stuff can be allocated
  7707. canAlloc = true;
  7708. }
  7709. if (!canAlloc)
  7710. {
  7711. if ((!ignoreErrors) && (PreFail()))
  7712. {
  7713. if (checkArgType->IsGenericParam())
  7714. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7715. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7716. else
  7717. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7718. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7719. }
  7720. return false;
  7721. }
  7722. }
  7723. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7724. return true;
  7725. if (genericParamInst->mTypeConstraint != NULL)
  7726. {
  7727. bool constraintMatched = false;
  7728. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7729. {
  7730. if (checkArgType->IsConstExprValue())
  7731. {
  7732. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7733. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7734. {
  7735. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7736. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7737. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7738. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7739. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7740. (primType->mTypeDef->mTypeCode != BfTypeCode_Let) &&
  7741. (primType->mTypeDef->mTypeCode != BfTypeCode_Var))
  7742. {
  7743. bool doError = true;
  7744. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7745. {
  7746. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7747. {
  7748. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7749. doError = false;
  7750. }
  7751. }
  7752. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7753. {
  7754. doError = false;
  7755. }
  7756. if (doError)
  7757. {
  7758. if ((!ignoreErrors) && (PreFail()))
  7759. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7760. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7761. return false;
  7762. }
  7763. }
  7764. }
  7765. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7766. {
  7767. if ((!ignoreErrors) && (PreFail()))
  7768. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7769. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7770. return false;
  7771. }
  7772. }
  7773. }
  7774. else
  7775. {
  7776. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7777. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7778. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7779. if (convCheckConstraint == NULL)
  7780. return false;
  7781. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7782. {
  7783. if (convCheckConstraint->IsDelegate())
  7784. {
  7785. BfMethodInstance* checkMethodInstance;
  7786. if (checkArgType->IsMethodRef())
  7787. {
  7788. auto methodRefType = (BfMethodRefType*)checkArgType;
  7789. checkMethodInstance = methodRefType->mMethodRef;
  7790. }
  7791. else
  7792. {
  7793. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7794. }
  7795. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7796. if (checkMethodInstance->HasExplicitThis() != 0)
  7797. {
  7798. // Don't allow functions with explicit 'this'
  7799. }
  7800. else
  7801. {
  7802. BfExprEvaluator exprEvaluator(this);
  7803. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7804. constraintMatched = true;
  7805. }
  7806. }
  7807. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7808. constraintMatched = true;
  7809. else if ((checkArgType->IsFunction()) && (convCheckConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  7810. constraintMatched = true;
  7811. }
  7812. else if ((checkArgType == convCheckConstraint) || (checkArgType->IsVar()) || (TypeIsSubTypeOf(checkArgType->ToTypeInstance(), convCheckConstraint->ToTypeInstance())))
  7813. {
  7814. constraintMatched = true;
  7815. }
  7816. else if (origCheckArgType->IsWrappableType())
  7817. {
  7818. if (origCheckArgType->IsSizedArray())
  7819. {
  7820. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7821. if (convCheckConstraint->IsGenericTypeInstance())
  7822. {
  7823. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7824. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7825. {
  7826. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7827. {
  7828. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7829. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7830. constraintMatched = true;
  7831. }
  7832. }
  7833. }
  7834. }
  7835. if (!constraintMatched)
  7836. {
  7837. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7838. if ((wrappedStructType == convCheckConstraint) || (TypeIsSubTypeOf(wrappedStructType, convCheckConstraint->ToTypeInstance())))
  7839. constraintMatched = true;
  7840. }
  7841. }
  7842. if (!constraintMatched)
  7843. {
  7844. if ((!ignoreErrors) && (PreFail()))
  7845. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7846. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7847. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7848. return false;
  7849. }
  7850. }
  7851. }
  7852. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7853. {
  7854. BfType* convCheckConstraint = checkConstraint;
  7855. if (convCheckConstraint->IsUnspecializedType())
  7856. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7857. if (convCheckConstraint == NULL)
  7858. return false;
  7859. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7860. bool implementsInterface = false;
  7861. if (origCheckArgType != checkArgType)
  7862. {
  7863. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7864. }
  7865. if (!implementsInterface)
  7866. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7867. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7868. {
  7869. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7870. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7871. implementsInterface = true;
  7872. }
  7873. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7874. {
  7875. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7876. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7877. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7878. implementsInterface = true;
  7879. }
  7880. if (!implementsInterface)
  7881. {
  7882. if ((!ignoreErrors) && (PreFail()))
  7883. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7884. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7885. return false;
  7886. }
  7887. }
  7888. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7889. {
  7890. auto leftType = checkOpConstraint.mLeftType;
  7891. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7892. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7893. if (leftType != NULL)
  7894. leftType = FixIntUnknown(leftType);
  7895. auto rightType = checkOpConstraint.mRightType;
  7896. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7897. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7898. if (rightType != NULL)
  7899. rightType = FixIntUnknown(rightType);
  7900. BfConstraintState constraintSet;
  7901. constraintSet.mPrevState = mContext->mCurConstraintState;
  7902. constraintSet.mGenericParamInstance = genericParamInst;
  7903. constraintSet.mLeftType = leftType;
  7904. constraintSet.mRightType = rightType;
  7905. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7906. if (!CheckConstraintState(NULL))
  7907. return false;
  7908. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7909. {
  7910. BfExprEvaluator exprEvaluator(this);
  7911. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7912. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7913. //
  7914. {
  7915. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7916. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7917. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7918. }
  7919. if ((!exprEvaluator.mResult) ||
  7920. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7921. {
  7922. if ((!ignoreErrors) && (PreFail()))
  7923. {
  7924. if (genericParamInst->mExternType != NULL)
  7925. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7926. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7927. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7928. ), checkArgTypeRef);
  7929. else
  7930. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7931. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7932. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7933. ), checkArgTypeRef);
  7934. }
  7935. return false;
  7936. }
  7937. }
  7938. else
  7939. {
  7940. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7941. StringT<128> failedOpName;
  7942. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7943. {
  7944. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7945. failedOpName = "implicit conversion from '";
  7946. }
  7947. else
  7948. {
  7949. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7950. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7951. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7952. {
  7953. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7954. failedOpName = "explicit conversion from '";
  7955. }
  7956. else
  7957. {
  7958. BfExprEvaluator exprEvaluator(this);
  7959. exprEvaluator.mResult = rightValue;
  7960. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7961. if ((!exprEvaluator.mResult) ||
  7962. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7963. {
  7964. failedOpName += "unary operation '";
  7965. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7966. }
  7967. }
  7968. }
  7969. if (!failedOpName.IsEmpty())
  7970. {
  7971. if ((!ignoreErrors) && (PreFail()))
  7972. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7973. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7974. failedOpName.c_str(), TypeToString(rightType).c_str()
  7975. ), checkArgTypeRef);
  7976. return false;
  7977. }
  7978. }
  7979. }
  7980. return true;
  7981. }
  7982. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7983. {
  7984. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7985. {
  7986. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7987. return genericParamType;
  7988. }
  7989. auto genericParamType = new BfGenericParamType();
  7990. genericParamType->mContext = mContext;
  7991. genericParamType->mGenericParamKind = paramKind;
  7992. genericParamType->mGenericParamIdx = paramIdx;
  7993. PopulateType(genericParamType);
  7994. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7995. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7996. BfResolvedTypeSet::LookupContext lookupCtx;
  7997. lookupCtx.mModule = this;
  7998. BfResolvedTypeSet::EntryRef typeEntry;
  7999. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  8000. BF_ASSERT(inserted);
  8001. typeEntry->mValue = genericParamType;
  8002. return genericParamType;
  8003. }
  8004. static int sValueFromExprIdx = 0;
  8005. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  8006. {
  8007. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  8008. if ((result) && (!result.mType->IsVar()) && (!ignoreNullable))
  8009. {
  8010. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  8011. //TODO: Make this work, needed for 'void' and such
  8012. BfType* nullableType = NULL;
  8013. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  8014. {
  8015. BfTypeVector typeVec;
  8016. typeVec.push_back(result.mType);
  8017. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  8018. BF_ASSERT(nullableType != NULL);
  8019. }
  8020. // Go back to start and do any setup we need
  8021. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8022. BfTypedValue nullableTypedValue;
  8023. if (nullableType != NULL)
  8024. {
  8025. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  8026. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  8027. GetConstValue(nullableType->mSize), nullableType->mAlign);
  8028. }
  8029. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8030. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  8031. mBfIRBuilder->SetInsertPoint(notNullBB);
  8032. result = LoadValue(result);
  8033. if (nullableTypedValue)
  8034. {
  8035. auto elementType = nullableType->GetUnderlyingType();
  8036. if (elementType->IsVar())
  8037. {
  8038. // Do nothing
  8039. }
  8040. else if (elementType->IsValuelessType())
  8041. {
  8042. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  8043. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  8044. }
  8045. else
  8046. {
  8047. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  8048. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  8049. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  8050. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  8051. }
  8052. result = nullableTypedValue;
  8053. }
  8054. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8055. AddBasicBlock(pendingNullCond->mDoneBB);
  8056. if (nullableType == NULL)
  8057. {
  8058. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  8059. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  8060. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  8061. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  8062. {
  8063. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  8064. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  8065. }
  8066. result.mValue = phi;
  8067. }
  8068. }
  8069. else
  8070. {
  8071. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  8072. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  8073. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  8074. AddBasicBlock(pendingNullCond->mDoneBB);
  8075. }
  8076. delete mCurMethodState->mPendingNullConditional;
  8077. mCurMethodState->mPendingNullConditional = NULL;
  8078. return result;
  8079. }
  8080. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  8081. {
  8082. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  8083. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  8084. if (mCurMethodState != NULL)
  8085. {
  8086. deferredLocalAssignData.mIsIfCondition = true;
  8087. deferredLocalAssignData.mIfMayBeSkipped = true;
  8088. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  8089. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  8090. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  8091. }
  8092. BfScopeData newScope;
  8093. newScope.mOuterIsConditional = true;
  8094. newScope.mAllowTargeting = false;
  8095. if (mCurMethodState != NULL)
  8096. {
  8097. mCurMethodState->AddScope(&newScope);
  8098. NewScopeState(true, false);
  8099. }
  8100. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8101. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  8102. if (mCurMethodState != NULL)
  8103. RestoreScopeState();
  8104. }
  8105. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8106. {
  8107. //
  8108. {
  8109. BP_ZONE("CreateValueFromExpression:CheckStack");
  8110. StackHelper stackHelper;
  8111. if (!stackHelper.CanStackExpand(128 * 1024))
  8112. {
  8113. BfTypedValue result;
  8114. if (!stackHelper.Execute([&]()
  8115. {
  8116. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8117. }))
  8118. {
  8119. Fail("Expression too complex to compile", expr);
  8120. }
  8121. return result;
  8122. }
  8123. }
  8124. BP_ZONE("BfModule::CreateValueFromExpression");
  8125. if (outOrigType != NULL)
  8126. *outOrigType = NULL;
  8127. exprEvaluator.mExpectingType = wantTypeRef;
  8128. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  8129. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  8130. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  8131. {
  8132. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  8133. {
  8134. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  8135. }
  8136. else
  8137. {
  8138. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  8139. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8140. }
  8141. }
  8142. else
  8143. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  8144. if (!exprEvaluator.mResult)
  8145. {
  8146. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  8147. return exprEvaluator.mResult;
  8148. if (!mCompiler->mPassInstance->HasFailed())
  8149. {
  8150. if (PreFail())
  8151. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  8152. }
  8153. return BfTypedValue();
  8154. }
  8155. auto typedVal = exprEvaluator.mResult;
  8156. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  8157. {
  8158. BF_ASSERT(typedVal.mType->IsGenericParam());
  8159. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  8160. bool handled = false;
  8161. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  8162. {
  8163. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  8164. if (genericTypeConstraint != NULL)
  8165. {
  8166. auto underlyingConstraint = genericTypeConstraint;
  8167. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  8168. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  8169. if (underlyingConstraint != NULL)
  8170. {
  8171. BfTypedValue result;
  8172. result.mKind = BfTypedValueKind_Value;
  8173. result.mType = genericTypeConstraint;
  8174. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  8175. typedVal = result;
  8176. handled = true;
  8177. }
  8178. }
  8179. }
  8180. if (!handled)
  8181. {
  8182. //Fail("Only const generic parameters can be used as values", expr);
  8183. AssertErrorState();
  8184. return BfTypedValue();
  8185. }
  8186. }
  8187. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  8188. FixIntUnknown(typedVal);
  8189. if (!mBfIRBuilder->mIgnoreWrites)
  8190. FixValueActualization(typedVal);
  8191. exprEvaluator.CheckResultForReading(typedVal);
  8192. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  8193. {
  8194. if ((flags & BfEvalExprFlags_NoCast) == 0)
  8195. {
  8196. // Only allow a 'ref' type if we have an explicit 'ref' operator
  8197. bool allowRef = false;
  8198. BfAstNode* checkExpr = expr;
  8199. while (checkExpr != NULL)
  8200. {
  8201. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  8202. checkExpr = parenExpr->mExpression;
  8203. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  8204. {
  8205. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  8206. allowRef = true;
  8207. break;
  8208. }
  8209. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  8210. {
  8211. if (block->mChildArr.mSize == 0)
  8212. break;
  8213. checkExpr = block->mChildArr.back();
  8214. }
  8215. else
  8216. break;
  8217. }
  8218. if (!allowRef)
  8219. typedVal = RemoveRef(typedVal);
  8220. }
  8221. }
  8222. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  8223. {
  8224. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  8225. {
  8226. if (typedVal.mValue.IsFake())
  8227. {
  8228. InternalError("Unexpected fakeval in CreateValueFromExpression");
  8229. typedVal = GetDefaultTypedValue(typedVal.mType);
  8230. }
  8231. }
  8232. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8233. }
  8234. if (wantTypeRef != NULL)
  8235. {
  8236. if (outOrigType != NULL)
  8237. *outOrigType = typedVal.mType;
  8238. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  8239. {
  8240. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  8241. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  8242. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  8243. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  8244. if (!typedVal)
  8245. return typedVal;
  8246. }
  8247. if (exprEvaluator.mIsVolatileReference)
  8248. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8249. }
  8250. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  8251. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  8252. if (auto autoComplete = mCompiler->GetAutoComplete())
  8253. autoComplete->CheckResult(expr, typedVal);
  8254. return typedVal;
  8255. }
  8256. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  8257. {
  8258. BfExprEvaluator exprEvaluator(this);
  8259. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  8260. }
  8261. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  8262. {
  8263. BfExprEvaluator exprEvaluator(this);
  8264. exprEvaluator.Evaluate(expr);
  8265. if (!exprEvaluator.mResult)
  8266. {
  8267. Fail("Invalid expression type", expr);
  8268. return BfTypedValue();
  8269. }
  8270. if (!exprEvaluator.mResult.IsAddr())
  8271. {
  8272. Fail("Cannot assign to value", expr);
  8273. return BfTypedValue();
  8274. }
  8275. return exprEvaluator.mResult;
  8276. }
  8277. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  8278. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue, BfAllocFlags allocFlags)
  8279. {
  8280. auto typeInstance = typedValue.mType->ToTypeInstance();
  8281. if (zeroMemory)
  8282. {
  8283. int zeroAlign = typedValue.mType->mAlign;
  8284. if (typeInstance != NULL)
  8285. zeroAlign = typeInstance->mInstAlign;
  8286. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  8287. }
  8288. if (!typedValue.mType->IsObject())
  8289. {
  8290. return;
  8291. }
  8292. if ((scopeData == NULL) && (mCurMethodState != NULL))
  8293. return; // Handled in heap alloc funcs
  8294. auto typeDef = typeInstance->mTypeDef;
  8295. mBfIRBuilder->PopulateType(typedValue.mType);
  8296. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  8297. bool isAutocomplete = mCompiler->IsAutocomplete();
  8298. BfIRValue vDataRef;
  8299. if (!isAutocomplete)
  8300. {
  8301. vDataRef = GetClassVDataPtr(typeInstance);
  8302. }
  8303. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8304. auto ptrType = CreatePointerType(i8Type);
  8305. auto ptrPtrType = CreatePointerType(ptrType);
  8306. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  8307. PopulateType(ptrType, BfPopulateType_Declaration);
  8308. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  8309. if (!isAutocomplete)
  8310. {
  8311. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8312. {
  8313. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8314. SizedArray<BfIRValue, 4> llvmArgs;
  8315. llvmArgs.push_back(objectPtr);
  8316. llvmArgs.push_back(vDataRef);
  8317. llvmArgs.push_back(sizeValue);
  8318. llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Int8, allocFlags));
  8319. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  8320. if (objectStackInitMethod)
  8321. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  8322. }
  8323. else
  8324. {
  8325. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  8326. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  8327. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8328. }
  8329. }
  8330. }
  8331. bool BfModule::IsAllocatorAligned()
  8332. {
  8333. if (mCompiler->mOptions.mMallocLinkName == "StompAlloc")
  8334. return false;
  8335. return true;
  8336. }
  8337. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  8338. {
  8339. BfIRValue result;
  8340. BfType* ptrType;
  8341. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  8342. ptrType = type;
  8343. else
  8344. ptrType = CreatePointerType(type);
  8345. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  8346. {
  8347. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8348. SizedArray<BfExpression*, 2> argExprs;
  8349. BfTypedValueExpression typedValueExpr;
  8350. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  8351. typedValueExpr.mRefNode = refNode;
  8352. argExprs.push_back(&typedValueExpr);
  8353. BfTypedValueExpression appendSizeValueExpr;
  8354. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  8355. appendSizeValueExpr.mRefNode = refNode;
  8356. argExprs.push_back(&appendSizeValueExpr);
  8357. BfExprEvaluator exprEvaluator(this);
  8358. BfTypedValue allocResult;
  8359. if (allocTarget.mScopedInvocationTarget != NULL)
  8360. {
  8361. SizedArray<BfTypeReference*, 2> genericArgs;
  8362. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  8363. allocResult = LoadValue(exprEvaluator.mResult);
  8364. }
  8365. else if (allocTarget.mCustomAllocator)
  8366. {
  8367. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8368. if (customTypeInst == NULL)
  8369. {
  8370. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  8371. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  8372. }
  8373. if (customTypeInst == NULL)
  8374. {
  8375. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  8376. }
  8377. else
  8378. {
  8379. BfTypedValueExpression typeValueExpr;
  8380. String allocMethodName = "Alloc";
  8381. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  8382. {
  8383. allocMethodName = "AllocTyped";
  8384. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  8385. auto typeRefVal = CreateTypeDataRef(type);
  8386. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  8387. typeValueExpr.mRefNode = refNode;
  8388. argExprs.Insert(0, &typeValueExpr);
  8389. }
  8390. if (HasMixin(customTypeInst, allocMethodName, 2))
  8391. {
  8392. BfSizedArray<BfExpression*> argExprArr;
  8393. argExprArr.mSize = (int)argExprs.size();
  8394. argExprArr.mVals = &argExprs[0];
  8395. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  8396. allocResult = exprEvaluator.GetResult();
  8397. }
  8398. else
  8399. {
  8400. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8401. BfResolvedArgs argValues(&sizedArgExprs);
  8402. exprEvaluator.ResolveArgValues(argValues);
  8403. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  8404. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  8405. }
  8406. }
  8407. }
  8408. if (allocResult)
  8409. {
  8410. if (allocResult.mType->IsVoidPtr())
  8411. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  8412. else
  8413. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  8414. return result;
  8415. }
  8416. }
  8417. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  8418. return result;
  8419. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8420. {
  8421. BfIRValue allocData = GetDbgRawAllocData(type);
  8422. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  8423. SizedArray<BfIRValue, 2> llvmArgs;
  8424. llvmArgs.push_back(sizeValue);
  8425. llvmArgs.push_back(allocData);
  8426. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  8427. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8428. }
  8429. BfModuleMethodInstance moduleMethodInstance;
  8430. moduleMethodInstance = GetInternalMethod("Malloc");
  8431. SizedArray<BfIRValue, 1> llvmArgs;
  8432. llvmArgs.push_back(sizeValue);
  8433. auto func = moduleMethodInstance.mFunc;
  8434. if ((!func) || (func.IsFake()))
  8435. {
  8436. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  8437. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  8438. }
  8439. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  8440. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  8441. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  8442. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  8443. return result;
  8444. }
  8445. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  8446. {
  8447. if (type->IsStruct())
  8448. {
  8449. auto typeInstance = type->ToTypeInstance();
  8450. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  8451. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8452. }
  8453. else if (type->IsObjectOrInterface())
  8454. {
  8455. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8456. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  8457. BF_ASSERT(moduleMethodInst.mFunc);
  8458. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8459. }
  8460. else
  8461. {
  8462. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  8463. BfExprEvaluator exprEvaluator(this);
  8464. SizedArray<BfResolvedArg, 1> resolvedArgs;
  8465. BfResolvedArg resolvedArg;
  8466. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  8467. resolvedArgs.Add(resolvedArg);
  8468. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  8469. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  8470. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  8471. BF_ASSERT(moduleMethodInst.mFunc);
  8472. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8473. }
  8474. return BfIRValue();
  8475. }
  8476. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  8477. {
  8478. BfIRValue allocDataValue;
  8479. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  8480. return allocDataValue;
  8481. BfIRValue markFuncPtr;
  8482. if (type->WantsGCMarking())
  8483. markFuncPtr = GetMarkFuncPtr(type);
  8484. else
  8485. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  8486. BfIRValue typeDataRef = CreateTypeDataRef(type);
  8487. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  8488. BfTypeInstance* typeInstance = type->ToTypeInstance();
  8489. if (typeInstance == NULL)
  8490. {
  8491. typeInstance = GetWrappedStructType(type);
  8492. if (typeInstance != NULL)
  8493. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8494. }
  8495. if (typeInstance != NULL)
  8496. PopulateType(typeInstance);
  8497. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8498. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8499. {
  8500. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8501. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8502. }
  8503. SizedArray<BfIRValue, 2> dataValues;
  8504. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8505. dataValues.Add(typeDataRef);
  8506. dataValues.Add(markFuncPtr);
  8507. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8508. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8509. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8510. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8511. return allocDataValue;
  8512. }
  8513. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8514. {
  8515. BP_ZONE("AllocFromType");
  8516. BfScopeData* scopeData = allocTarget.mScopeData;
  8517. BF_ASSERT(!type->IsVar());
  8518. auto typeInstance = type->ToTypeInstance();
  8519. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8520. typeInstance = mContext->mBfObjectType;
  8521. bool isHeapAlloc = scopeData == NULL;
  8522. bool isScopeAlloc = scopeData != NULL;
  8523. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8524. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8525. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8526. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8527. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8528. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8529. {
  8530. BfPointerType* ptrType = CreatePointerType(type);
  8531. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8532. return val;
  8533. }
  8534. if (typeInstance != NULL)
  8535. mBfIRBuilder->PopulateType(typeInstance);
  8536. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8537. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8538. {
  8539. return mBfIRBuilder->GetFakeVal();
  8540. }
  8541. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8542. BfIRValue sizeValue;
  8543. BfIRType allocType = mBfIRBuilder->MapType(type);
  8544. int allocSize = type->mSize;
  8545. int allocAlign = type->mAlign;
  8546. if (typeInstance != NULL)
  8547. {
  8548. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8549. typeInstance->mHasBeenInstantiated = true;
  8550. allocSize = typeInstance->mInstSize;
  8551. allocAlign = typeInstance->mInstAlign;
  8552. //if (typeInstance->IsEnum())
  8553. //allocType = typeInstance->mIRType;
  8554. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8555. }
  8556. if (alignOverride != -1)
  8557. allocAlign = alignOverride;
  8558. // The "dynSize" cases:
  8559. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8560. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8561. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8562. // though we'd expect their stack space to be released
  8563. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8564. {
  8565. MarkDynStack(scopeData);
  8566. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8567. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8568. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8569. BfType* voidPtrType = CreatePointerType(voidType);
  8570. if (!mCurMethodState->mDynStackRevIdx)
  8571. {
  8572. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8573. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8574. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8575. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8576. mBfIRBuilder->ClearDebugLocation(storeInst);
  8577. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8578. }
  8579. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8580. auto bytePtrType = CreatePointerType(byteType);
  8581. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8582. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8583. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8584. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8585. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8586. mBfIRBuilder->ClearDebugLocation(storeInst);
  8587. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8588. mBfIRBuilder->ClearDebugLocation(storeInst);
  8589. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8590. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8591. if (IsTargetingBeefBackend())
  8592. {
  8593. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8594. // to ensure there isn't any register collision during looping is just to not allow it to
  8595. // bind to a register at all
  8596. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8597. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8598. }
  8599. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8600. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8601. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8602. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8603. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8604. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8605. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8606. mBfIRBuilder->AddBlock(verCheckBB);
  8607. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8608. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8609. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8610. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8611. mBfIRBuilder->AddBlock(resizeBB);
  8612. mBfIRBuilder->SetInsertPoint(resizeBB);
  8613. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8614. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8615. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8616. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8617. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8618. mBfIRBuilder->CreateBr(endBB);
  8619. mBfIRBuilder->AddBlock(endBB);
  8620. mBfIRBuilder->SetInsertPoint(endBB);
  8621. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8622. };
  8623. if (isScopeAlloc)
  8624. {
  8625. if (arraySize)
  8626. {
  8627. bool isConstantArraySize = arraySize.IsConst();
  8628. if (isRawArrayAlloc)
  8629. {
  8630. BfPointerType* ptrType = CreatePointerType(type);
  8631. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8632. {
  8633. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8634. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8635. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8636. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8637. }
  8638. else
  8639. {
  8640. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8641. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8642. if (!isDynAlloc)
  8643. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8644. else
  8645. {
  8646. MarkDynStack(scopeData);
  8647. SaveStackState(scopeData);
  8648. }
  8649. int typeSize = type->GetStride();
  8650. BfIRValue allocaInst;
  8651. BfIRValue result;
  8652. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8653. {
  8654. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8655. result = allocaInst;
  8656. }
  8657. else
  8658. {
  8659. if (typeInstance->IsStruct())
  8660. typeSize = typeInstance->GetInstStride();
  8661. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8662. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8663. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8664. auto ptrType = CreatePointerType(typeInstance);
  8665. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8666. if (!isDynAlloc)
  8667. mBfIRBuilder->ClearDebugLocation(result);
  8668. }
  8669. if (!isDynAlloc)
  8670. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8671. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8672. if (!isDynAlloc)
  8673. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8674. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8675. if (arraySize.IsConst())
  8676. {
  8677. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8678. if (constant->mInt64 == 0)
  8679. noDtorCall = true;
  8680. }
  8681. if (!noDtorCall)
  8682. {
  8683. bool isConstSize = arraySize.IsConst();
  8684. BfIRBlock clearBlock;
  8685. BfIRBlock contBlock;
  8686. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8687. if (wantsDeinit)
  8688. {
  8689. BfIRBlock prevBlock;
  8690. if (!isConstSize)
  8691. {
  8692. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8693. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8694. prevBlock = mBfIRBuilder->GetInsertBlock();
  8695. mBfIRBuilder->AddBlock(clearBlock);
  8696. mBfIRBuilder->SetInsertPoint(clearBlock);
  8697. }
  8698. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8699. if (!isConstSize)
  8700. {
  8701. mBfIRBuilder->CreateBr(contBlock);
  8702. mBfIRBuilder->SetInsertPoint(prevBlock);
  8703. if (deferredCall != NULL)
  8704. {
  8705. // Zero out size args
  8706. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8707. {
  8708. auto scopedArg = deferredCall->mScopeArgs[i];
  8709. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8710. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8711. }
  8712. }
  8713. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8714. mBfIRBuilder->AddBlock(contBlock);
  8715. mBfIRBuilder->SetInsertPoint(contBlock);
  8716. }
  8717. }
  8718. }
  8719. return result;
  8720. }
  8721. }
  8722. else
  8723. {
  8724. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8725. {
  8726. // Generate and check new size
  8727. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8728. auto firstElementField = &arrayType->mFieldInstances.back();
  8729. int arrayClassSize = firstElementField->mDataOffset;
  8730. sizeValue = GetConstValue(arrayClassSize);
  8731. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8732. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8733. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8734. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8735. if (!noDtorCall)
  8736. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8737. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8738. return typedVal.mValue;
  8739. }
  8740. else
  8741. {
  8742. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8743. auto firstElementField = &arrayType->mFieldInstances.back();
  8744. if (!type->IsValuelessType())
  8745. {
  8746. int arrayClassSize = firstElementField->mDataOffset;
  8747. sizeValue = GetConstValue(arrayClassSize);
  8748. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8749. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8750. }
  8751. else
  8752. sizeValue = GetConstValue(arrayType->mInstSize);
  8753. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8754. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8755. if (!isDynAlloc)
  8756. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8757. else
  8758. {
  8759. MarkDynStack(scopeData);
  8760. SaveStackState(scopeData);
  8761. }
  8762. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8763. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8764. if (!isDynAlloc)
  8765. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8766. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8767. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8768. BfTypedValue typedVal;
  8769. if (!isDynAlloc)
  8770. {
  8771. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8772. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8773. mBfIRBuilder->ClearDebugLocation(typedVal.mValue);
  8774. mBfIRBuilder->SetInsertPoint(prevBlock);
  8775. allocaBlock = mCurMethodState->mIRInitBlock;
  8776. }
  8777. else
  8778. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8779. if (!noDtorCall)
  8780. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8781. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8782. return typedVal.mValue;
  8783. }
  8784. }
  8785. }
  8786. else if (appendSizeValue)
  8787. {
  8788. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8789. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8790. // use the "dynSize" version conservatively
  8791. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8792. {
  8793. // Generate and check new size
  8794. sizeValue = GetConstValue(typeInstance->mInstSize);
  8795. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8796. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8797. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8798. if (!noDtorCall)
  8799. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8800. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8801. return typedVal.mValue;
  8802. }
  8803. else // stack alloc, unlooped, with append
  8804. {
  8805. sizeValue = GetConstValue(typeInstance->mInstSize);
  8806. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8807. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8808. bool wasDynAlloc = isDynAlloc;
  8809. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8810. if (!isDynAlloc)
  8811. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8812. else
  8813. {
  8814. MarkDynStack(scopeData);
  8815. SaveStackState(scopeData);
  8816. }
  8817. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8818. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8819. if (!isDynAlloc)
  8820. {
  8821. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8822. }
  8823. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8824. bool mayBeLarge = false;
  8825. if (sizeValue.IsConst())
  8826. {
  8827. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8828. if (constantInt->mInt64 >= 4096)
  8829. mayBeLarge = true;
  8830. }
  8831. else
  8832. mayBeLarge = true;
  8833. if (((type->IsObject() && (!mayBeLarge))) ||
  8834. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8835. ((zeroMemory) && (!mayBeLarge)))
  8836. {
  8837. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8838. }
  8839. BfIRValue castedVal;
  8840. if (!isDynAlloc)
  8841. {
  8842. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8843. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8844. mBfIRBuilder->ClearDebugLocation(castedVal);
  8845. mBfIRBuilder->SetInsertPoint(prevBlock);
  8846. if (WantsLifetimes())
  8847. {
  8848. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8849. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8850. }
  8851. }
  8852. else
  8853. {
  8854. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8855. }
  8856. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8857. if (!noDtorCall)
  8858. {
  8859. bool doCondAlloca = false;
  8860. if (!IsTargetingBeefBackend())
  8861. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8862. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8863. }
  8864. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue, allocFlags);
  8865. return typedVal.mValue;
  8866. }
  8867. }
  8868. else // "Normal" stack alloc
  8869. {
  8870. BF_ASSERT(!sizeValue);
  8871. //TODO: If sizeValue is a constant then do this in the head IR builder
  8872. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8873. if (!isLoopedAlloc)
  8874. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8875. else
  8876. {
  8877. MarkDynStack(scopeData);
  8878. SaveStackState(scopeData);
  8879. }
  8880. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8881. if (!isLoopedAlloc)
  8882. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8883. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8884. bool mayBeLarge = allocSize >= 4096;
  8885. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8886. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8887. ((zeroMemory) && (!mayBeLarge)))
  8888. {
  8889. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8890. // and memset is always safe
  8891. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8892. }
  8893. auto typedVal = BfTypedValue(allocaInst, type);
  8894. if (!isLoopedAlloc)
  8895. {
  8896. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8897. mBfIRBuilder->SetInsertPoint(prevBlock);
  8898. if (WantsLifetimes())
  8899. {
  8900. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8901. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8902. }
  8903. }
  8904. if (!noDtorCall)
  8905. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8906. if (typeInstance != NULL)
  8907. {
  8908. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8909. }
  8910. else
  8911. {
  8912. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8913. }
  8914. return allocaInst;
  8915. }
  8916. }
  8917. else if (arraySize)
  8918. {
  8919. if (isRawArrayAlloc)
  8920. {
  8921. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8922. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8923. }
  8924. else
  8925. {
  8926. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8927. typeInstance = arrayType;
  8928. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8929. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8930. appendSizeValue = elementDataSize;
  8931. if (!type->IsSizeAligned())
  8932. {
  8933. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8934. }
  8935. }
  8936. }
  8937. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8938. {
  8939. auto vDataRef = GetClassVDataPtr(typeInstance);
  8940. BfIRValue result;
  8941. bool isResultInitialized = false;
  8942. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8943. if (typeInstance->mTypeOptionsIdx != -1)
  8944. {
  8945. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8946. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8947. }
  8948. if (mIsComptimeModule)
  8949. stackCount = 0;
  8950. if (!sizeValue)
  8951. sizeValue = GetConstValue(typeInstance->mInstSize);
  8952. if (appendSizeValue)
  8953. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8954. BfIRValue origSizeValue = sizeValue;
  8955. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8956. if (isAllocEx)
  8957. {
  8958. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8959. if (prepareStackTraceMethod)
  8960. {
  8961. SizedArray<BfIRValue, 2> irArgs;
  8962. irArgs.Add(sizeValue);
  8963. irArgs.Add(GetConstValue(stackCount));
  8964. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8965. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8966. }
  8967. }
  8968. if (allocTarget.mCustomAllocator)
  8969. {
  8970. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8971. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8972. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8973. {
  8974. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8975. mBfIRBuilder->PopulateType(classVDataType);
  8976. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8977. mBfIRBuilder->PopulateType(typeInstType);
  8978. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8979. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8980. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8981. BfTypedValueExpression typedValueExpr;
  8982. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8983. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8984. BfExprEvaluator exprEvaluator(this);
  8985. SizedArray<BfExpression*, 2> argExprs;
  8986. argExprs.push_back(&typedValueExpr);
  8987. BfTypedValueExpression sizeValueExpr;
  8988. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8989. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8990. argExprs.push_back(&sizeValueExpr);
  8991. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8992. BfResolvedArgs argValues(&sizedArgExprs);
  8993. exprEvaluator.ResolveArgValues(argValues);
  8994. exprEvaluator.mNoBind = true;
  8995. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8996. if (allocResult)
  8997. {
  8998. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8999. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  9000. else
  9001. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  9002. isResultInitialized = true;
  9003. }
  9004. }
  9005. }
  9006. bool wasAllocated = false;
  9007. if (!result)
  9008. {
  9009. if (hasCustomAllocator)
  9010. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  9011. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9012. {
  9013. SizedArray<BfIRValue, 4> llvmArgs;
  9014. llvmArgs.push_back(sizeValue);
  9015. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9016. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9017. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  9018. wasAllocated = true;
  9019. }
  9020. }
  9021. if (result)
  9022. {
  9023. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9024. {
  9025. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  9026. SizedArray<BfIRValue, 4> llvmArgs;
  9027. llvmArgs.push_back(objectPtr);
  9028. llvmArgs.push_back(origSizeValue);
  9029. llvmArgs.push_back(vDataRef);
  9030. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  9031. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  9032. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  9033. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  9034. if (wasAllocated)
  9035. {
  9036. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  9037. auto bytePtrType = CreatePointerType(byteType);
  9038. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  9039. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  9040. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  9041. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  9042. }
  9043. }
  9044. else
  9045. {
  9046. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  9047. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9048. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  9049. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  9050. }
  9051. }
  9052. else
  9053. {
  9054. if ((mBfIRBuilder->mIgnoreWrites) ||
  9055. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  9056. {
  9057. if (mBfIRBuilder->mIgnoreWrites)
  9058. {
  9059. return GetDefaultValue(typeInstance);
  9060. }
  9061. else
  9062. {
  9063. // Fake with alloca
  9064. mBfIRBuilder->PopulateType(typeInstance);
  9065. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInstance));
  9066. }
  9067. }
  9068. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  9069. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  9070. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9071. {
  9072. SizedArray<BfIRValue, 4> llvmArgs;
  9073. llvmArgs.push_back(vData);
  9074. llvmArgs.push_back(sizeValue);
  9075. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  9076. llvmArgs.push_back(GetConstValue(stackCount));
  9077. llvmArgs.push_back(GetConstValue(allocFlags, GetPrimitiveType(BfTypeCode_Int8)));
  9078. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 5);
  9079. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  9080. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9081. }
  9082. else
  9083. {
  9084. SizedArray<BfIRValue, 4> llvmArgs;
  9085. llvmArgs.push_back(sizeValue);
  9086. BfIRFunction irFunc;
  9087. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  9088. {
  9089. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  9090. irFunc = moduleMethodInstance.mFunc;
  9091. }
  9092. if (!irFunc)
  9093. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  9094. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  9095. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  9096. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  9097. if (mIsComptimeModule)
  9098. {
  9099. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  9100. }
  9101. mBfIRBuilder->CreateStore(vData, vdataPtr);
  9102. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  9103. }
  9104. }
  9105. if ((zeroMemory) && (arraySize))
  9106. {
  9107. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9108. typeInstance = arrayType;
  9109. auto firstElementField = &arrayType->mFieldInstances.back();
  9110. int arrayClassSize = firstElementField->mDataOffset;
  9111. BfIRValue elementDataSize;
  9112. bool skipZero = false;
  9113. if (arraySize.IsConst())
  9114. {
  9115. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  9116. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  9117. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  9118. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  9119. if (constVal->mInt64 <= 0)
  9120. skipZero = true;
  9121. }
  9122. else
  9123. {
  9124. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  9125. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  9126. }
  9127. if (!skipZero)
  9128. {
  9129. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  9130. auto ptrType = CreatePointerType(i8Type);
  9131. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  9132. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  9133. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  9134. appendSizeValue = elementDataSize;
  9135. }
  9136. }
  9137. return result;
  9138. }
  9139. else
  9140. {
  9141. if (!sizeValue)
  9142. sizeValue = GetConstValue(allocSize);
  9143. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  9144. }
  9145. }
  9146. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  9147. {
  9148. if ((type == NULL) || (refNode == NULL))
  9149. return;
  9150. auto typeInstance = type->ToTypeInstance();
  9151. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  9152. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  9153. }
  9154. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  9155. {
  9156. if (align <= 1)
  9157. return;
  9158. if (sizeMultiple == 0)
  9159. sizeMultiple = align;
  9160. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  9161. {
  9162. if (!IsAllocatorAligned())
  9163. {
  9164. // Don't align
  9165. }
  9166. else if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  9167. {
  9168. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9169. BF_ASSERT(localVar->mName == "__appendIdx");
  9170. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  9171. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9172. if (align > 1)
  9173. {
  9174. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9175. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9176. }
  9177. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  9178. }
  9179. else
  9180. {
  9181. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  9182. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  9183. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  9184. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  9185. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  9186. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  9187. }
  9188. }
  9189. if (mCurMethodState->mCurAppendAlign == 0)
  9190. mCurMethodState->mCurAppendAlign = sizeMultiple;
  9191. else
  9192. {
  9193. if (sizeMultiple % align == 0)
  9194. mCurMethodState->mCurAppendAlign = align;
  9195. else
  9196. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  9197. }
  9198. }
  9199. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  9200. {
  9201. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  9202. BF_ASSERT(localVar->mName == "__appendIdx");
  9203. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  9204. BfIRValue retValue;
  9205. BfTypeInstance* retTypeInstance = NULL;
  9206. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  9207. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  9208. if (arraySize)
  9209. {
  9210. if (isRawArrayAlloc)
  9211. {
  9212. EmitAppendAlign(type->mAlign);
  9213. BfPointerType* ptrType = CreatePointerType(type);
  9214. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9215. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9216. if (mSystem->mPtrSize != 4)
  9217. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9218. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9219. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9220. if (zeroMemory)
  9221. {
  9222. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  9223. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  9224. }
  9225. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  9226. }
  9227. else
  9228. {
  9229. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  9230. EmitAppendAlign(arrayType->mAlign, type->mSize);
  9231. auto firstElementField = &arrayType->mFieldInstances.back();
  9232. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  9233. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  9234. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  9235. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  9236. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9237. if (mSystem->mPtrSize != 4)
  9238. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9239. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9240. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9241. if (zeroMemory)
  9242. {
  9243. // Only zero out the actual elements
  9244. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  9245. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  9246. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  9247. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  9248. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  9249. }
  9250. retTypeInstance = arrayType;
  9251. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  9252. }
  9253. }
  9254. else
  9255. {
  9256. auto typeInst = type->ToTypeInstance();
  9257. BfIRValue sizeValue;
  9258. BfIRType toType;
  9259. if (typeInst != NULL)
  9260. {
  9261. mBfIRBuilder->PopulateType(typeInst);
  9262. if (typeInst->WantsGCMarking())
  9263. mCurTypeInstance->mHasAppendWantMark = true;
  9264. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  9265. sizeValue = GetConstValue(typeInst->mInstSize);
  9266. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  9267. }
  9268. else
  9269. {
  9270. EmitAppendAlign(type->mAlign, type->mSize);
  9271. sizeValue = GetConstValue(type->mSize);
  9272. auto toPtrType = CreatePointerType(type);
  9273. toType = mBfIRBuilder->MapType(toPtrType);
  9274. }
  9275. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9276. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  9277. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9278. retTypeInstance = typeInst;
  9279. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  9280. if ((typeInst != NULL) && (typeInst->WantsGCMarking()) && (mCompiler->mOptions.mDebugAlloc))
  9281. {
  9282. auto curThis = GetThis();
  9283. auto thisObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), curThis, mContext->mBfObjectType);
  9284. if (typeInst->IsObject())
  9285. {
  9286. auto appendedObj = Cast(mCurMethodInstance->mMethodDef->GetRefNode(), BfTypedValue(retValue, typeInst), mContext->mBfObjectType);
  9287. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_ObjectAppended", 2);
  9288. SizedArray<BfIRValue, 2> llvmArgs;
  9289. llvmArgs.push_back(thisObj.mValue);
  9290. llvmArgs.push_back(appendedObj.mValue);
  9291. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9292. }
  9293. else
  9294. {
  9295. // Raw
  9296. BfIRValue allocPtr = mBfIRBuilder->CreateBitCast(retValue, mBfIRBuilder->MapType(voidPtrType));
  9297. BfIRValue allocData = GetDbgRawAllocData(type);
  9298. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAppended", 3);
  9299. SizedArray<BfIRValue, 3> llvmArgs;
  9300. llvmArgs.push_back(thisObj.mValue);
  9301. llvmArgs.push_back(allocPtr);
  9302. llvmArgs.push_back(allocData);
  9303. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  9304. }
  9305. }
  9306. }
  9307. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  9308. {
  9309. mBfIRBuilder->PopulateType(retTypeInstance);
  9310. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  9311. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  9312. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  9313. auto curThis = GetThis();
  9314. BfIRValue newFlags;
  9315. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9316. {
  9317. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  9318. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  9319. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  9320. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  9321. }
  9322. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  9323. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  9324. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  9325. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  9326. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9327. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9328. {
  9329. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  9330. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  9331. }
  9332. }
  9333. if (appendSizeValue)
  9334. {
  9335. EmitAppendAlign(appendAllocAlign);
  9336. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  9337. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  9338. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  9339. }
  9340. return retValue;
  9341. }
  9342. bool BfModule::IsOptimized()
  9343. {
  9344. if (mProject == NULL)
  9345. return false;
  9346. if (mIsComptimeModule)
  9347. return false;
  9348. int optLevel = GetModuleOptions().mOptLevel;
  9349. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  9350. }
  9351. bool BfModule::IsTargetingBeefBackend()
  9352. {
  9353. if (mProject == NULL)
  9354. return true;
  9355. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9356. }
  9357. bool BfModule::WantsLifetimes()
  9358. {
  9359. if (mBfIRBuilder->mIgnoreWrites)
  9360. return false;
  9361. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  9362. return true;
  9363. else if (mProject == NULL)
  9364. return false;
  9365. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  9366. }
  9367. bool BfModule::HasCompiledOutput()
  9368. {
  9369. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  9370. }
  9371. bool BfModule::HasExecutedOutput()
  9372. {
  9373. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  9374. }
  9375. // We will skip the object access check for any occurrences of this value
  9376. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  9377. {
  9378. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9379. return;
  9380. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9381. return;
  9382. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  9383. return;
  9384. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  9385. }
  9386. bool BfModule::WantsObjectAccessCheck(BfType* type)
  9387. {
  9388. if ((mBfIRBuilder->mIgnoreWrites) || (!type->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9389. return false;
  9390. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9391. return false;
  9392. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9393. auto typeOptions = GetTypeOptions();
  9394. if (typeOptions != NULL)
  9395. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9396. if (!emitObjectAccessCheck)
  9397. return false;
  9398. return true;
  9399. }
  9400. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  9401. {
  9402. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  9403. return;
  9404. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  9405. return;
  9406. if (typedVal.mValue.IsConst())
  9407. {
  9408. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9409. if (stringIdx != -1)
  9410. return;
  9411. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9412. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9413. return;
  9414. if (constant->mConstType == BfConstType_BitCastNull)
  9415. return;
  9416. }
  9417. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  9418. auto typeOptions = GetTypeOptions();
  9419. if (typeOptions != NULL)
  9420. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  9421. if (!emitObjectAccessCheck)
  9422. return;
  9423. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  9424. {
  9425. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  9426. return;
  9427. }
  9428. if (typedVal.IsAddr())
  9429. typedVal = LoadValue(typedVal);
  9430. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  9431. }
  9432. bool BfModule::WantsDebugHelpers()
  9433. {
  9434. if (mBfIRBuilder->mIgnoreWrites)
  9435. return false;
  9436. if (mIsComptimeModule)
  9437. {
  9438. // Always add
  9439. }
  9440. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  9441. return false;
  9442. return true;
  9443. }
  9444. void BfModule::EmitEnsureInstructionAt()
  9445. {
  9446. if (!WantsDebugHelpers())
  9447. return;
  9448. mBfIRBuilder->CreateEnsureInstructionAt();
  9449. }
  9450. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  9451. {
  9452. if (mBfIRBuilder->mIgnoreWrites)
  9453. return; // Nothing needed here
  9454. auto irb = mBfIRBuilder;
  9455. auto checkBB = irb->CreateBlock("as.check");
  9456. auto isNull = irb->CreateIsNull(targetValue.mValue);
  9457. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  9458. if (mIsComptimeModule)
  9459. {
  9460. AddBasicBlock(checkBB);
  9461. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9462. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  9463. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9464. return;
  9465. }
  9466. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  9467. auto intPtrType = CreatePointerType(intType);
  9468. auto intPtrPtrType = CreatePointerType(intPtrType);
  9469. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  9470. auto int32PtrType = CreatePointerType(int32Type);
  9471. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  9472. if (mCompiler->mOptions.mAllowHotSwapping)
  9473. {
  9474. BfExprEvaluator exprEvaluator(this);
  9475. AddBasicBlock(checkBB);
  9476. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9477. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  9478. SizedArray<BfIRValue, 4> irArgs;
  9479. irArgs.push_back(objectParam);
  9480. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  9481. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  9482. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  9483. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9484. }
  9485. else
  9486. {
  9487. AddBasicBlock(checkBB);
  9488. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  9489. vDataPtr = irb->CreateLoad(vDataPtr);
  9490. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  9491. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  9492. if (targetType->IsInterface())
  9493. {
  9494. auto targetTypeInst = targetType->ToTypeInstance();
  9495. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9496. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  9497. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  9498. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9499. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  9500. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  9501. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  9502. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  9503. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  9504. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9505. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  9506. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  9507. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9508. }
  9509. else
  9510. {
  9511. if (!targetType->IsTypeInstance())
  9512. targetType = GetWrappedStructType(targetType);
  9513. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9514. int inheritanceIdOfs = mSystem->mPtrSize * mCompiler->GetVDataPrefixDataCount();
  9515. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  9516. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  9517. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  9518. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  9519. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  9520. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  9521. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  9522. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9523. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  9524. fieldInst = &typeTypeInstance->mFieldInstances[10];
  9525. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  9526. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  9527. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  9528. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  9529. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  9530. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  9531. }
  9532. }
  9533. }
  9534. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  9535. {
  9536. if (mBfIRBuilder->mIgnoreWrites)
  9537. return;
  9538. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  9539. auto typeOptions = GetTypeOptions();
  9540. if (typeOptions != NULL)
  9541. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  9542. if (emitDynamicCastCheck)
  9543. {
  9544. int wantTypeId = 0;
  9545. if (!type->IsGenericParam())
  9546. wantTypeId = type->mTypeId;
  9547. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  9548. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  9549. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  9550. AddBasicBlock(failBlock);
  9551. if (mIsComptimeModule)
  9552. {
  9553. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9554. }
  9555. else
  9556. {
  9557. SizedArray<BfIRValue, 8> llvmArgs;
  9558. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9559. llvmArgs.push_back(bitAddr);
  9560. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9561. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9562. BF_ASSERT(objDynCheck);
  9563. if (objDynCheck)
  9564. {
  9565. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9566. }
  9567. }
  9568. mBfIRBuilder->CreateBr(endBlock);
  9569. AddBasicBlock(endBlock);
  9570. }
  9571. }
  9572. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9573. {
  9574. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9575. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9576. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9577. {
  9578. if (toType == mContext->mBfObjectType)
  9579. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9580. if (toType->IsBoxed())
  9581. {
  9582. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9583. if (boxedType->mElementType->IsGenericParam())
  9584. {
  9585. if (typedVal.mType == boxedType->mElementType)
  9586. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9587. else
  9588. return BfTypedValue();
  9589. }
  9590. }
  9591. }
  9592. BP_ZONE("BoxValue");
  9593. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9594. if (typedVal.mType->IsNullable())
  9595. {
  9596. typedVal = MakeAddressable(typedVal);
  9597. auto innerType = typedVal.mType->GetUnderlyingType();
  9598. if (!innerType->IsValueType())
  9599. {
  9600. if (!mIgnoreErrors)
  9601. Fail("Only value types can be boxed", srcNode);
  9602. return BfTypedValue();
  9603. }
  9604. auto boxedType = CreateBoxedType(innerType);
  9605. auto resultType = toType;
  9606. if (resultType == NULL)
  9607. resultType = boxedType;
  9608. if (mBfIRBuilder->mIgnoreWrites)
  9609. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9610. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9611. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9612. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9613. mBfIRBuilder->PopulateType(typedVal.mType);
  9614. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9615. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9616. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9617. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9618. mBfIRBuilder->AddBlock(boxBB);
  9619. mBfIRBuilder->SetInsertPoint(boxBB);
  9620. BfScopeData newScope;
  9621. newScope.mOuterIsConditional = true;
  9622. mCurMethodState->AddScope(&newScope);
  9623. NewScopeState();
  9624. BfIRValue nullableValueAddr;
  9625. BfIRValue loadedVal;
  9626. if (innerType->IsValuelessType())
  9627. {
  9628. loadedVal = mBfIRBuilder->GetFakeVal();
  9629. }
  9630. else
  9631. {
  9632. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9633. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9634. }
  9635. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9636. RestoreScopeState();
  9637. if (!boxedVal)
  9638. return BfTypedValue();
  9639. mBfIRBuilder->CreateBr(endBB);
  9640. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9641. mBfIRBuilder->AddBlock(endBB);
  9642. mBfIRBuilder->SetInsertPoint(endBB);
  9643. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9644. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9645. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9646. return BfTypedValue(phi, resultType);
  9647. }
  9648. bool alreadyCheckedCast = false;
  9649. BfTypeInstance* toTypeInstance = NULL;
  9650. if (toType != NULL)
  9651. toTypeInstance = toType->ToTypeInstance();
  9652. bool isStructPtr = typedVal.mType->IsStructPtr();
  9653. if (fromStructTypeInstance == NULL)
  9654. {
  9655. auto primType = (BfPrimitiveType*)typedVal.mType;
  9656. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9657. {
  9658. // Can always do IHashable
  9659. alreadyCheckedCast = true;
  9660. }
  9661. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9662. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9663. else
  9664. {
  9665. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9666. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9667. fromStructTypeInstance = checkStructTypeInstance;
  9668. }
  9669. if (isStructPtr)
  9670. {
  9671. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9672. alreadyCheckedCast = true;
  9673. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9674. }
  9675. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9676. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9677. }
  9678. if (fromStructTypeInstance == NULL)
  9679. return BfTypedValue();
  9680. // Need to box it
  9681. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9682. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9683. {
  9684. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9685. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9686. auto boxedType = CreateBoxedType(typedVal.mType);
  9687. mBfIRBuilder->PopulateType(boxedType);
  9688. if (wantConst)
  9689. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9690. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9691. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9692. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9693. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9694. if (boxedType->IsUnspecializedType())
  9695. {
  9696. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9697. }
  9698. else
  9699. {
  9700. PopulateType(fromStructTypeInstance);
  9701. if (!fromStructTypeInstance->IsValuelessType())
  9702. {
  9703. typedVal = LoadValue(typedVal);
  9704. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9705. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9706. {
  9707. auto ptrType = CreatePointerType(typedVal.mType);
  9708. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9709. }
  9710. if (typedVal.IsSplat())
  9711. {
  9712. AggregateSplatIntoAddr(typedVal, valPtr);
  9713. }
  9714. else
  9715. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9716. }
  9717. }
  9718. if (toType == NULL)
  9719. {
  9720. return BfTypedValue(allocaInst, boxedType);
  9721. }
  9722. else
  9723. {
  9724. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9725. return BfTypedValue(castedValue, toType);
  9726. }
  9727. }
  9728. return BfTypedValue();
  9729. }
  9730. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9731. {
  9732. BfTypeInstance* checkTypeInst = typeInst;
  9733. while (checkTypeInst != NULL)
  9734. {
  9735. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9736. {
  9737. if (checkProp->mName == propDef->mName)
  9738. {
  9739. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9740. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9741. {
  9742. propDef = checkProp;
  9743. typeInst = checkTypeInst;
  9744. return true;
  9745. }
  9746. }
  9747. }
  9748. checkTypeInst = checkTypeInst->mBaseType;
  9749. }
  9750. return false;
  9751. }
  9752. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9753. {
  9754. if (typeInstance->IsDeleting())
  9755. {
  9756. mCompiler->RequestExtraCompile();
  9757. InternalError("GetRawMethodInstanceAtIdx for deleted type", typeInstance->mTypeDef->GetRefNode());
  9758. return NULL;
  9759. }
  9760. if (!typeInstance->mResolvingVarField)
  9761. {
  9762. if (!typeInstance->DefineStateAllowsStaticMethods())
  9763. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9764. }
  9765. else
  9766. {
  9767. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9768. {
  9769. AssertErrorState();
  9770. return NULL;
  9771. }
  9772. }
  9773. if (assertName != NULL)
  9774. {
  9775. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9776. }
  9777. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9778. {
  9779. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9780. {
  9781. InternalError("OOB in GetRawMethodInstanceAtIdx");
  9782. }
  9783. return NULL;
  9784. }
  9785. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9786. if (methodGroup.mDefault == NULL)
  9787. {
  9788. if (!mCompiler->mIsResolveOnly)
  9789. {
  9790. // Get it from the owning module so we don't create a reference prematurely...
  9791. auto declModule = typeInstance->mModule;
  9792. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9793. {
  9794. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9795. if (!declModule->mIsScratchModule)
  9796. declModule->mOnDemandMethodCount++;
  9797. }
  9798. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9799. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9800. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9801. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9802. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9803. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9804. }
  9805. else
  9806. {
  9807. auto declModule = typeInstance->mModule;
  9808. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9809. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9810. }
  9811. }
  9812. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9813. //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
  9814. // be from a call to the NON-raw version
  9815. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9816. // {
  9817. // methodInstance->mIsReified = mIsReified;
  9818. // if (methodInstance->mMethodProcessRequest == NULL)
  9819. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9820. // }
  9821. return methodInstance;
  9822. }
  9823. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9824. {
  9825. if (methodDef->mIsLocalMethod)
  9826. {
  9827. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9828. }
  9829. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9830. }
  9831. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9832. {
  9833. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9834. while (typeInstance != NULL)
  9835. {
  9836. typeInstance->mTypeDef->PopulateMemberSets();
  9837. BfMemberSetEntry* entry = NULL;
  9838. BfMethodDef* methodDef = NULL;
  9839. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9840. methodDef = (BfMethodDef*)entry->mMemberDef;
  9841. while (methodDef != NULL)
  9842. {
  9843. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9844. (methodDef->mGenericParams.size() == 0) &&
  9845. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9846. return GetRawMethodInstance(typeInstance, methodDef);
  9847. methodDef = methodDef->mNextWithSameName;
  9848. }
  9849. if (!checkBase)
  9850. break;
  9851. typeInstance = typeInstance->mBaseType;
  9852. }
  9853. return NULL;
  9854. }
  9855. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9856. {
  9857. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9858. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9859. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9860. if (!useUnspecializedType)
  9861. return methodInstance;
  9862. if (!owner->IsGenericTypeInstance())
  9863. return methodInstance;
  9864. if ((owner->IsDelegateFromTypeRef()) ||
  9865. (owner->IsFunctionFromTypeRef()) ||
  9866. (owner->IsTuple()))
  9867. {
  9868. return methodInstance;
  9869. }
  9870. auto genericType = (BfTypeInstance*)owner;
  9871. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9872. return methodInstance;
  9873. if (methodInstance->mMethodDef->mIsLocalMethod)
  9874. return methodInstance;
  9875. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9876. return methodInstance;
  9877. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9878. if (unspecializedType == NULL)
  9879. {
  9880. AssertErrorState();
  9881. return methodInstance;
  9882. }
  9883. if (unspecializedType == NULL)
  9884. return methodInstance;
  9885. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9886. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9887. }
  9888. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9889. {
  9890. int genericCount = 0;
  9891. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9892. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9893. {
  9894. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9895. if (param->IsGenericParam())
  9896. genericCount++;
  9897. }
  9898. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9899. genericCount++;
  9900. return genericCount;
  9901. }
  9902. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9903. {
  9904. BF_ASSERT(!mIsScratchModule);
  9905. BF_ASSERT(mIsReified);
  9906. BfModule* mainModule = this;
  9907. if (mParentModule != NULL)
  9908. mainModule = mParentModule;
  9909. BfModule* specModule = NULL;
  9910. BfModule** specModulePtr = NULL;
  9911. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9912. {
  9913. return *specModulePtr;
  9914. }
  9915. else
  9916. {
  9917. String specModuleName = mModuleName;
  9918. for (auto bfProject : projectList)
  9919. {
  9920. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9921. }
  9922. specModule = new BfModule(mContext, specModuleName);
  9923. specModule->mProject = mainModule->mProject;
  9924. specModule->mParentModule = mainModule;
  9925. specModule->mIsSpecializedMethodModuleRoot = true;
  9926. specModule->Init();
  9927. Array<BfProject*> projList;
  9928. for (auto project : projectList)
  9929. projList.Add(project);
  9930. mainModule->mSpecializedMethodModules[projList] = specModule;
  9931. }
  9932. return specModule;
  9933. }
  9934. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9935. {
  9936. if (IsSkippingExtraResolveChecks())
  9937. return BfIRValue();
  9938. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9939. {
  9940. //BF_ASSERT(!methodInstance->mIRFunction);
  9941. return BfIRValue();
  9942. }
  9943. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  9944. FinishInit();
  9945. auto methodDef = methodInstance->mMethodDef;
  9946. StringT<4096> methodName;
  9947. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9948. if (isInlined != methodInstance->mAlwaysInline)
  9949. {
  9950. if (isInlined)
  9951. methodName += "__INLINE";
  9952. else
  9953. methodName += "__NOINLINE";
  9954. }
  9955. if (tryExisting)
  9956. {
  9957. auto func = mBfIRBuilder->GetFunction(methodName);
  9958. if (func)
  9959. return func;
  9960. }
  9961. auto intrinsic = GetIntrinsic(methodInstance);
  9962. if (intrinsic)
  9963. return intrinsic;
  9964. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9965. {
  9966. return CreateDllImportGlobalVar(methodInstance, false);
  9967. }
  9968. BfIRType returnType;
  9969. SizedArray<BfIRType, 8> paramTypes;
  9970. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9971. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9972. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9973. auto callingConv = GetIRCallingConvention(methodInstance);
  9974. if (callingConv != BfIRCallingConv_CDecl)
  9975. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9976. SetupIRMethod(methodInstance, func, isInlined);
  9977. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9978. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9979. // {
  9980. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9981. // {
  9982. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9983. // }
  9984. // }
  9985. return func;
  9986. }
  9987. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9988. {
  9989. if (assertName != NULL)
  9990. {
  9991. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9992. }
  9993. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9994. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9995. return BfModuleMethodInstance();
  9996. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9997. BfMethodDef* methodDef = NULL;
  9998. BfTypeInstance* foreignType = NULL;
  9999. if (methodInstance != NULL)
  10000. {
  10001. methodDef = methodInstance->mMethodDef;
  10002. if (methodInstance->mMethodInfoEx != NULL)
  10003. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  10004. }
  10005. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  10006. {
  10007. // Can't use it, not reified
  10008. methodInstance = NULL;
  10009. }
  10010. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  10011. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  10012. {
  10013. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  10014. return BfModuleMethodInstance(methodInstance, func);
  10015. }
  10016. if (foreignType != NULL)
  10017. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  10018. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  10019. }
  10020. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10021. {
  10022. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10023. while (typeInstance != NULL)
  10024. {
  10025. typeInstance->mTypeDef->PopulateMemberSets();
  10026. BfMemberSetEntry* entry = NULL;
  10027. BfMethodDef* methodDef = NULL;
  10028. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10029. methodDef = (BfMethodDef*)entry->mMemberDef;
  10030. while (methodDef != NULL)
  10031. {
  10032. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10033. (methodDef->mGenericParams.size() == 0) &&
  10034. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10035. {
  10036. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10037. if (moduleMethodInstance)
  10038. return moduleMethodInstance;
  10039. }
  10040. methodDef = methodDef->mNextWithSameName;
  10041. }
  10042. if (!checkBase)
  10043. break;
  10044. typeInstance = typeInstance->mBaseType;
  10045. }
  10046. return BfModuleMethodInstance();
  10047. }
  10048. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  10049. {
  10050. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10051. while (typeInstance != NULL)
  10052. {
  10053. typeInstance->mTypeDef->PopulateMemberSets();
  10054. BfMemberSetEntry* entry = NULL;
  10055. BfMethodDef* methodDef = NULL;
  10056. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10057. methodDef = (BfMethodDef*)entry->mMemberDef;
  10058. while (methodDef != NULL)
  10059. {
  10060. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10061. (methodDef->mGenericParams.size() == 0) &&
  10062. (paramTypes.size() == methodDef->mParams.size()))
  10063. {
  10064. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  10065. if (moduleMethodInstance.mMethodInstance != NULL)
  10066. {
  10067. bool matches = true;
  10068. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  10069. {
  10070. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  10071. matches = false;
  10072. }
  10073. if (matches)
  10074. return moduleMethodInstance;
  10075. }
  10076. }
  10077. methodDef = methodDef->mNextWithSameName;
  10078. }
  10079. if (!checkBase)
  10080. break;
  10081. typeInstance = typeInstance->mBaseType;
  10082. }
  10083. return BfModuleMethodInstance();
  10084. }
  10085. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  10086. {
  10087. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  10088. PopulateType(internalType);
  10089. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  10090. if (!moduleMethodInstance)
  10091. {
  10092. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  10093. }
  10094. return moduleMethodInstance;
  10095. }
  10096. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  10097. {
  10098. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  10099. typeInstance->mOperatorInfo.Add(NULL);
  10100. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  10101. {
  10102. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  10103. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  10104. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  10105. BfTypeState typeState;
  10106. typeState.mType = typeInstance;
  10107. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  10108. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  10109. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  10110. if (operatorDef->mReturnTypeRef != NULL)
  10111. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  10112. if (operatorDef->mParams.size() >= 1)
  10113. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  10114. if (operatorDef->mParams.size() >= 2)
  10115. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  10116. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  10117. }
  10118. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  10119. }
  10120. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  10121. {
  10122. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  10123. if (operatorInfo == NULL)
  10124. return NULL;
  10125. if (operatorInfo->mReturnType == NULL)
  10126. return NULL;
  10127. auto castFlags = BfCastFlags_IsConstraintCheck;
  10128. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10129. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  10130. if (lhs)
  10131. {
  10132. if (operatorInfo->mLHSType == NULL)
  10133. return NULL;
  10134. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  10135. return NULL;
  10136. }
  10137. if (rhs)
  10138. {
  10139. if (operatorInfo->mRHSType == NULL)
  10140. return NULL;
  10141. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  10142. return NULL;
  10143. }
  10144. return operatorInfo->mReturnType;
  10145. }
  10146. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10147. {
  10148. while (typeInstance != NULL)
  10149. {
  10150. typeInstance->mTypeDef->PopulateMemberSets();
  10151. BfMemberSetEntry* entry = NULL;
  10152. BfMethodDef* methodDef = NULL;
  10153. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10154. methodDef = (BfMethodDef*)entry->mMemberDef;
  10155. while (methodDef != NULL)
  10156. {
  10157. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  10158. (methodDef->mGenericParams.size() == 0) &&
  10159. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10160. {
  10161. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  10162. if (!methodInstanceGroup.IsImplemented())
  10163. return false;
  10164. if (methodInstanceGroup.mDefault == NULL)
  10165. return false;
  10166. return methodInstanceGroup.mDefault->mIsReified;
  10167. }
  10168. methodDef = methodDef->mNextWithSameName;
  10169. }
  10170. if (!checkBase)
  10171. break;
  10172. typeInstance = typeInstance->mBaseType;
  10173. }
  10174. return false;
  10175. }
  10176. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  10177. {
  10178. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  10179. while (typeInstance != NULL)
  10180. {
  10181. typeInstance->mTypeDef->PopulateMemberSets();
  10182. BfMemberSetEntry* entry = NULL;
  10183. BfMethodDef* methodDef = NULL;
  10184. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  10185. methodDef = (BfMethodDef*)entry->mMemberDef;
  10186. while (methodDef != NULL)
  10187. {
  10188. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  10189. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  10190. return true;
  10191. methodDef = methodDef->mNextWithSameName;
  10192. }
  10193. if (!checkBase)
  10194. break;
  10195. typeInstance = typeInstance->mBaseType;
  10196. }
  10197. return BfModuleMethodInstance();
  10198. }
  10199. String BfModule::FieldToString(BfFieldInstance* fieldInstance)
  10200. {
  10201. auto result = TypeToString(fieldInstance->mOwner);
  10202. result += ".";
  10203. auto fieldDef = fieldInstance->GetFieldDef();
  10204. if (fieldDef != NULL)
  10205. result += fieldDef->mName;
  10206. else
  10207. result += "???";
  10208. return result;
  10209. }
  10210. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  10211. {
  10212. auto methodDef = methodInst->mMethodDef;
  10213. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  10214. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10215. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  10216. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  10217. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10218. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10219. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  10220. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10221. if (allowResolveGenericParamNames)
  10222. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10223. StringT<128> methodName;
  10224. auto _AddTypeName = [&](BfType* type)
  10225. {
  10226. auto typeNameFlags = BfTypeNameFlags_None;
  10227. if (allowResolveGenericParamNames)
  10228. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10229. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  10230. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  10231. methodName += TypeToString(type, typeNameFlags);
  10232. };
  10233. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  10234. {
  10235. _AddTypeName(methodInst->mReturnType);
  10236. methodName += " ";
  10237. }
  10238. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  10239. {
  10240. methodName += TypeToString(type, typeNameFlags);
  10241. if (methodName == "$")
  10242. methodName = "";
  10243. else if (!methodName.IsEmpty())
  10244. methodName += ".";
  10245. }
  10246. String accessorString;
  10247. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  10248. if (methodInst->mMethodDef->mIsLocalMethod)
  10249. {
  10250. int atPos = (int)methodDefName.IndexOf('$');
  10251. methodDefName.RemoveToEnd(atPos);
  10252. methodDefName.Replace("@", ".");
  10253. }
  10254. else
  10255. {
  10256. int atPos = (int)methodDefName.IndexOf('$');
  10257. if (atPos != -1)
  10258. {
  10259. accessorString = methodDefName.Substring(0, atPos);
  10260. if ((accessorString == "get") || (accessorString == "set"))
  10261. {
  10262. methodDefName = methodDefName.Substring(atPos + 1);
  10263. }
  10264. else
  10265. accessorString = "";
  10266. }
  10267. }
  10268. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  10269. {
  10270. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10271. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10272. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10273. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  10274. methodName += ".";
  10275. }
  10276. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  10277. {
  10278. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  10279. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10280. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  10281. methodName += "[";
  10282. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  10283. methodName += "].";
  10284. }
  10285. if (methodDef->mMethodType == BfMethodType_Operator)
  10286. {
  10287. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  10288. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  10289. {
  10290. // Don't add explicit/implicit part, since that's not available in GCC mangling
  10291. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  10292. {
  10293. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10294. methodName += "explicit ";
  10295. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  10296. methodName += "explicit ";
  10297. }*/
  10298. methodName += "operator ";
  10299. if (methodInst->mReturnType != NULL)
  10300. methodName += TypeToString(methodInst->mReturnType);
  10301. }
  10302. else
  10303. {
  10304. methodName += "operator";
  10305. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  10306. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  10307. }
  10308. }
  10309. else if (methodDef->mMethodType == BfMethodType_Ctor)
  10310. {
  10311. if (methodDef->mIsStatic)
  10312. methodName += "__BfStaticCtor";
  10313. else
  10314. methodName += "this";
  10315. accessorString = "";
  10316. }
  10317. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  10318. {
  10319. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10320. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10321. {
  10322. methodName += "get indexer";
  10323. }
  10324. else
  10325. {
  10326. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10327. propertyDecl->mNameNode->ToString(methodName);
  10328. methodName += " get accessor";
  10329. return methodName;
  10330. }
  10331. }
  10332. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10333. {
  10334. auto propertyDecl = methodDef->GetPropertyDeclaration();
  10335. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  10336. {
  10337. methodName += "set indexer";
  10338. }
  10339. else
  10340. {
  10341. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  10342. propertyDecl->mNameNode->ToString(methodName);
  10343. methodName += " set accessor";
  10344. return methodName;
  10345. }
  10346. }
  10347. else
  10348. methodName += methodDefName;
  10349. if (methodDef->mMethodType == BfMethodType_Mixin)
  10350. methodName += "!";
  10351. BfTypeVector newMethodGenericArgs;
  10352. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  10353. {
  10354. methodName += "<";
  10355. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  10356. {
  10357. if (i > 0)
  10358. methodName += ", ";
  10359. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  10360. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  10361. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  10362. if (allowResolveGenericParamNames)
  10363. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  10364. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  10365. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  10366. {
  10367. bool hasEmpty = false;
  10368. for (auto arg : *methodGenericArgs)
  10369. {
  10370. if (arg == NULL)
  10371. hasEmpty = true;
  10372. }
  10373. if (hasEmpty)
  10374. {
  10375. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  10376. {
  10377. auto arg = (*methodGenericArgs)[genericIdx];
  10378. if (arg != NULL)
  10379. newMethodGenericArgs.push_back(arg);
  10380. else
  10381. {
  10382. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  10383. if (genericParamInst->mTypeConstraint != NULL)
  10384. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  10385. else
  10386. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  10387. }
  10388. }
  10389. methodGenericArgs = &newMethodGenericArgs;
  10390. }
  10391. if (type->IsUnspecializedType())
  10392. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  10393. }
  10394. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  10395. {
  10396. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  10397. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  10398. methodName += TypeToString(type, typeNameFlags);
  10399. }
  10400. else
  10401. methodName += TypeToString(type, typeNameFlags);
  10402. }
  10403. methodName += ">";
  10404. }
  10405. if (accessorString.length() == 0)
  10406. {
  10407. int dispParamIdx = 0;
  10408. methodName += "(";
  10409. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  10410. {
  10411. int paramKind = methodInst->GetParamKind(paramIdx);
  10412. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  10413. continue;
  10414. if (dispParamIdx > 0)
  10415. methodName += ", ";
  10416. if (paramKind == BfParamKind_Params)
  10417. methodName += "params ";
  10418. BfType* type = methodInst->GetParamType(paramIdx);
  10419. _AddTypeName(type);
  10420. methodName += " ";
  10421. methodName += methodInst->GetParamName(paramIdx);
  10422. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  10423. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  10424. {
  10425. methodName += " = ";
  10426. methodName += paramInitializer->ToString();
  10427. }
  10428. dispParamIdx++;
  10429. }
  10430. methodName += ")";
  10431. }
  10432. if (accessorString.length() != 0)
  10433. {
  10434. methodName += " ";
  10435. methodName += accessorString;
  10436. }
  10437. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  10438. {
  10439. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  10440. methodName += " mut";
  10441. }
  10442. return methodName;
  10443. }
  10444. void BfModule::pt(BfType* type)
  10445. {
  10446. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  10447. }
  10448. void BfModule::pm(BfMethodInstance* type)
  10449. {
  10450. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  10451. }
  10452. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  10453. {
  10454. if ((flagsLeft & checkFlag) == 0)
  10455. return;
  10456. if (!str.empty())
  10457. {
  10458. if (flagsLeft == checkFlag)
  10459. {
  10460. if ((int)str.IndexOf(',') != -1)
  10461. str += ", and ";
  10462. else
  10463. str += " and ";
  10464. }
  10465. else
  10466. str += ", ";
  10467. }
  10468. str += addString;
  10469. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  10470. }
  10471. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  10472. {
  10473. String resultStr;
  10474. auto flagsLeft = attrTarget;
  10475. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  10476. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  10477. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  10478. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  10479. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  10480. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  10481. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  10482. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  10483. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  10484. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  10485. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  10486. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  10487. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  10488. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  10489. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  10490. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  10491. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  10492. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  10493. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  10494. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  10495. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  10496. if (resultStr.IsEmpty())
  10497. return "<nothing>";
  10498. return resultStr;
  10499. }
  10500. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  10501. {
  10502. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  10503. {
  10504. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  10505. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  10506. }
  10507. return irType;
  10508. }
  10509. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  10510. {
  10511. auto constant = mBfIRBuilder->GetConstant(irVal);
  10512. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  10513. if (stringPoolIdx != -1)
  10514. {
  10515. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  10516. return;
  10517. }
  10518. if (constant->mConstType == BfConstType_Agg)
  10519. {
  10520. auto constArray = (BfConstantAgg*)constant;
  10521. SizedArray<BfIRValue, 8> newVals;
  10522. for (auto val : constArray->mValues)
  10523. {
  10524. auto newVal = val;
  10525. CurrentAddToConstHolder(newVal);
  10526. newVals.push_back(newVal);
  10527. }
  10528. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  10529. return;
  10530. }
  10531. auto origConst = irVal;
  10532. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10533. {
  10534. auto bitcast = (BfConstantBitCast*)constant;
  10535. BfIRValue newVal;
  10536. if (constant->mConstType == BfConstType_BitCast)
  10537. {
  10538. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  10539. CurrentAddToConstHolder(newVal);
  10540. }
  10541. else
  10542. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  10543. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  10544. return;
  10545. }
  10546. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  10547. }
  10548. void BfModule::ClearConstData()
  10549. {
  10550. mBfIRBuilder->ClearConstData();
  10551. mStringObjectPool.Clear();
  10552. mStringCharPtrPool.Clear();
  10553. mStringPoolRefs.Clear();
  10554. mUnreifiedStringPoolRefs.Clear();
  10555. mStaticFieldRefs.Clear();
  10556. }
  10557. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  10558. {
  10559. switch (constant->mTypeCode)
  10560. {
  10561. case BfTypeCode_StringId:
  10562. case BfTypeCode_Boolean:
  10563. case BfTypeCode_Int8:
  10564. case BfTypeCode_UInt8:
  10565. case BfTypeCode_Int16:
  10566. case BfTypeCode_UInt16:
  10567. case BfTypeCode_Int32:
  10568. case BfTypeCode_UInt32:
  10569. case BfTypeCode_Int64:
  10570. case BfTypeCode_UInt64:
  10571. case BfTypeCode_IntPtr:
  10572. case BfTypeCode_UIntPtr:
  10573. case BfTypeCode_IntUnknown:
  10574. case BfTypeCode_UIntUnknown:
  10575. case BfTypeCode_Char8:
  10576. case BfTypeCode_Char16:
  10577. case BfTypeCode_Char32:
  10578. case BfTypeCode_Float:
  10579. case BfTypeCode_Double:
  10580. {
  10581. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10582. BfTypedValue typedValue;
  10583. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10584. if (constant->mTypeCode == BfTypeCode_StringId)
  10585. {
  10586. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10587. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10588. {
  10589. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10590. return typedValue;
  10591. }
  10592. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10593. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10594. }
  10595. if (!typedValue)
  10596. {
  10597. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10598. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10599. }
  10600. if (typedValue.mType == wantType)
  10601. return typedValue;
  10602. if (wantType->IsTypedPrimitive())
  10603. {
  10604. if (typedValue.mType == wantType->GetUnderlyingType())
  10605. {
  10606. typedValue.mType = wantType;
  10607. return typedValue;
  10608. }
  10609. }
  10610. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10611. if (!castedTypedValue)
  10612. return BfTypedValue();
  10613. return castedTypedValue;
  10614. }
  10615. break;
  10616. default: break;
  10617. }
  10618. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10619. BF_ASSERT(irValue);
  10620. if (!irValue)
  10621. return BfTypedValue();
  10622. if (constant->mConstType == BfConstType_GlobalVar)
  10623. {
  10624. mBfIRBuilder->PopulateType(wantType);
  10625. auto result = BfTypedValue(irValue, wantType, true);
  10626. if (!wantType->IsComposite())
  10627. result = LoadValue(result);
  10628. return result;
  10629. }
  10630. return BfTypedValue(irValue, wantType, false);
  10631. }
  10632. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10633. {
  10634. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10635. return true;
  10636. if (constant->mTypeCode == BfTypeCode_StringId)
  10637. return true;
  10638. if (constant->mTypeCode == BfTypeCode_CharPtr)
  10639. return true;
  10640. if (constant->mConstType == BfConstType_Agg)
  10641. {
  10642. auto constArray = (BfConstantAgg*)constant;
  10643. for (auto val : constArray->mValues)
  10644. {
  10645. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10646. return true;
  10647. }
  10648. }
  10649. if (constant->mConstType == BfConstType_PtrToInt)
  10650. {
  10651. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10652. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10653. return HasUnactializedConstant(fromTarget, constHolder);
  10654. }
  10655. if (constant->mConstType == BfConstType_BitCast)
  10656. {
  10657. auto bitcast = (BfConstantBitCast*)constant;
  10658. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10659. return HasUnactializedConstant(fromTarget, constHolder);
  10660. }
  10661. return false;
  10662. }
  10663. bool BfModule::HasGlobalVarReference(BfConstant* constant, BfIRConstHolder* constHolder)
  10664. {
  10665. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10666. return true;
  10667. if (constant->mTypeCode == BfTypeCode_StringId)
  10668. return true;
  10669. if (constant->mConstType == BfConstType_GlobalVar)
  10670. return true;
  10671. // NullPtr is stand-in for GlobalVar during autocomplete
  10672. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10673. return true;
  10674. if (constant->mConstType == BfConstType_Agg)
  10675. {
  10676. auto constArray = (BfConstantAgg*)constant;
  10677. for (auto val : constArray->mValues)
  10678. {
  10679. if (HasGlobalVarReference(constHolder->GetConstant(val), constHolder))
  10680. return true;
  10681. }
  10682. }
  10683. return false;
  10684. }
  10685. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10686. {
  10687. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10688. {
  10689. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10690. wantType = mContext->mTypes[constant->mIRType.mId];
  10691. if (wantType == NULL)
  10692. return mBfIRBuilder->CreateConstNull();
  10693. return GetDefaultValue(wantType);
  10694. }
  10695. if ((constant->mTypeCode == BfTypeCode_StringId) || (constant->mTypeCode == BfTypeCode_CharPtr))
  10696. {
  10697. if (!allowUnactualized)
  10698. {
  10699. if ((wantType == NULL) ||
  10700. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10701. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10702. {
  10703. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10704. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10705. bool wantCharPtr = ((wantType != NULL) && (wantType->IsPointer()));
  10706. if ((wantType == NULL) && (constant->mTypeCode == BfTypeCode_CharPtr))
  10707. wantCharPtr = true;
  10708. if (wantCharPtr)
  10709. return GetStringCharPtr(stringObjConst, true);
  10710. return stringObjConst;
  10711. }
  10712. }
  10713. }
  10714. if (constant->mTypeCode == BfTypeCode_CharPtr)
  10715. {
  10716. if (!allowUnactualized)
  10717. {
  10718. if ((wantType == NULL) ||
  10719. (wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10720. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10721. {
  10722. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10723. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10724. if ((wantType != NULL) && (wantType->IsPointer()))
  10725. return GetStringCharPtr(stringObjConst, true);
  10726. return stringObjConst;
  10727. }
  10728. }
  10729. }
  10730. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10731. {
  10732. auto constTypeOf = (BfTypeOf_Const*)constant;
  10733. if (mCurTypeInstance != NULL)
  10734. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10735. return CreateTypeDataRef(constTypeOf->mType, true);
  10736. }
  10737. if (constant->mConstType == BfConstType_PtrToInt)
  10738. {
  10739. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10740. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10741. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10742. }
  10743. if (constant->mConstType == BfConstType_IntToPtr)
  10744. {
  10745. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10746. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10747. BfIRType toIRType = fromPtrToInt->mToType;
  10748. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10749. {
  10750. auto toType = mContext->mTypes[toIRType.mId];
  10751. toIRType = mBfIRBuilder->MapType(toType);
  10752. }
  10753. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10754. }
  10755. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10756. {
  10757. auto bitcast = (BfConstantBitCast*)constant;
  10758. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10759. BfIRType toIRType = bitcast->mToType;
  10760. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10761. {
  10762. auto toType = mContext->mTypes[toIRType.mId];
  10763. toIRType = mBfIRBuilder->MapType(toType);
  10764. }
  10765. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10766. }
  10767. if (constant->mConstType == BfConstType_Agg)
  10768. {
  10769. auto constArray = (BfConstantAgg*)constant;
  10770. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10771. wantType = mContext->mTypes[constArray->mType.mId];
  10772. if (wantType->IsArray())
  10773. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10774. bool handleAsArray = false;
  10775. SizedArray<BfIRValue, 8> newVals;
  10776. if (wantType->IsSizedArray())
  10777. {
  10778. handleAsArray = true;
  10779. }
  10780. else if (wantType->IsInstanceOf(mCompiler->mSpanTypeDef))
  10781. {
  10782. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  10783. handleAsArray = true;
  10784. if (!constArray->mValues.IsEmpty())
  10785. {
  10786. auto firstConstant = constHolder->GetConstant(constArray->mValues[0]);
  10787. if ((firstConstant->mConstType == BfConstType_AggZero) && (firstConstant->mIRType.mKind == BfIRType::TypeKind_TypeId) &&
  10788. (firstConstant->mIRType.mId == valueType->mTypeId))
  10789. handleAsArray = false;
  10790. if (firstConstant->mConstType == BfConstType_Agg)
  10791. {
  10792. auto firstConstArray = (BfConstantAgg*)firstConstant;
  10793. if ((firstConstArray->mType.mKind == BfIRType::TypeKind_TypeId) &&
  10794. (firstConstArray->mType.mId == valueType->mTypeId))
  10795. handleAsArray = false;
  10796. }
  10797. }
  10798. }
  10799. if (handleAsArray)
  10800. {
  10801. auto elementType = wantType->GetUnderlyingType();
  10802. for (auto val : constArray->mValues)
  10803. {
  10804. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10805. }
  10806. }
  10807. else
  10808. {
  10809. auto wantTypeInst = wantType->ToTypeInstance();
  10810. if (wantTypeInst == NULL)
  10811. {
  10812. InternalError("BfModule::ConstantToCurrent typeInst error");
  10813. return BfIRValue();
  10814. }
  10815. if (wantTypeInst->mBaseType != NULL)
  10816. {
  10817. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10818. newVals.Add(baseVal);
  10819. }
  10820. if (wantType->IsUnion())
  10821. {
  10822. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10823. if (!innerType->IsValuelessType())
  10824. {
  10825. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10826. newVals.Add(val);
  10827. }
  10828. }
  10829. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10830. {
  10831. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10832. {
  10833. if (fieldInstance.mDataIdx < 0)
  10834. continue;
  10835. if (fieldInstance.mDataIdx >= constArray->mValues.mSize)
  10836. {
  10837. InternalError("BfModule::ConstantToCurrent union error");
  10838. return BfIRValue();
  10839. }
  10840. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10841. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10842. if (fieldInstance.mDataIdx == newVals.mSize)
  10843. newVals.Add(memberVal);
  10844. else
  10845. {
  10846. while (fieldInstance.mDataIdx >= newVals.mSize)
  10847. newVals.Add(BfIRValue());
  10848. newVals[fieldInstance.mDataIdx] = memberVal;
  10849. }
  10850. }
  10851. }
  10852. for (auto& val : newVals)
  10853. {
  10854. if (!val)
  10855. val = mBfIRBuilder->CreateConstArrayZero(0);
  10856. }
  10857. }
  10858. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10859. }
  10860. return mBfIRBuilder->CreateConst(constant, constHolder);
  10861. }
  10862. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget, bool force)
  10863. {
  10864. if (attrTarget == BfAttributeTargets_SkipValidate)
  10865. return;
  10866. for (auto& customAttribute : customAttributes->mAttributes)
  10867. {
  10868. if (!customAttribute.mAwaitingValidation)
  10869. continue;
  10870. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10871. {
  10872. if ((customAttribute.mIsMultiUse) && (!force))
  10873. continue;
  10874. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10875. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10876. }
  10877. customAttribute.mAwaitingValidation = false;
  10878. }
  10879. }
  10880. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10881. {
  10882. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10883. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10884. if (!mCompiler->mHasRequiredTypes)
  10885. return;
  10886. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10887. {
  10888. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10889. sourceClassifier->VisitChild(attributesDirective);
  10890. }
  10891. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10892. if (mCompiler->IsAutocomplete())
  10893. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10894. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10895. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10896. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10897. BfAutoComplete* autoComplete = NULL;
  10898. if (mCompiler->mResolvePassData != NULL)
  10899. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10900. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10901. {
  10902. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10903. {
  10904. if (captureInfo == NULL)
  10905. {
  10906. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10907. continue;
  10908. }
  10909. BfCaptureInfo::Entry captureEntry;
  10910. captureEntry.mRefNode = tokenNode;
  10911. captureEntry.mCaptureType = BfCaptureType_Copy;
  10912. if (tokenNode->mToken == BfToken_Ampersand)
  10913. captureEntry.mCaptureType = BfCaptureType_Reference;
  10914. if (tokenNode->mToken == BfToken_Question)
  10915. captureEntry.mCaptureType = BfCaptureType_Auto;
  10916. if (!attributesDirective->mArguments.IsEmpty())
  10917. {
  10918. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]))
  10919. captureEntry.mNameNode = identifierNode;
  10920. else if (auto thisExpr = BfNodeDynCast<BfThisExpression>(attributesDirective->mArguments[0]))
  10921. {
  10922. captureEntry.mNameNode = thisExpr;
  10923. }
  10924. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10925. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10926. }
  10927. captureInfo->mCaptures.Add(captureEntry);
  10928. continue;
  10929. }
  10930. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10931. BfCustomAttribute customAttribute;
  10932. customAttribute.mAwaitingValidation = true;
  10933. customAttribute.mDeclaringType = activeTypeDef;
  10934. customAttribute.mRef = attributesDirective;
  10935. customAttribute.mIsMultiUse = attributesDirective->mIsMultiUse;
  10936. if (attributesDirective->mAttrOpenToken != NULL)
  10937. targetOverride = (BfAttributeTargets)0;
  10938. if (attributesDirective->mAttributeTypeRef == NULL)
  10939. {
  10940. AssertErrorState();
  10941. continue;
  10942. }
  10943. BfType* attrType;
  10944. if (mContext->mCurTypeState != NULL)
  10945. {
  10946. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10947. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10948. }
  10949. else
  10950. {
  10951. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10952. }
  10953. BfTypeDef* attrTypeDef = NULL;
  10954. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10955. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10956. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10957. {
  10958. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10959. if (attrTypeDef != NULL)
  10960. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10961. }
  10962. bool isBypassedAttr = false;
  10963. if (attrTypeDef != NULL)
  10964. {
  10965. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10966. // We solve it by having a 'bypass' for known attributes that Object depends on
  10967. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10968. {
  10969. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10970. {
  10971. for (auto methodDef : attrTypeDef->mMethods)
  10972. {
  10973. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10974. {
  10975. customAttribute.mType = attrType->ToTypeInstance();
  10976. customAttribute.mCtor = methodDef;
  10977. isBypassedAttr = true;
  10978. break;
  10979. }
  10980. }
  10981. }
  10982. }
  10983. if (isBypassedAttr)
  10984. {
  10985. customAttribute.mAwaitingValidation = false;
  10986. customAttributes->mAttributes.push_back(customAttribute);
  10987. continue;
  10988. }
  10989. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10990. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10991. if (mContext->mCurTypeState != NULL)
  10992. {
  10993. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10994. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10995. }
  10996. else
  10997. {
  10998. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10999. }
  11000. }
  11001. BfTypeInstance* attrTypeInst = NULL;
  11002. if (attrType == NULL)
  11003. continue;
  11004. attrTypeInst = attrType->ToTypeInstance();
  11005. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  11006. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  11007. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  11008. {
  11009. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  11010. continue;
  11011. }
  11012. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  11013. {
  11014. // Reify attribute
  11015. PopulateType(attrTypeInst);
  11016. }
  11017. if (mCurTypeInstance != NULL)
  11018. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11019. customAttribute.mType = attrTypeInst;
  11020. bool allocatedMethodState = NULL;
  11021. defer(
  11022. {
  11023. if (allocatedMethodState)
  11024. {
  11025. delete mCurMethodState;
  11026. mCurMethodState = NULL;
  11027. }
  11028. });
  11029. if (mCurMethodState == NULL)
  11030. {
  11031. allocatedMethodState = true;
  11032. mCurMethodState = new BfMethodState();
  11033. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  11034. }
  11035. BfConstResolver constResolver(this);
  11036. if (allowNonConstArgs)
  11037. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  11038. bool inPropSet = false;
  11039. SizedArray<BfResolvedArg, 2> argValues;
  11040. for (BfExpression* arg : attributesDirective->mArguments)
  11041. {
  11042. if (arg == NULL)
  11043. {
  11044. continue;
  11045. }
  11046. if (autoComplete != NULL)
  11047. autoComplete->mShowAttributeProperties = attrTypeInst;
  11048. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  11049. {
  11050. inPropSet = true;
  11051. if (autoComplete != NULL)
  11052. autoComplete->CheckNode(assignExpr->mLeft, true);
  11053. String findName = assignExpr->mLeft->ToString();
  11054. BfPropertyDef* bestProp = NULL;
  11055. BfTypeInstance* bestPropTypeInst = NULL;
  11056. BfFieldDef* bestField = NULL;
  11057. BfTypeInstance* bestFieldTypeInst = NULL;
  11058. auto checkTypeInst = attrTypeInst;
  11059. while (checkTypeInst != NULL)
  11060. {
  11061. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  11062. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  11063. {
  11064. if (prop->mName == findName)
  11065. {
  11066. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  11067. {
  11068. bestProp = prop;
  11069. bestPropTypeInst = checkTypeInst;
  11070. }
  11071. }
  11072. }
  11073. for (auto field : checkTypeInst->mTypeDef->mFields)
  11074. {
  11075. if (field->mName == findName)
  11076. {
  11077. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  11078. {
  11079. bestField = field;
  11080. bestFieldTypeInst = checkTypeInst;
  11081. }
  11082. }
  11083. }
  11084. if ((bestProp != NULL) || (bestField != NULL))
  11085. break;
  11086. checkTypeInst = checkTypeInst->mBaseType;
  11087. }
  11088. bool handledExpr = false;
  11089. if (bestField != NULL)
  11090. {
  11091. handledExpr = true;
  11092. if (mCompiler->mResolvePassData != NULL)
  11093. {
  11094. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  11095. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11096. {
  11097. autoComplete->mDefField = bestField;
  11098. autoComplete->mDefType = attrTypeDef;
  11099. }
  11100. }
  11101. if (bestField->mProtection != BfProtection_Public)
  11102. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11103. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11104. BfCustomAttributeSetField setField;
  11105. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  11106. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  11107. if (assignExpr->mRight != NULL)
  11108. {
  11109. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  11110. if (result)
  11111. {
  11112. if (!keepConstsInModule)
  11113. CurrentAddToConstHolder(result.mValue);
  11114. setField.mParam = result;
  11115. customAttribute.mSetField.push_back(setField);
  11116. }
  11117. }
  11118. }
  11119. else if (bestProp == NULL)
  11120. {
  11121. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  11122. }
  11123. else
  11124. {
  11125. BfMethodDef* setMethod = NULL;
  11126. for (auto methodDef : bestProp->mMethods)
  11127. {
  11128. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  11129. {
  11130. setMethod = methodDef;
  11131. break;
  11132. }
  11133. }
  11134. if (setMethod == NULL)
  11135. {
  11136. Fail("Property has no setter", assignExpr->mLeft);
  11137. }
  11138. else
  11139. {
  11140. if (mCompiler->mResolvePassData != NULL)
  11141. {
  11142. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  11143. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  11144. {
  11145. autoComplete->mDefProp = bestProp;
  11146. autoComplete->mDefType = attrTypeDef;
  11147. }
  11148. }
  11149. handledExpr = true;
  11150. if (bestProp->mProtection != BfProtection_Public)
  11151. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  11152. BfResolvedArg resolvedArg;
  11153. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11154. BfCustomAttributeSetProperty setProperty;
  11155. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  11156. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  11157. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  11158. if (methodInstance.mMethodInstance != NULL)
  11159. {
  11160. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  11161. if (assignExpr->mRight != NULL)
  11162. {
  11163. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  11164. if ((result) && (!result.mType->IsVar()))
  11165. {
  11166. if (!result.mValue.IsConst())
  11167. result = GetDefaultTypedValue(result.mType);
  11168. BF_ASSERT(result.mType == propType);
  11169. if (!keepConstsInModule)
  11170. CurrentAddToConstHolder(result.mValue);
  11171. setProperty.mParam = result;
  11172. customAttribute.mSetProperties.push_back(setProperty);
  11173. }
  11174. }
  11175. }
  11176. }
  11177. }
  11178. if ((!handledExpr) && (assignExpr->mRight != NULL))
  11179. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  11180. }
  11181. else
  11182. {
  11183. if (inPropSet)
  11184. {
  11185. Fail("Named attribute argument expected", arg); // CS1016
  11186. }
  11187. BfDeferEvalChecker deferEvalChecker;
  11188. arg->Accept(&deferEvalChecker);
  11189. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  11190. BfResolvedArg resolvedArg;
  11191. resolvedArg.mExpression = arg;
  11192. if (deferParamEval)
  11193. {
  11194. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  11195. }
  11196. else
  11197. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  11198. if (!inPropSet)
  11199. {
  11200. argValues.push_back(resolvedArg);
  11201. }
  11202. }
  11203. if (autoComplete != NULL)
  11204. autoComplete->mShowAttributeProperties = NULL;
  11205. }
  11206. auto wasCapturingMethodInfo = false;
  11207. if (autoComplete != NULL)
  11208. {
  11209. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  11210. if (attributesDirective->mCtorOpenParen != NULL)
  11211. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  11212. }
  11213. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  11214. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  11215. attrTypeDef = attrTypeInst->mTypeDef;
  11216. bool success = true;
  11217. int methodCheckCount = 0;
  11218. bool isFailurePass = false;
  11219. for (int pass = 0; pass < 2; pass++)
  11220. {
  11221. bool isFailurePass = pass == 1;
  11222. for (auto checkMethod : attrTypeDef->mMethods)
  11223. {
  11224. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  11225. continue; // Don't match private default ctor if there's a user-defined one
  11226. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  11227. continue;
  11228. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  11229. continue;
  11230. methodCheckCount++;
  11231. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  11232. }
  11233. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  11234. break;
  11235. }
  11236. if (autoComplete != NULL)
  11237. {
  11238. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11239. {
  11240. autoComplete->mIsCapturingMethodMatchInfo = true;
  11241. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11242. }
  11243. else
  11244. autoComplete->mIsCapturingMethodMatchInfo = false;
  11245. }
  11246. if (methodMatcher.mBestMethodDef == NULL)
  11247. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  11248. if (methodMatcher.mBestMethodDef == NULL)
  11249. {
  11250. if (methodCheckCount == 0)
  11251. Fail(StrFormat("No attribute constructors found for type '%s'", TypeToString(attrTypeInst).c_str()), attributesDirective);
  11252. AssertErrorState();
  11253. continue;
  11254. }
  11255. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  11256. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  11257. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  11258. {
  11259. Fail("Custom attribute circular reference", attributesDirective);
  11260. }
  11261. if (mCurTypeInstance != NULL)
  11262. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  11263. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  11264. success = false;
  11265. for (auto& arg : argValues)
  11266. {
  11267. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  11268. {
  11269. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  11270. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  11271. }
  11272. }
  11273. // Move all those to the constHolder
  11274. if (!keepConstsInModule)
  11275. {
  11276. for (auto& ctorArg : customAttribute.mCtorArgs)
  11277. {
  11278. if (ctorArg.IsConst())
  11279. CurrentAddToConstHolder(ctorArg);
  11280. }
  11281. }
  11282. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  11283. {
  11284. targetOverride = BfAttributeTargets_ReturnValue;
  11285. if (attrTarget != BfAttributeTargets_Method)
  11286. {
  11287. 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.",
  11288. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  11289. success = false;
  11290. }
  11291. }
  11292. if ((success) && (targetOverride != (BfAttributeTargets)0))
  11293. {
  11294. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  11295. {
  11296. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  11297. if (methodInfoEx->mMethodCustomAttributes == NULL)
  11298. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  11299. if (success)
  11300. {
  11301. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  11302. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  11303. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  11304. }
  11305. }
  11306. // Mark as failed since we don't actually want to add this to the custom attributes set
  11307. success = false;
  11308. }
  11309. if (success)
  11310. {
  11311. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  11312. {
  11313. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  11314. {
  11315. if (prevCustomAttribute.mType == attrTypeInst)
  11316. {
  11317. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  11318. }
  11319. }
  11320. }
  11321. }
  11322. if (success)
  11323. {
  11324. customAttributes->mAttributes.push_back(customAttribute);
  11325. }
  11326. }
  11327. ValidateCustomAttributes(customAttributes, attrTarget);
  11328. }
  11329. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  11330. {
  11331. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  11332. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  11333. return customAttributes;
  11334. }
  11335. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  11336. {
  11337. BF_ASSERT(mCompiler->IsAutocomplete());
  11338. BfAttributeTargets attrTarget;
  11339. if (typeDef->mIsDelegate)
  11340. attrTarget = BfAttributeTargets_Delegate;
  11341. else if (typeDef->mIsFunction)
  11342. attrTarget = BfAttributeTargets_Function;
  11343. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  11344. attrTarget = BfAttributeTargets_Enum;
  11345. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  11346. attrTarget = BfAttributeTargets_Interface;
  11347. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  11348. attrTarget = BfAttributeTargets_Struct;
  11349. else if (typeDef->mTypeCode == BfTypeCode_Extension)
  11350. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Struct | BfAttributeTargets_Class | BfAttributeTargets_Interface | BfAttributeTargets_Enum);
  11351. else
  11352. attrTarget = BfAttributeTargets_Class;
  11353. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  11354. }
  11355. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  11356. {
  11357. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  11358. Warn(0, "Unused attributes", attributeState->mSrc);
  11359. }
  11360. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  11361. {
  11362. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  11363. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11364. if (mCurTypeInstance->mCustomAttributes != NULL)
  11365. {
  11366. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11367. {
  11368. String typeName = TypeToString(customAttribute.mType);
  11369. if (typeName == "System.PackedAttribute")
  11370. {
  11371. packing = 1;
  11372. if (customAttribute.mCtorArgs.size() >= 1)
  11373. {
  11374. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11375. int checkPacking = alignConstant->mInt32;
  11376. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  11377. packing = checkPacking;
  11378. else
  11379. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  11380. }
  11381. }
  11382. else if (typeName == "System.UnionAttribute")
  11383. {
  11384. isUnion = true;
  11385. }
  11386. else if (typeName == "System.CReprAttribute")
  11387. {
  11388. isCRepr = true;
  11389. isOrdered = true;
  11390. }
  11391. else if (typeName == "System.OrderedAttribute")
  11392. {
  11393. isOrdered = true;
  11394. }
  11395. else if (typeName == "System.AlwaysIncludeAttribute")
  11396. {
  11397. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  11398. for (auto setProp : customAttribute.mSetProperties)
  11399. {
  11400. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  11401. if (propertyDef->mName == "AssumeInstantiated")
  11402. {
  11403. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11404. if ((constant != NULL) && (constant->mBool))
  11405. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  11406. }
  11407. else if (propertyDef->mName == "IncludeAllMethods")
  11408. {
  11409. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11410. if ((constant != NULL) && (constant->mBool))
  11411. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  11412. }
  11413. }
  11414. }
  11415. else if (typeName == "System.AlignAttribute")
  11416. {
  11417. if (customAttribute.mCtorArgs.size() >= 1)
  11418. {
  11419. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11420. int checkAlign = alignConstant->mInt32;
  11421. if ((checkAlign & (checkAlign - 1)) == 0)
  11422. alignOverride = checkAlign;
  11423. else
  11424. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  11425. }
  11426. }
  11427. else if (typeName == "System.UnderlyingArrayAttribute")
  11428. {
  11429. if (customAttribute.mCtorArgs.size() >= 2)
  11430. {
  11431. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11432. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  11433. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  11434. {
  11435. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  11436. underlyingArraySize = sizeConstant->mInt32;
  11437. }
  11438. }
  11439. }
  11440. if (customAttribute.mType->mAttributeData == NULL)
  11441. PopulateType(customAttribute.mType);
  11442. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  11443. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  11444. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  11445. }
  11446. }
  11447. }
  11448. // Checking to see if we're an attribute or not
  11449. void BfModule::ProcessCustomAttributeData()
  11450. {
  11451. if (mCurTypeInstance->mAttributeData != NULL)
  11452. return;
  11453. bool isAttribute = false;
  11454. auto checkTypeInst = mCurTypeInstance->mBaseType;
  11455. while (checkTypeInst != NULL)
  11456. {
  11457. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  11458. isAttribute = true;
  11459. checkTypeInst = checkTypeInst->mBaseType;
  11460. }
  11461. if (!isAttribute)
  11462. return;
  11463. auto attributeData = new BfAttributeData();
  11464. bool hasCustomAttribute = false;
  11465. if (mCurTypeInstance->mCustomAttributes != NULL)
  11466. {
  11467. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  11468. {
  11469. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  11470. {
  11471. if (customAttribute.mCtorArgs.size() > 0)
  11472. {
  11473. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11474. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11475. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11476. }
  11477. if (customAttribute.mCtorArgs.size() == 2)
  11478. {
  11479. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  11480. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11481. {
  11482. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  11483. }
  11484. }
  11485. for (auto& setProp : customAttribute.mSetProperties)
  11486. {
  11487. BfPropertyDef* propDef = setProp.mPropertyRef;
  11488. if (propDef->mName == "AllowMultiple")
  11489. {
  11490. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11491. if ((constant != NULL) && (constant->mBool))
  11492. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  11493. else
  11494. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  11495. }
  11496. else if (propDef->mName == "Inherited")
  11497. {
  11498. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11499. if ((constant != NULL) && (constant->mBool))
  11500. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  11501. else
  11502. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  11503. }
  11504. else if (propDef->mName == "ValidOn")
  11505. {
  11506. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11507. if (constant != NULL)
  11508. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  11509. }
  11510. else if (propDef->mName == "AlwaysIncludeUser")
  11511. {
  11512. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  11513. if (constant != NULL)
  11514. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  11515. }
  11516. }
  11517. hasCustomAttribute = true;
  11518. }
  11519. }
  11520. }
  11521. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  11522. {
  11523. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  11524. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  11525. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  11526. }
  11527. mCurTypeInstance->mAttributeData = attributeData;
  11528. }
  11529. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  11530. {
  11531. auto constant = constHolder->GetConstant(irValue);
  11532. if (constant == NULL)
  11533. return false;
  11534. if (constant->mTypeCode != BfTypeCode_StringId)
  11535. return false;
  11536. int stringId = constant->mInt32;
  11537. BfStringPoolEntry* entry = NULL;
  11538. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  11539. {
  11540. str += entry->mString;
  11541. }
  11542. else
  11543. {
  11544. BF_DBG_FATAL("Failed to find string by id");
  11545. }
  11546. return true;
  11547. }
  11548. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  11549. {
  11550. BfVariant variant;
  11551. variant.mTypeCode = BfTypeCode_None;
  11552. BfType* primType = NULL;
  11553. if (value.mType->IsPrimitiveType())
  11554. primType = (BfPrimitiveType*)value.mType;
  11555. else if (value.mType->IsTypedPrimitive())
  11556. primType = value.mType->GetUnderlyingType();
  11557. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  11558. primType = value.mType;
  11559. if (primType)
  11560. {
  11561. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  11562. if (constant != NULL)
  11563. {
  11564. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  11565. {
  11566. variant.mUInt64 = 0;
  11567. variant.mTypeCode = BfTypeCode_Let;
  11568. return variant;
  11569. }
  11570. if (constant->mConstType == BfConstType_GlobalVar)
  11571. {
  11572. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  11573. if (stringIdx != -1)
  11574. {
  11575. variant.mTypeCode = BfTypeCode_StringId;
  11576. variant.mInt64 = stringIdx;
  11577. return variant;
  11578. }
  11579. }
  11580. switch (constant->mTypeCode)
  11581. {
  11582. case BfTypeCode_Boolean:
  11583. case BfTypeCode_Int8:
  11584. case BfTypeCode_UInt8:
  11585. case BfTypeCode_Int16:
  11586. case BfTypeCode_UInt16:
  11587. case BfTypeCode_Int32:
  11588. case BfTypeCode_UInt32:
  11589. case BfTypeCode_Int64:
  11590. case BfTypeCode_UInt64:
  11591. case BfTypeCode_IntPtr:
  11592. case BfTypeCode_UIntPtr:
  11593. case BfTypeCode_IntUnknown:
  11594. case BfTypeCode_UIntUnknown:
  11595. case BfTypeCode_Double:
  11596. case BfTypeCode_Char8:
  11597. case BfTypeCode_Char16:
  11598. case BfTypeCode_Char32:
  11599. case BfTypeCode_StringId:
  11600. variant.mTypeCode = constant->mTypeCode;
  11601. if (((variant.mTypeCode == BfTypeCode_Int64) || (variant.mTypeCode == BfTypeCode_UInt64)) &&
  11602. (primType->mSize > 0) && (primType->mSize < 8) &&
  11603. (mBfIRBuilder->IsIntable(primType->GetTypeCode())))
  11604. {
  11605. // We may have an 'int unknown' that we need to downsize
  11606. variant.mTypeCode = primType->GetTypeCode();
  11607. }
  11608. variant.mInt64 = constant->mInt64;
  11609. break;
  11610. case BfTypeCode_Float:
  11611. variant.mTypeCode = constant->mTypeCode;
  11612. variant.mSingle = (float)constant->mDouble;
  11613. break;
  11614. default:
  11615. if (refNode != NULL)
  11616. Fail("Invalid const expression type", refNode);
  11617. break;
  11618. }
  11619. }
  11620. }
  11621. else if (value.mType->IsConstExprValue())
  11622. {
  11623. auto constExprType = (BfConstExprValueType*)value.mType;
  11624. return constExprType->mValue;
  11625. }
  11626. else if (value.mType->IsValueType())
  11627. {
  11628. PopulateType(value.mType);
  11629. int allocSize = value.mType->mSize + 4;
  11630. BfVariant::StructData* structData = (BfVariant::StructData*)(new uint8[allocSize]);
  11631. memset(structData, 0, allocSize);
  11632. structData->mSize = value.mType->mSize;
  11633. mBfIRBuilder->WriteConstant(value.mValue, structData->mData, value.mType);
  11634. variant.mTypeCode = BfTypeCode_Struct;
  11635. variant.mPtr = structData;
  11636. }
  11637. return variant;
  11638. }
  11639. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue, bool makeInReadOnly)
  11640. {
  11641. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  11642. {
  11643. auto refType = (BfRefType*)typedValue.mType;
  11644. auto elementType = typedValue.mType->GetUnderlyingType();
  11645. if (typedValue.IsAddr())
  11646. {
  11647. if (elementType->IsValuelessType())
  11648. {
  11649. BF_ASSERT(!typedValue.mValue);
  11650. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11651. }
  11652. else
  11653. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  11654. }
  11655. else
  11656. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  11657. if (typedValue.mType->IsValuelessType())
  11658. {
  11659. BF_ASSERT(typedValue.mValue.IsFake());
  11660. }
  11661. if ((refType->mRefKind == BfRefType::RefKind_In) && (makeInReadOnly))
  11662. {
  11663. if (typedValue.mKind == BfTypedValueKind_Addr)
  11664. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  11665. }
  11666. }
  11667. return typedValue;
  11668. }
  11669. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  11670. {
  11671. if (!typedValue)
  11672. return typedValue;
  11673. if (typedValue.mType->IsRef())
  11674. {
  11675. typedValue = LoadValue(typedValue);
  11676. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  11677. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  11678. return copiedVal;
  11679. }
  11680. return typedValue;
  11681. }
  11682. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  11683. {
  11684. if (refType == NULL)
  11685. refType = CreateRefType(typedValue.mType);
  11686. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  11687. {
  11688. return LoadValue(typedValue);
  11689. }
  11690. if (refType->mRefKind == BfRefType::RefKind_Mut)
  11691. refType = CreateRefType(typedValue.mType);
  11692. if (!typedValue.mType->IsValuelessNonOpaqueType())
  11693. typedValue = MakeAddressable(typedValue, false, true);
  11694. return BfTypedValue(typedValue.mValue, refType);
  11695. }
  11696. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  11697. {
  11698. if (!typedValue.IsAddr())
  11699. return typedValue;
  11700. PopulateType(typedValue.mType);
  11701. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  11702. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  11703. if (typedValue.mValue.IsConst())
  11704. {
  11705. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  11706. if (constantValue != NULL)
  11707. {
  11708. if (constantValue->mConstType == BfConstType_GlobalVar)
  11709. {
  11710. auto globalVar = (BfGlobalVar*)constantValue;
  11711. if (globalVar->mName[0] == '#')
  11712. {
  11713. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11714. if (result)
  11715. {
  11716. // We want to avoid 'unreachable code' issues from values that
  11717. // are technically constant but change depending on compilation context
  11718. if (mCurMethodState != NULL)
  11719. {
  11720. auto checkScope = mCurMethodState->mCurScope;
  11721. while (checkScope != NULL)
  11722. {
  11723. checkScope->mSupressNextUnreachable = true;
  11724. checkScope = checkScope->mPrevScope;
  11725. }
  11726. }
  11727. return result;
  11728. }
  11729. if (!mIsComptimeModule)
  11730. return GetDefaultTypedValue(typedValue.mType);
  11731. }
  11732. }
  11733. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11734. {
  11735. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11736. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11737. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11738. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11739. if (ceTypedValue)
  11740. {
  11741. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11742. {
  11743. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11744. if (data == NULL)
  11745. {
  11746. Fail("Invalid address", refNode);
  11747. return GetDefaultTypedValue(typedValue.mType);
  11748. }
  11749. uint64 dataAddr;
  11750. if (mSystem->mPtrSize == 4)
  11751. dataAddr = *(uint32*)data;
  11752. else
  11753. dataAddr = *(uint64*)data;
  11754. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11755. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11756. }
  11757. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11758. if (!constVal)
  11759. {
  11760. Fail("Failed to create const", refNode);
  11761. return GetDefaultTypedValue(typedValue.mType);
  11762. }
  11763. return BfTypedValue(constVal, typedValue.mType);
  11764. }
  11765. }
  11766. }
  11767. }
  11768. BfIRValue loadedVal = typedValue.mValue;
  11769. if (loadedVal)
  11770. {
  11771. if (typedValue.mType->IsVar())
  11772. {
  11773. return BfTypedValue(loadedVal, typedValue.mType, false);
  11774. }
  11775. PopulateType(typedValue.mType, BfPopulateType_Data);
  11776. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11777. }
  11778. return BfTypedValue(loadedVal, typedValue.mType, false);
  11779. }
  11780. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11781. {
  11782. if (!typedValue.mValue.IsConst())
  11783. return typedValue;
  11784. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11785. if (constant->mTypeCode == BfTypeCode_StringId)
  11786. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11787. return typedValue;
  11788. }
  11789. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11790. {
  11791. if (typedValue.IsSplat())
  11792. return AggregateSplat(typedValue);
  11793. if (typedValue.IsAddr())
  11794. return LoadValue(typedValue);
  11795. if ((typedValue.mType != NULL) && (typedValue.mType->IsParamsType()) && (!typedValue.IsParams()))
  11796. {
  11797. return GetDefaultTypedValue(ResolveTypeDef(mCompiler->mTupleTypeDef));
  11798. }
  11799. else if ((typedValue.IsParams()) && (typedValue.mType->IsGenericParam()))
  11800. {
  11801. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType);
  11802. }
  11803. return typedValue;
  11804. }
  11805. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11806. {
  11807. if (!typedValue.IsSplat())
  11808. return typedValue;
  11809. BF_ASSERT(!mIsComptimeModule);
  11810. if (typedValue.mType->IsValuelessType())
  11811. return typedValue;
  11812. int elementIdx = 0;
  11813. auto _ExtractValue = [&](BfType* checkType)
  11814. {
  11815. if (valueArrPtr != NULL)
  11816. return valueArrPtr[elementIdx++];
  11817. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11818. };
  11819. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11820. {
  11821. if (checkType->IsStruct())
  11822. {
  11823. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11824. auto checkTypeInstance = checkType->ToTypeInstance();
  11825. if (checkTypeInstance->mBaseType != NULL)
  11826. {
  11827. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11828. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11829. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11830. }
  11831. if (checkTypeInstance->mIsUnion)
  11832. {
  11833. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11834. if (!unionInnerType->IsValuelessType())
  11835. {
  11836. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11837. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11838. }
  11839. if (checkTypeInstance->IsEnum())
  11840. {
  11841. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11842. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11843. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11844. }
  11845. }
  11846. else
  11847. {
  11848. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11849. {
  11850. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11851. if (fieldInstance->mDataIdx >= 0)
  11852. {
  11853. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11854. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11855. }
  11856. }
  11857. }
  11858. return curValue;
  11859. }
  11860. else if (checkType->IsMethodRef())
  11861. {
  11862. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11863. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11864. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11865. {
  11866. BfIRValue fieldValue;
  11867. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11868. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11869. {
  11870. fieldValue = checkTypeLambda(checkType);
  11871. }
  11872. else
  11873. {
  11874. fieldValue = _ExtractValue(checkType);
  11875. }
  11876. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11877. }
  11878. return curValue;
  11879. }
  11880. else if (!checkType->IsValuelessType())
  11881. {
  11882. return _ExtractValue(checkType);
  11883. }
  11884. return BfIRValue();
  11885. };
  11886. BfIRValue value = checkTypeLambda(typedValue.mType);
  11887. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11888. }
  11889. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11890. {
  11891. if (!typedValue.IsSplat())
  11892. return;
  11893. if (typedValue.mType->IsValuelessType())
  11894. return;
  11895. BF_ASSERT(!mIsComptimeModule);
  11896. /*static int sCallIdx = 0;
  11897. if (!mCompiler->mIsResolveOnly)
  11898. sCallIdx++;
  11899. int callIdx = sCallIdx;*/
  11900. int elementIdx = 0;
  11901. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11902. {
  11903. if (checkType->IsStruct())
  11904. {
  11905. auto checkTypeInstance = checkType->ToTypeInstance();
  11906. if (checkTypeInstance->mBaseType != NULL)
  11907. {
  11908. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11909. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11910. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11911. }
  11912. if (checkTypeInstance->mIsUnion)
  11913. {
  11914. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11915. if (!unionInnerType->IsValuelessType())
  11916. {
  11917. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11918. checkTypeLambda(unionInnerType, fieldAddrVal);
  11919. }
  11920. if (checkTypeInstance->IsEnum())
  11921. {
  11922. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11923. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11924. checkTypeLambda(dscrType, fieldAddrVal);
  11925. }
  11926. }
  11927. else
  11928. {
  11929. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11930. {
  11931. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11932. if (fieldInstance->mDataIdx >= 0)
  11933. {
  11934. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11935. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11936. }
  11937. }
  11938. }
  11939. }
  11940. else if (checkType->IsMethodRef())
  11941. {
  11942. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11943. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11944. {
  11945. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11946. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11947. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11948. {
  11949. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11950. }
  11951. else
  11952. {
  11953. // static int sItrCount = 0;
  11954. // sItrCount++;
  11955. // int curItr = sItrCount;
  11956. // if (curItr == 1)
  11957. // {
  11958. // NOP;
  11959. // }
  11960. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11961. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11962. }
  11963. }
  11964. }
  11965. else if (!checkType->IsValuelessType())
  11966. {
  11967. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11968. mBfIRBuilder->CreateStore(val, curAddrVal);
  11969. }
  11970. };
  11971. checkTypeLambda(typedValue.mType, addrVal);
  11972. }
  11973. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11974. {
  11975. if (!typedVal)
  11976. return typedVal;
  11977. bool wasReadOnly = typedVal.IsReadOnly();
  11978. if ((forceAddressable) ||
  11979. ((typedVal.mType->IsValueType()) &&
  11980. (!typedVal.mType->IsValuelessNonOpaqueType())))
  11981. {
  11982. wasReadOnly = true; // Any non-addr is implicitly read-only
  11983. //static int gCallIdx = 0;
  11984. FixValueActualization(typedVal);
  11985. if (typedVal.IsAddr())
  11986. return typedVal;
  11987. BfType* type = typedVal.mType;
  11988. PopulateType(type);
  11989. BfIRValue tempVar;
  11990. if (typedVal.mValue.IsFake())
  11991. tempVar = mBfIRBuilder->GetFakeVal();
  11992. else
  11993. {
  11994. tempVar = CreateAlloca(type);
  11995. if (typedVal.IsSplat())
  11996. AggregateSplatIntoAddr(typedVal, tempVar);
  11997. else
  11998. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11999. }
  12000. if (forceMutable)
  12001. wasReadOnly = false;
  12002. return BfTypedValue(tempVar, type,
  12003. typedVal.IsThis() ?
  12004. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  12005. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  12006. }
  12007. return LoadValue(typedVal);
  12008. }
  12009. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  12010. {
  12011. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  12012. typedValue.mKind = BfTypedValueKind_Addr;
  12013. return typedValue;
  12014. }
  12015. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  12016. {
  12017. return MakeAddressable(LoadValue(typedValue), true);
  12018. }
  12019. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  12020. {
  12021. BF_ASSERT(!mIsComptimeModule);
  12022. BfIRValue val;
  12023. if (typedValue.mValue.IsArg())
  12024. {
  12025. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  12026. if (isAddr != NULL)
  12027. {
  12028. if (wantType != NULL)
  12029. *isAddr = wantType->IsComposite();
  12030. else
  12031. *isAddr = false;
  12032. }
  12033. else if (wantType->IsComposite())
  12034. val = mBfIRBuilder->CreateLoad(val);
  12035. }
  12036. if (!val)
  12037. {
  12038. auto checkMethodState = mCurMethodState;
  12039. while (checkMethodState != NULL)
  12040. {
  12041. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  12042. {
  12043. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  12044. if (decompAddr == typedValue.mValue)
  12045. {
  12046. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  12047. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  12048. {
  12049. // This is really backing for a POINTER to a composite inside a methodRef
  12050. val = mBfIRBuilder->CreateLoad(val);
  12051. }
  12052. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  12053. {
  12054. *isAddr = true;
  12055. return val;
  12056. }
  12057. else
  12058. {
  12059. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  12060. break;
  12061. }
  12062. }
  12063. }
  12064. if (val)
  12065. break;
  12066. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  12067. {
  12068. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12069. return mBfIRBuilder->GetFakeVal();
  12070. }
  12071. checkMethodState = checkMethodState->mPrevMethodState;
  12072. }
  12073. }
  12074. if (val)
  12075. {
  12076. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  12077. {
  12078. BF_ASSERT(wantType != NULL);
  12079. if (wantType != NULL)
  12080. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  12081. }
  12082. return val;
  12083. }
  12084. BFMODULE_FATAL(this, "Splat not found");
  12085. return BfIRValue();
  12086. }
  12087. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  12088. {
  12089. int useFieldIdx = fieldIdx;
  12090. BfType* fieldType = NULL;
  12091. if (fieldInstance != NULL)
  12092. {
  12093. fieldType = fieldInstance->mResolvedType;
  12094. if (typedValue.mType->IsUnion())
  12095. {
  12096. if (fieldIdx == 1)
  12097. {
  12098. if (typedValue.IsSplat())
  12099. {
  12100. bool isAddr = false;
  12101. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12102. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12103. }
  12104. }
  12105. }
  12106. }
  12107. else
  12108. {
  12109. if (typedValue.mType->IsPayloadEnum())
  12110. {
  12111. auto typeInst = typedValue.mType->ToTypeInstance();
  12112. if (fieldIdx == 1)
  12113. fieldType = typeInst->GetUnionInnerType();
  12114. else if (fieldIdx == 2)
  12115. {
  12116. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  12117. }
  12118. }
  12119. else if (typedValue.mType->IsUnion())
  12120. {
  12121. if (fieldIdx == 1)
  12122. {
  12123. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  12124. if (typedValue.IsSplat())
  12125. {
  12126. bool isAddr = false;
  12127. BfIRValue irVal = ExtractSplatValue(typedValue, 0, fieldType, &isAddr);
  12128. return BfTypedValue(irVal, fieldType, typedValue.mValue.IsArg() ? BfTypedValueKind_SplatHead : BfTypedValueKind_Addr);
  12129. }
  12130. }
  12131. }
  12132. }
  12133. BF_ASSERT(typedValue.mType->IsStruct());
  12134. if (typedValue.IsSplat())
  12135. {
  12136. if (typedValue.mType->IsPayloadEnum())
  12137. {
  12138. if (fieldIdx == 1)
  12139. {
  12140. // Payload
  12141. auto typeInst = typedValue.mType->ToTypeInstance();
  12142. auto unionInnerType = typeInst->GetUnionInnerType();
  12143. bool isAddr = false;
  12144. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  12145. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  12146. }
  12147. if (fieldIdx == 2)
  12148. {
  12149. // Discriminator
  12150. auto typeInst = typedValue.mType->ToTypeInstance();
  12151. auto unionInnerType = typeInst->GetUnionInnerType();
  12152. auto dscrType = typeInst->GetDiscriminatorType();
  12153. int argIdx = typedValue.mValue.mId;
  12154. int componentIdx = 0;
  12155. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  12156. bool isAddr;
  12157. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  12158. return BfTypedValue(irVal, dscrType, isAddr);
  12159. }
  12160. }
  12161. int componentIdx = 0;
  12162. BfTypedValue retVal;
  12163. BfFieldInstance* wantFieldInstance = fieldInstance;
  12164. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  12165. {
  12166. if (checkType->IsStruct())
  12167. {
  12168. auto checkTypeInstance = checkType->ToTypeInstance();
  12169. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  12170. {
  12171. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  12172. fieldType = checkTypeInstance->GetUnionInnerType();
  12173. checkTypeLambda(fieldType);
  12174. if (checkType->IsEnum())
  12175. {
  12176. // Past discriminator...
  12177. componentIdx++;
  12178. }
  12179. return;
  12180. }
  12181. if (checkTypeInstance->mBaseType != NULL)
  12182. checkTypeLambda(checkTypeInstance->mBaseType);
  12183. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12184. {
  12185. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12186. if (fieldInstance == wantFieldInstance)
  12187. {
  12188. if (fieldInstance->mResolvedType->IsValuelessType())
  12189. {
  12190. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  12191. break;
  12192. }
  12193. bool isAddr = false;
  12194. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  12195. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  12196. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  12197. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  12198. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  12199. {
  12200. retVal = LoadValue(retVal);
  12201. }
  12202. break;
  12203. }
  12204. if (fieldInstance->mDataIdx >= 0)
  12205. checkTypeLambda(fieldInstance->GetResolvedType());
  12206. }
  12207. }
  12208. else if (!checkType->IsValuelessType())
  12209. {
  12210. componentIdx++;
  12211. //argIdx++;
  12212. }
  12213. };
  12214. checkTypeLambda(typedValue.mType);
  12215. BF_ASSERT(retVal);
  12216. return retVal;
  12217. }
  12218. if (typedValue.IsAddr())
  12219. {
  12220. BF_ASSERT(fieldType != NULL);
  12221. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  12222. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  12223. }
  12224. else
  12225. {
  12226. BF_ASSERT(fieldType != NULL);
  12227. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  12228. }
  12229. }
  12230. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  12231. {
  12232. if (typedValue.IsAddr())
  12233. {
  12234. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  12235. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  12236. }
  12237. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  12238. }
  12239. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  12240. {
  12241. if (isElementIndex)
  12242. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12243. else
  12244. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12245. // if (elementType->IsSizeAligned())
  12246. // {
  12247. // if (isElementIndex)
  12248. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  12249. // else
  12250. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12251. // }
  12252. //
  12253. // auto ptrType = CreatePointerType(elementType);
  12254. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  12255. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  12256. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  12257. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  12258. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  12259. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  12260. }
  12261. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  12262. {
  12263. if (elementType->IsSizeAligned())
  12264. {
  12265. if (isElementIndex)
  12266. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  12267. else
  12268. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  12269. }
  12270. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  12271. }
  12272. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  12273. {
  12274. if (modifyType == NULL)
  12275. modifyType = "modify";
  12276. if (typedValue.mType->IsVar())
  12277. return true;
  12278. if (typedValue.IsReadOnly())
  12279. {
  12280. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  12281. return false;
  12282. }
  12283. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  12284. {
  12285. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  12286. return false;
  12287. }
  12288. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  12289. {
  12290. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  12291. return false;
  12292. }
  12293. return true;
  12294. }
  12295. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12296. {
  12297. // If one is an interface and the other is an impl, B is the impl
  12298. auto implOwner = methodB->GetOwner();
  12299. if (methodA->mMethodDef->mIsLocalMethod)
  12300. {
  12301. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  12302. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  12303. if (sepPosA != sepPosB)
  12304. return false;
  12305. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  12306. return false;
  12307. }
  12308. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  12309. return false;
  12310. if (methodA->mMethodDef->mAppendKind != methodB->mMethodDef->mAppendKind)
  12311. return false;
  12312. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  12313. return false;
  12314. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  12315. return false;
  12316. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  12317. return false;
  12318. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  12319. {
  12320. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12321. return false;
  12322. }
  12323. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  12324. {
  12325. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  12326. return false;
  12327. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  12328. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  12329. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  12330. return false;
  12331. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  12332. return false;
  12333. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  12334. return false;
  12335. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  12336. {
  12337. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  12338. return false;
  12339. }
  12340. }
  12341. int implicitParamCountA = methodA->GetImplicitParamCount();
  12342. int implicitParamCountB = methodB->GetImplicitParamCount();
  12343. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  12344. return false;
  12345. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  12346. return false;
  12347. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  12348. {
  12349. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  12350. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  12351. return false;
  12352. }
  12353. // Compare generic params. Generic params are part of the method signature here
  12354. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  12355. return false;
  12356. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  12357. {
  12358. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  12359. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  12360. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  12361. return false;
  12362. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  12363. return false;
  12364. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  12365. return false;
  12366. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  12367. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  12368. return false;
  12369. }
  12370. return true;
  12371. }
  12372. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  12373. {
  12374. if (!CompareMethodSignatures(methodA, methodB))
  12375. return false;
  12376. if (methodA->mReturnType != methodB->mReturnType)
  12377. return false;
  12378. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  12379. return false;
  12380. return true;
  12381. }
  12382. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  12383. {
  12384. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  12385. return false;
  12386. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  12387. return false;
  12388. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  12389. return false;
  12390. if (iMethodInst->mMethodDef->mIsOperator)
  12391. {
  12392. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  12393. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  12394. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  12395. return false;
  12396. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  12397. return false;
  12398. }
  12399. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  12400. return false;
  12401. auto selfType = methodInstance->GetOwner();
  12402. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  12403. {
  12404. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  12405. return false;
  12406. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  12407. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  12408. iParamType = ResolveSelfType(iParamType, selfType);
  12409. methodParamType = ResolveSelfType(methodParamType, selfType);
  12410. if (!iParamType->IsGenericParam())
  12411. {
  12412. if (methodParamType != iParamType)
  12413. return false;
  12414. }
  12415. else
  12416. {
  12417. if (!methodParamType->IsGenericParam())
  12418. return false;
  12419. auto genericParamType = (BfGenericParamType*)methodParamType;
  12420. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  12421. return false;
  12422. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12423. bool hadInterface = false;
  12424. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  12425. if (interfaceConstraint == iParamType)
  12426. hadInterface = true;
  12427. if (!hadInterface)
  12428. return false;
  12429. }
  12430. }
  12431. return true;
  12432. }
  12433. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  12434. {
  12435. BfMethodInstance* methodInstance = methodRef;
  12436. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  12437. {
  12438. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  12439. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12440. {
  12441. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  12442. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  12443. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12444. BfMethodRef methodRef = methodInstance;
  12445. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  12446. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  12447. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  12448. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  12449. (mIsReified))
  12450. {
  12451. specializedMethodRefInfo->mHasReifiedRef = true;
  12452. }
  12453. }
  12454. }
  12455. }
  12456. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12457. {
  12458. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  12459. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12460. if (mBfIRBuilder == NULL)
  12461. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12462. if (methodInstance->GetOwner()->IsFunction())
  12463. {
  12464. // No actual ref needed- not an actual generated function
  12465. return BfModuleMethodInstance(methodInstance, BfIRValue());
  12466. }
  12467. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  12468. if (!isGenFunction)
  12469. AddMethodReference(methodInstance, flags);
  12470. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  12471. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  12472. if (IsSkippingExtraResolveChecks())
  12473. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12474. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  12475. {
  12476. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12477. }
  12478. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12479. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  12480. isInlined = false;
  12481. BfMethodRef methodRef = methodInstance;
  12482. if (isInlined)
  12483. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  12484. else
  12485. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  12486. if (!isGenFunction)
  12487. {
  12488. BfIRValue* irFuncPtr = NULL;
  12489. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  12490. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  12491. }
  12492. if (mAwaitingInitFinish)
  12493. FinishInit();
  12494. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  12495. if (!isGenFunction)
  12496. {
  12497. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  12498. mFuncReferences[methodRef] = func;
  12499. }
  12500. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  12501. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12502. {
  12503. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  12504. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  12505. // type instance
  12506. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  12507. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  12508. for (auto ownedTypeInst : mOwnedTypeInstances)
  12509. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  12510. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  12511. {
  12512. mIncompleteMethodCount++;
  12513. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12514. inlineMethodRequest->mType = methodInstance->GetOwner();
  12515. inlineMethodRequest->mFromModule = this;
  12516. inlineMethodRequest->mFunc = func;
  12517. inlineMethodRequest->mFromModuleRevision = mRevision;
  12518. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  12519. inlineMethodRequest->mMethodInstance = methodInstance;
  12520. BF_ASSERT(mIsModuleMutable);
  12521. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12522. }
  12523. }
  12524. return BfModuleMethodInstance(methodInstance, func);
  12525. }
  12526. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  12527. {
  12528. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  12529. if (mBfIRBuilder == NULL)
  12530. {
  12531. // To allow for custom attribute data
  12532. PrepareForIRWriting(typeInst);
  12533. }
  12534. BfModule* declareModule = this;
  12535. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  12536. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  12537. declareModule = declareModule->mParentModule;
  12538. // Check for attributes
  12539. if (typeInst == mContext->mBfObjectType)
  12540. {
  12541. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  12542. if (methodDecl != NULL)
  12543. {
  12544. auto attributesDirective = methodDecl->mAttributes;
  12545. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  12546. {
  12547. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  12548. sourceClassifier->VisitChild(attributesDirective);
  12549. }
  12550. }
  12551. }
  12552. else
  12553. {
  12554. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  12555. GetMethodCustomAttributes(methodInstance);
  12556. }
  12557. BF_ASSERT(mModuleOptions == NULL);
  12558. if (methodInstance->GetCustomAttributes() != NULL)
  12559. {
  12560. auto project = typeInst->mTypeDef->mProject;
  12561. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  12562. BfModuleOptions wantOptions = moduleOptions;
  12563. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  12564. if (typeOptions != NULL)
  12565. {
  12566. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  12567. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  12568. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  12569. }
  12570. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  12571. {
  12572. StringT<128> attrName;
  12573. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  12574. {
  12575. attrName.Clear();
  12576. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  12577. Array<int>* arrPtr;
  12578. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  12579. {
  12580. for (auto optionsIdx : *arrPtr)
  12581. {
  12582. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  12583. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  12584. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  12585. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  12586. }
  12587. }
  12588. }
  12589. }
  12590. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  12591. {
  12592. auto lastCheckModule = this;
  12593. auto checkModule = this->mNextAltModule;
  12594. while (checkModule != NULL)
  12595. {
  12596. if (*checkModule->mModuleOptions == wantOptions)
  12597. {
  12598. declareModule = checkModule;
  12599. break;
  12600. }
  12601. lastCheckModule = checkModule;
  12602. checkModule = checkModule->mNextAltModule;
  12603. }
  12604. // Not found?
  12605. if (declareModule == this)
  12606. {
  12607. String specModuleName = mModuleName + "@@";
  12608. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  12609. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  12610. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  12611. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  12612. declareModule = new BfModule(mContext, specModuleName);
  12613. declareModule->mProject = project;
  12614. declareModule->mModuleOptions = new BfModuleOptions();
  12615. *declareModule->mModuleOptions = wantOptions;
  12616. declareModule->mParentModule = lastCheckModule;
  12617. declareModule->Init();
  12618. lastCheckModule->mNextAltModule = declareModule;
  12619. }
  12620. }
  12621. }
  12622. declareModule->PrepareForIRWriting(typeInst);
  12623. return declareModule;
  12624. }
  12625. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType, BfModule* referencingModule)
  12626. {
  12627. if (methodDef->mMethodType == BfMethodType_Init)
  12628. return BfModuleMethodInstance();
  12629. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  12630. {
  12631. // Don't bother inlining for resolve-only
  12632. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12633. }
  12634. if (methodDef->mIsExtern)
  12635. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12636. bool processNow = false;
  12637. bool keepInCurrentModule = false;
  12638. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  12639. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  12640. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  12641. {
  12642. return BfModuleMethodInstance();
  12643. }
  12644. if (methodDef->mIsLocalMethod)
  12645. {
  12646. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12647. BfLocalMethod* localMethod;
  12648. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  12649. {
  12650. // Handle the def in the correct method state
  12651. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  12652. }
  12653. BFMODULE_FATAL(this, "Cannot find local method");
  12654. return BfModuleMethodInstance();
  12655. }
  12656. #ifdef _DEBUG
  12657. for (auto arg : methodGenericArguments)
  12658. BF_ASSERT(!arg->IsVar());
  12659. #endif
  12660. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  12661. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  12662. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  12663. // a FinishInit
  12664. if ((typeInst->IsIncomplete()) &&
  12665. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  12666. {
  12667. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  12668. // for resolve-only because we don't differentiate between reified/unreified there
  12669. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  12670. {
  12671. if (!typeInst->DefineStateAllowsStaticMethods())
  12672. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  12673. }
  12674. else
  12675. PopulateType(typeInst, BfPopulateType_Full);
  12676. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  12677. {
  12678. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12679. {
  12680. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  12681. return BfModuleMethodInstance();
  12682. }
  12683. }
  12684. }
  12685. bool tryModuleMethodLookup = false;
  12686. BfModuleMethodInstance moduleMethodInst;
  12687. BfModule* instModule = typeInst->mModule;
  12688. if (keepInCurrentModule)
  12689. {
  12690. // Stay here
  12691. instModule = this;
  12692. }
  12693. if (this == mContext->mUnreifiedModule)
  12694. {
  12695. // Stay in this 'resolve only' module here
  12696. }
  12697. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  12698. {
  12699. BF_ASSERT(this == mContext->mUnreifiedModule);
  12700. }
  12701. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  12702. {
  12703. BF_ASSERT(instModule == mParentModule);
  12704. }
  12705. else if (instModule != this)
  12706. {
  12707. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12708. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  12709. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  12710. {
  12711. BF_ASSERT(!mCompiler->mIsResolveOnly);
  12712. // A resolve-only module is specializing a method from a type in a reified module,
  12713. // we need to take care that this doesn't cause anything new to become reified
  12714. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  12715. if (!moduleMethodInstance)
  12716. return moduleMethodInstance;
  12717. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  12718. return moduleMethodInstance;
  12719. }
  12720. else
  12721. {
  12722. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12723. {
  12724. if (!typeInst->IsUnspecializedType())
  12725. {
  12726. if (!instModule->mReifyQueued)
  12727. {
  12728. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12729. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12730. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12731. mContext->mReifyModuleWorkList.Add(instModule);
  12732. instModule->mReifyQueued = true;
  12733. }
  12734. BfLogSysM("REIFIED(GetMethodInstance QueueSpecializationRequest): %s %s MethodDef:%p RefModule:%s RefMethod:%p\n", TypeToString(typeInst).c_str(), methodDef->mName.c_str(), methodDef, mModuleName.c_str(), mCurMethodInstance);
  12735. // This ensures that the method will actually be created when it gets reified
  12736. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12737. specializationRequest->mFromModule = typeInst->mModule;
  12738. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12739. specializationRequest->Init(typeInst, foreignType, methodDef);
  12740. //specializationRequest->mMethodDef = methodDef;
  12741. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12742. specializationRequest->mType = typeInst;
  12743. specializationRequest->mFlags = flags;
  12744. }
  12745. }
  12746. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12747. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12748. if (mIsComptimeModule)
  12749. {
  12750. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12751. if (!mCompiler->mIsResolveOnly)
  12752. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12753. }
  12754. // Not extern
  12755. // Create the instance in the proper module and then create a reference in this one
  12756. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType, this);
  12757. if (!moduleMethodInst)
  12758. return moduleMethodInst;
  12759. tryModuleMethodLookup = true;
  12760. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12761. {
  12762. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12763. }
  12764. }
  12765. }
  12766. if (tryModuleMethodLookup)
  12767. {
  12768. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12769. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12770. }
  12771. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12772. {
  12773. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12774. if (moduleMethodInstance)
  12775. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12776. return moduleMethodInst;
  12777. }
  12778. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12779. bool hadConcreteInterfaceGenericArgument = false;
  12780. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12781. isReified = false;
  12782. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12783. {
  12784. isReified = false;
  12785. }
  12786. BfTypeVector sanitizedMethodGenericArguments;
  12787. SizedArray<BfProject*, 4> projectList;
  12788. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12789. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12790. isUnspecializedPass = false;
  12791. // 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
  12792. bool isExternalExtensionMethod = false;
  12793. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12794. {
  12795. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12796. (methodDef->mDeclaringType != NULL) &&
  12797. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12798. {
  12799. auto specProject = methodDef->mDeclaringType->mProject;
  12800. isExternalExtensionMethod = true;
  12801. if (typeInst->IsGenericTypeInstance())
  12802. {
  12803. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12804. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12805. genericTypeInst->GenerateProjectsReferenced();
  12806. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12807. {
  12808. // This is a generic type where a generic param is already confined to the project in question
  12809. isExternalExtensionMethod = false;
  12810. }
  12811. }
  12812. if (isExternalExtensionMethod)
  12813. {
  12814. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12815. projectList.push_back(methodDef->mDeclaringType->mProject);
  12816. }
  12817. }
  12818. }
  12819. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12820. {
  12821. int typeProjectsCounts = 0;
  12822. if (typeInst->IsGenericTypeInstance())
  12823. {
  12824. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12825. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12826. genericTypeInst->GenerateProjectsReferenced();
  12827. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12828. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12829. }
  12830. else
  12831. {
  12832. typeProjectsCounts = 1;
  12833. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12834. }
  12835. isUnspecializedPass = true;
  12836. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12837. {
  12838. auto genericArgType = methodGenericArguments[genericArgIdx];
  12839. //BF_ASSERT(!genericArgType->IsRef());
  12840. if (genericArgType->IsConcreteInterfaceType())
  12841. {
  12842. hadConcreteInterfaceGenericArgument = true;
  12843. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12844. genericArgType = concreteInterfaceType->mInterface;
  12845. }
  12846. if (genericArgType->IsGenericParam())
  12847. {
  12848. auto genericParam = (BfGenericParamType*) genericArgType;
  12849. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12850. isUnspecializedPass = false;
  12851. }
  12852. else
  12853. {
  12854. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12855. isUnspecializedPass = false;
  12856. }
  12857. sanitizedMethodGenericArguments.push_back(genericArgType);
  12858. }
  12859. if ((int)projectList.size() > typeProjectsCounts)
  12860. {
  12861. // Just leave the new items
  12862. projectList.RemoveRange(0, typeProjectsCounts);
  12863. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12864. {
  12865. return lhs->mName < rhs->mName;
  12866. });
  12867. }
  12868. else
  12869. {
  12870. projectList.Clear();
  12871. }
  12872. }
  12873. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12874. BfMethodInstanceGroup* methodInstGroup = NULL;
  12875. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12876. {
  12877. BF_ASSERT(!typeInst->IsInterface());
  12878. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12879. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12880. {
  12881. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12882. // if (checkGroup.mDefault == NULL)
  12883. // {
  12884. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12885. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12886. // methodInstGroup = &checkGroup;
  12887. // break;
  12888. // }
  12889. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12890. {
  12891. methodInstGroup = &checkGroup;
  12892. break;
  12893. }
  12894. }
  12895. if (methodInstGroup == NULL)
  12896. {
  12897. if (lookupMethodGenericArguments.size() != 0)
  12898. {
  12899. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12900. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12901. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12902. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12903. }
  12904. else
  12905. {
  12906. // Allocate a new entry
  12907. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12908. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12909. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12910. methodInstGroup->mOwner = typeInst;
  12911. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12912. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12913. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12914. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12915. else
  12916. {
  12917. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12918. if (!mIsScratchModule)
  12919. mOnDemandMethodCount++;
  12920. }
  12921. }
  12922. }
  12923. }
  12924. else
  12925. {
  12926. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12927. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12928. if (methodDef->mIdx >= typeInst->mMethodInstanceGroups.mSize)
  12929. {
  12930. InternalError("GetMethodInstance OOB error", methodDef->GetRefNode());
  12931. return BfModuleMethodInstance();
  12932. }
  12933. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12934. }
  12935. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12936. {
  12937. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12938. {
  12939. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12940. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12941. }
  12942. }
  12943. BfIRFunction prevIRFunc;
  12944. bool doingRedeclare = false;
  12945. BfMethodInstance* methodInstance = NULL;
  12946. auto _SetReified = [&]()
  12947. {
  12948. if (!mCompiler->mIsResolveOnly)
  12949. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12950. methodInstance->mIsReified = true;
  12951. };
  12952. if (lookupMethodGenericArguments.size() == 0)
  12953. {
  12954. methodInstance = methodInstGroup->mDefault;
  12955. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12956. return methodInstance;
  12957. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12958. {
  12959. MarkDerivedDirty(typeInst);
  12960. if (!HasCompiledOutput())
  12961. {
  12962. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12963. _SetReified();
  12964. CheckHotMethod(methodInstance, "");
  12965. }
  12966. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12967. {
  12968. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12969. // the specializations to handle that for us
  12970. return BfModuleMethodInstance(methodInstance);
  12971. }
  12972. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12973. {
  12974. if (methodDef->mIsAbstract)
  12975. {
  12976. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12977. _SetReified();
  12978. }
  12979. else
  12980. {
  12981. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12982. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12983. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12984. doingRedeclare = true;
  12985. mOnDemandMethodCount++;
  12986. VerifyOnDemandMethods();
  12987. }
  12988. }
  12989. else
  12990. {
  12991. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12992. // We haven't processed it yet
  12993. _SetReified();
  12994. CheckHotMethod(methodInstance, "");
  12995. if (methodInstance->mDeclModule == this)
  12996. {
  12997. if (methodInstance->mMethodProcessRequest != NULL)
  12998. {
  12999. // Disconnect method process request
  13000. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  13001. }
  13002. }
  13003. else
  13004. {
  13005. if (methodInstance->mMethodProcessRequest != NULL)
  13006. {
  13007. // Disconnect method process request
  13008. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  13009. methodInstance->mMethodProcessRequest = NULL;
  13010. }
  13011. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  13012. {
  13013. // Add new request in proper module
  13014. methodInstance->mDeclModule = this;
  13015. }
  13016. else
  13017. {
  13018. if (methodInstance->mDeclModule == NULL)
  13019. {
  13020. //
  13021. }
  13022. else if (methodInstance->mDeclModule != this)
  13023. {
  13024. // Is from specialized module?
  13025. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  13026. }
  13027. }
  13028. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  13029. {
  13030. methodInstance->mIRFunction = BfIRFunction();
  13031. if (!mIsModuleMutable)
  13032. StartExtension();
  13033. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  13034. {
  13035. StringT<512> mangledName;
  13036. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  13037. bool isIntrinsic = false;
  13038. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13039. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  13040. }
  13041. }
  13042. AddMethodToWorkList(methodInstance);
  13043. }
  13044. }
  13045. }
  13046. }
  13047. else
  13048. {
  13049. if (methodInstGroup->mDefault == NULL)
  13050. {
  13051. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  13052. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  13053. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  13054. }
  13055. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  13056. if (methodInstGroup->mMethodSpecializationMap == NULL)
  13057. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  13058. BfMethodInstance** methodInstancePtr = NULL;
  13059. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  13060. {
  13061. methodInstance = *methodInstancePtr;
  13062. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  13063. return methodInstance;
  13064. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  13065. {
  13066. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  13067. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  13068. if (methodInstance->mMethodProcessRequest == NULL)
  13069. AddMethodToWorkList(methodInstance);
  13070. methodInstance->mRequestedByAutocomplete = false;
  13071. }
  13072. if ((isReified) && (!methodInstance->mIsReified))
  13073. {
  13074. MarkDerivedDirty(typeInst);
  13075. if (methodInstance->mHasBeenProcessed)
  13076. {
  13077. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  13078. delete methodInstance;
  13079. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13080. methodInstance = NULL;
  13081. }
  13082. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  13083. {
  13084. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  13085. delete methodInstance;
  13086. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  13087. methodInstance = NULL;
  13088. }
  13089. else
  13090. {
  13091. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  13092. // We haven't processed it yet
  13093. _SetReified();
  13094. CheckHotMethod(methodInstance, "");
  13095. if (methodInstance->mMethodProcessRequest == NULL)
  13096. AddMethodToWorkList(methodInstance);
  13097. }
  13098. }
  13099. }
  13100. }
  13101. auto _CheckDllImport = [&]()
  13102. {
  13103. auto declModule = methodInstance->mDeclModule;
  13104. if ((!methodInstance->mIRFunction) && (declModule->mIsModuleMutable) && (!declModule->mBfIRBuilder->mIgnoreWrites))
  13105. {
  13106. auto importKind = methodInstance->GetImportCallKind();
  13107. if (importKind != BfImportCallKind_None)
  13108. {
  13109. BfLogSysM("DllImportGlobalVar creating %p in module %p from module %p\n", methodInstance, declModule, this);
  13110. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13111. auto func = declModule->CreateDllImportGlobalVar(methodInstance, true);
  13112. BF_ASSERT(func);
  13113. declModule->mFuncReferences[methodInstance] = func;
  13114. }
  13115. }
  13116. };
  13117. if ((methodInstance != NULL) && (!doingRedeclare))
  13118. {
  13119. SetMethodDependency(methodInstance);
  13120. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  13121. {
  13122. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  13123. BF_ASSERT(!methodInstance->mIsReified);*/
  13124. if ((!mCompiler->mIsResolveOnly) && (isReified))
  13125. {
  13126. auto refModule = referencingModule;
  13127. if (refModule == NULL)
  13128. refModule = this;
  13129. BfLogSysM("REIFIED(GetMethodInstance Reference): %s MethodDef:%p MethodInst:%p RefModule:%s RefMethod:%p\n", methodInstance->mMethodDef->mName.c_str(), methodDef, methodInstance, refModule->mModuleName.c_str(), refModule->mCurMethodInstance);
  13130. }
  13131. if (methodInstance->mIsReified != isReified)
  13132. {
  13133. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  13134. }
  13135. if ((!isReified) &&
  13136. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  13137. {
  13138. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  13139. methodInstance->mIRFunction = BfIRFunction();
  13140. }
  13141. methodInstance->mIsReified = isReified;
  13142. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  13143. {
  13144. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  13145. }
  13146. if (!methodInstance->mMethodDef->mIsAbstract)
  13147. {
  13148. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  13149. {
  13150. // Wait until unreified
  13151. }
  13152. else
  13153. AddMethodToWorkList(methodInstance);
  13154. }
  13155. else
  13156. {
  13157. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13158. auto owningModule = methodInstance->GetOwner()->mModule;
  13159. if (!owningModule->mIsScratchModule)
  13160. {
  13161. owningModule->mOnDemandMethodCount--;
  13162. owningModule->VerifyOnDemandMethods();
  13163. }
  13164. }
  13165. }
  13166. if (mExtensionCount > 0)
  13167. {
  13168. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  13169. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  13170. {
  13171. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  13172. if (mAwaitingInitFinish)
  13173. FinishInit();
  13174. // We need to refer to a function that was defined in a prior module
  13175. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  13176. if (methodInstance->mIsIntrinsic)
  13177. isInlined = false;
  13178. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  13179. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  13180. methodInstance->mDeclModule = this;
  13181. // Add this inlined def to ourselves
  13182. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  13183. {
  13184. mIncompleteMethodCount++;
  13185. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  13186. inlineMethodRequest->mType = typeInst;
  13187. inlineMethodRequest->mFromModule = this;
  13188. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  13189. inlineMethodRequest->mFromModuleRevision = mRevision;
  13190. inlineMethodRequest->mFromModuleRebuildIdx = mRebuildIdx;
  13191. inlineMethodRequest->mMethodInstance = methodInstance;
  13192. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  13193. BF_ASSERT(mIsModuleMutable);
  13194. }
  13195. }
  13196. }
  13197. if (IsSkippingExtraResolveChecks())
  13198. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13199. else
  13200. {
  13201. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13202. return methodInstance;
  13203. if (methodInstance->mDeclModule != this)
  13204. return ReferenceExternalMethodInstance(methodInstance, flags);
  13205. _CheckDllImport();
  13206. return BfModuleMethodInstance(methodInstance);
  13207. }
  13208. }
  13209. if (!doingRedeclare)
  13210. {
  13211. BfModule* specModule = NULL;
  13212. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  13213. {
  13214. specModule = GetSpecializedMethodModule(projectList);
  13215. }
  13216. if ((specModule != NULL) && (specModule != this))
  13217. {
  13218. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  13219. if (mAwaitingInitFinish)
  13220. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  13221. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  13222. return specMethodInstance.mMethodInstance;
  13223. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  13224. }
  13225. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  13226. {
  13227. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  13228. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  13229. }
  13230. }
  13231. if (methodInstance == NULL)
  13232. {
  13233. if (!mCompiler->EnsureCeUnpaused(typeInst))
  13234. {
  13235. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  13236. return BfModuleMethodInstance();
  13237. }
  13238. if (lookupMethodGenericArguments.size() == 0)
  13239. {
  13240. BF_ASSERT(methodInstGroup->mDefault == NULL);
  13241. methodInstance = new BfMethodInstance();
  13242. methodInstGroup->mDefault = methodInstance;
  13243. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  13244. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  13245. }
  13246. else
  13247. {
  13248. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  13249. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  13250. depthExceeded = true;
  13251. if (depthExceeded)
  13252. {
  13253. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  13254. return BfModuleMethodInstance();
  13255. }
  13256. BfMethodInstance** methodInstancePtr = NULL;
  13257. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  13258. BF_ASSERT(added);
  13259. methodInstance = new BfMethodInstance();
  13260. *methodInstancePtr = methodInstance;
  13261. if (mCompiler->IsAutocomplete())
  13262. methodInstance->mRequestedByAutocomplete = true;
  13263. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  13264. }
  13265. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  13266. methodInstance->mIRFunction = prevIRFunc; // Take it over
  13267. }
  13268. methodInstance->mMethodDef = methodDef;
  13269. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  13270. methodInstance->mMethodInstanceGroup = methodInstGroup;
  13271. methodInstance->mIsReified = isReified;
  13272. SetupMethodIdHash(methodInstance);
  13273. if (hadConcreteInterfaceGenericArgument)
  13274. methodInstance->mIgnoreBody = true;
  13275. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  13276. {
  13277. methodInstance->mIsForeignMethodDef = true;
  13278. BF_ASSERT(foreignType != NULL);
  13279. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  13280. }
  13281. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  13282. {
  13283. if (!lookupMethodGenericArguments.empty())
  13284. {
  13285. auto compareType = lookupMethodGenericArguments[0];
  13286. PopulateType(compareType, BfPopulateType_Data);
  13287. if (compareType->IsSplattable())
  13288. methodInstance->mAlwaysInline = true;
  13289. }
  13290. }
  13291. if (methodDef->mMethodType == BfMethodType_Init)
  13292. {
  13293. methodInstance->mMangleWithIdx = true;
  13294. }
  13295. if (methodDef->mAppendKind > BfAllowAppendKind_No)
  13296. {
  13297. methodInstance->mMangleWithIdx = true;
  13298. }
  13299. BF_ASSERT(typeInst == methodInstance->GetOwner());
  13300. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13301. if (isUnspecializedPass)
  13302. {
  13303. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  13304. {
  13305. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  13306. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  13307. }
  13308. }
  13309. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  13310. {
  13311. if (!sanitizedMethodGenericArguments.IsEmpty())
  13312. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  13313. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  13314. {
  13315. Fail("Internal error");
  13316. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  13317. return NULL;
  13318. }
  13319. for (auto genericArg : sanitizedMethodGenericArguments)
  13320. {
  13321. if (genericArg->IsPrimitiveType())
  13322. genericArg = GetWrappedStructType(genericArg);
  13323. if (genericArg != NULL)
  13324. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  13325. }
  13326. }
  13327. // Generic constraints
  13328. if (!methodDef->mGenericParams.IsEmpty())
  13329. {
  13330. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  13331. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  13332. {
  13333. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  13334. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13335. }
  13336. }
  13337. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  13338. {
  13339. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  13340. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  13341. }
  13342. bool addToWorkList = !processNow;
  13343. if (mCompiler->GetAutoComplete() != NULL)
  13344. {
  13345. if (typeInst->IsSpecializedByAutoCompleteMethod())
  13346. addToWorkList = false;
  13347. if (methodInstance->mRequestedByAutocomplete)
  13348. addToWorkList = false;
  13349. }
  13350. BfModule* declareModule;
  13351. //
  13352. {
  13353. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13354. declareModule = GetOrCreateMethodModule(methodInstance);
  13355. }
  13356. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  13357. declareModule = methodInstance->mDeclModule;
  13358. BF_ASSERT(declareModule != NULL);
  13359. methodInstance->mDeclModule = declareModule;
  13360. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  13361. {
  13362. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  13363. // of a reified module -
  13364. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  13365. // BUT if we don't reify it then we have to remove the body after processing.
  13366. // 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
  13367. // the proper reified module.
  13368. declareModule = mContext->mUnreifiedModule;
  13369. }
  13370. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  13371. {
  13372. if (!methodInstance->mIsReified)
  13373. {
  13374. declareModule = mContext->mUnreifiedModule;
  13375. }
  13376. else
  13377. {
  13378. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  13379. }
  13380. }
  13381. SetMethodDependency(methodInstance);
  13382. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  13383. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  13384. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  13385. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  13386. {
  13387. // For mixins we only process the unspecialized version
  13388. addToWorkList = false;
  13389. }
  13390. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  13391. {
  13392. addToWorkList = false;
  13393. }
  13394. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  13395. // addToWorkList = false;
  13396. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  13397. if (processNow)
  13398. {
  13399. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  13400. ProcessMethod(methodInstance);
  13401. }
  13402. if (IsSkippingExtraResolveChecks())
  13403. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  13404. if (methodInstance->mDeclModule != this)
  13405. return ReferenceExternalMethodInstance(methodInstance, flags);
  13406. if (doingRedeclare)
  13407. {
  13408. _CheckDllImport();
  13409. }
  13410. return BfModuleMethodInstance(methodInstance);
  13411. }
  13412. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  13413. {
  13414. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  13415. if (methodInstance->mIsForeignMethodDef)
  13416. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  13417. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  13418. }
  13419. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  13420. {
  13421. if (!methodInstance->mMethodDef->mIsLocalMethod)
  13422. return NULL;
  13423. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  13424. if (outerLocal == NULL)
  13425. return NULL;
  13426. BfTypeVector genericArgs;
  13427. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  13428. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  13429. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  13430. }
  13431. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  13432. {
  13433. HashContext hashCtx;
  13434. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  13435. {
  13436. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  13437. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  13438. if (methodInstance->GetNumGenericArguments() != 0)
  13439. {
  13440. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  13441. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13442. hashCtx.Mixin(methodGenericArg->mTypeId);
  13443. }
  13444. };
  13445. _MixinMethodInstance(methodInstance);
  13446. if (methodInstance->mMethodDef->mIsLocalMethod)
  13447. {
  13448. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  13449. if (outmostMethodInstance != NULL)
  13450. {
  13451. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  13452. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  13453. }
  13454. }
  13455. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  13456. }
  13457. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  13458. {
  13459. if (methodInstance->mHasBeenDeclared)
  13460. return true;
  13461. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  13462. return false;
  13463. }
  13464. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  13465. {
  13466. BfIRValue globalValue;
  13467. BfIRValue* globalValuePtr = NULL;
  13468. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  13469. {
  13470. globalValue = *globalValuePtr;
  13471. }
  13472. if (!globalValue)
  13473. {
  13474. // This is necessary to reify the interface type
  13475. PopulateType(ifaceType);
  13476. StringT<512> slotVarName;
  13477. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  13478. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  13479. BfIRValue value;
  13480. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  13481. {
  13482. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  13483. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  13484. int virtSlotIdx = ifaceType->mSlotNum + 1;
  13485. value = GetConstValue32(virtSlotIdx);*/
  13486. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  13487. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  13488. }
  13489. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  13490. mInterfaceSlotRefs[ifaceType] = globalValue;
  13491. // Make sure we reify
  13492. PopulateType(ifaceType, BfPopulateType_Declaration);
  13493. AddDependency(ifaceType, mCurTypeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  13494. }
  13495. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  13496. }
  13497. void BfModule::HadSlotCountDependency()
  13498. {
  13499. if (mCompiler->mIsResolveOnly)
  13500. return;
  13501. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  13502. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  13503. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  13504. }
  13505. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  13506. {
  13507. if (str == "#IsComptime")
  13508. {
  13509. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13510. }
  13511. if (str == "#IsBuilding")
  13512. {
  13513. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13514. }
  13515. if (str == "#IsReified")
  13516. {
  13517. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  13518. }
  13519. if (str == "#CompileRev")
  13520. {
  13521. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  13522. }
  13523. if (str == "#NextId")
  13524. {
  13525. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  13526. }
  13527. if (str == "#ModuleName")
  13528. {
  13529. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13530. }
  13531. if (str == "#ProjectName")
  13532. {
  13533. if (mProject != NULL)
  13534. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13535. }
  13536. if (str == "#AllocStackCount")
  13537. {
  13538. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  13539. }
  13540. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  13541. {
  13542. if (str == "#CallerLineNum")
  13543. {
  13544. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  13545. }
  13546. else if (str == "#CallerFilePath")
  13547. {
  13548. String filePath = "";
  13549. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13550. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13551. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  13552. }
  13553. else if (str == "#CallerFileName")
  13554. {
  13555. String filePath = "";
  13556. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13557. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13558. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13559. }
  13560. else if (str == "#CallerFileDir")
  13561. {
  13562. String filePath = "";
  13563. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  13564. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  13565. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  13566. }
  13567. else if (str == "#CallerTypeName")
  13568. {
  13569. String typeName = "";
  13570. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13571. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  13572. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13573. }
  13574. else if (str == "#CallerType")
  13575. {
  13576. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  13577. BfType* type = NULL;
  13578. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13579. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  13580. if (type != NULL)
  13581. {
  13582. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  13583. return BfTypedValue(CreateTypeDataRef(type), typeType);
  13584. }
  13585. }
  13586. else if (str == "#CallerMemberName")
  13587. {
  13588. String memberName = "";
  13589. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  13590. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  13591. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13592. }
  13593. else if (str == "#CallerProject")
  13594. {
  13595. BfProject* project = NULL;
  13596. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  13597. if (project != NULL)
  13598. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  13599. }
  13600. }
  13601. if (str == "#TimeLocal")
  13602. {
  13603. time_t rawtime;
  13604. time(&rawtime);
  13605. tm* timeinfo = localtime(&rawtime);
  13606. char result[32];
  13607. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  13608. 1900 + timeinfo->tm_year,
  13609. timeinfo->tm_mon + 1,
  13610. timeinfo->tm_mday,
  13611. timeinfo->tm_hour,
  13612. timeinfo->tm_min,
  13613. timeinfo->tm_sec);
  13614. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  13615. }
  13616. return BfTypedValue();
  13617. }
  13618. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  13619. {
  13620. if (!typedValue.IsAddr())
  13621. return BfTypedValue();
  13622. if (typedValue.mValue.IsConst())
  13623. {
  13624. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  13625. if (constantValue != NULL)
  13626. {
  13627. if (constantValue->mConstType == BfConstType_GlobalVar)
  13628. {
  13629. auto globalVar = (BfGlobalVar*)constantValue;
  13630. if (globalVar->mName[0] == '#')
  13631. {
  13632. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  13633. return result;
  13634. }
  13635. }
  13636. }
  13637. }
  13638. return BfTypedValue();
  13639. }
  13640. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  13641. {
  13642. BfIRValue globalValue;
  13643. auto fieldDef = fieldInstance->GetFieldDef();
  13644. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  13645. {
  13646. if (fieldInstance->mConstIdx != -1)
  13647. {
  13648. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  13649. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  13650. }
  13651. else
  13652. {
  13653. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  13654. }
  13655. }
  13656. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  13657. {
  13658. // Just fake it for the extern and unspecialized modules
  13659. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  13660. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)), fieldInstance->GetResolvedType(), true);
  13661. }
  13662. BfIRValue* globalValuePtr = NULL;
  13663. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  13664. {
  13665. globalValue = *globalValuePtr;
  13666. BF_ASSERT(globalValue);
  13667. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  13668. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  13669. {
  13670. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  13671. mBfIRBuilder->CreateGlobalVariable(globalValue);
  13672. }
  13673. }
  13674. else
  13675. {
  13676. StringT<512> staticVarName;
  13677. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  13678. auto typeType = fieldInstance->GetResolvedType();
  13679. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  13680. {
  13681. typeType = typeType->GetUnderlyingType();
  13682. }
  13683. if (mIsComptimeModule)
  13684. {
  13685. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  13686. }
  13687. PopulateType(typeType);
  13688. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  13689. {
  13690. BfIRType irType = mBfIRBuilder->MapType(typeType);
  13691. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  13692. globalValue = mBfIRBuilder->CreateGlobalVariable(
  13693. irType,
  13694. false,
  13695. BfIRLinkageType_External,
  13696. BfIRValue(),
  13697. staticVarName,
  13698. IsThreadLocal(fieldInstance));
  13699. BF_ASSERT(globalValue);
  13700. mStaticFieldRefs[fieldInstance] = globalValue;
  13701. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  13702. }
  13703. }
  13704. auto type = fieldInstance->GetResolvedType();
  13705. if (type->IsValuelessType())
  13706. return BfTypedValue(globalValue, type);
  13707. if (fieldDef->mIsVolatile)
  13708. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  13709. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  13710. }
  13711. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  13712. {
  13713. if (typeInst->IsDataIncomplete())
  13714. PopulateType(typeInst);
  13715. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  13716. {
  13717. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  13718. return 0;
  13719. }
  13720. return &typeInst->mFieldInstances[fieldIdx];
  13721. }
  13722. void BfModule::MarkUsingThis()
  13723. {
  13724. auto useMethodState = mCurMethodState;
  13725. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13726. {
  13727. useMethodState = useMethodState->mPrevMethodState;
  13728. }
  13729. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  13730. {
  13731. auto localVar = useMethodState->mLocals[0];
  13732. if (localVar->mIsThis)
  13733. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13734. }
  13735. }
  13736. BfTypedValue BfModule::GetThis(bool markUsing)
  13737. {
  13738. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  13739. {
  13740. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  13741. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  13742. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  13743. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  13744. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  13745. {
  13746. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  13747. {
  13748. if (dbgVar.mName == "this")
  13749. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  13750. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13751. }
  13752. }
  13753. return BfTypedValue();
  13754. }
  13755. auto useMethodState = mCurMethodState;
  13756. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13757. {
  13758. useMethodState = useMethodState->mPrevMethodState;
  13759. }
  13760. if (useMethodState != NULL)
  13761. {
  13762. // Fake a 'this' for var field resolution
  13763. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13764. {
  13765. auto thisType = mCurTypeInstance;
  13766. if (thisType->IsValueType())
  13767. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13768. else
  13769. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13770. }
  13771. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13772. {
  13773. return BfTypedValue();
  13774. }
  13775. }
  13776. else
  13777. {
  13778. //TODO: Do we allow useMethodState to be NULL anymore?
  13779. return BfTypedValue();
  13780. }
  13781. // Check mixin state for 'this'
  13782. {
  13783. auto checkMethodState = mCurMethodState;
  13784. while (checkMethodState != NULL)
  13785. {
  13786. if (checkMethodState->mMixinState != NULL)
  13787. {
  13788. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13789. if (thisValue.HasType())
  13790. {
  13791. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13792. if (!thisValue.mType->IsValueType())
  13793. thisValue = LoadValue(thisValue);
  13794. return thisValue;
  13795. }
  13796. }
  13797. checkMethodState = checkMethodState->mPrevMethodState;
  13798. }
  13799. }
  13800. auto curMethodInstance = mCurMethodInstance;
  13801. if (useMethodState->mMethodInstance != NULL)
  13802. curMethodInstance = useMethodState->mMethodInstance;
  13803. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13804. {
  13805. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13806. {
  13807. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13808. if (constLocal.mIsThis)
  13809. {
  13810. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13811. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13812. }
  13813. }
  13814. return BfTypedValue();
  13815. }
  13816. if (useMethodState->mLocals.IsEmpty())
  13817. {
  13818. // 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
  13819. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13820. return BfTypedValue();
  13821. }
  13822. auto thisLocal = useMethodState->mLocals[0];
  13823. BF_ASSERT(thisLocal->mIsThis);
  13824. bool preferValue = !IsTargetingBeefBackend();
  13825. if (!thisLocal->mAddr)
  13826. preferValue = true;
  13827. bool usedVal = false;
  13828. BfIRValue thisValue;
  13829. if ((preferValue) && (!thisLocal->mIsLowered))
  13830. {
  13831. thisValue = thisLocal->mValue;
  13832. usedVal = true;
  13833. }
  13834. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13835. thisValue = thisLocal->mAddr;
  13836. else
  13837. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13838. if (markUsing)
  13839. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13840. if (useMethodState->mClosureState != NULL)
  13841. {
  13842. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13843. if (closureTypeInst != NULL)
  13844. {
  13845. if (closureTypeInst->mFieldInstances.size() > 0)
  13846. {
  13847. auto& field = closureTypeInst->mFieldInstances[0];
  13848. auto fieldDef = field.GetFieldDef();
  13849. if (fieldDef->mName == "__this")
  13850. {
  13851. if (mCurMethodState->mClosureState->mCapturing)
  13852. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13853. // This is a captured 'this'
  13854. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13855. if (field.mResolvedType->IsRef())
  13856. {
  13857. auto refType = (BfRefType*)field.mResolvedType;
  13858. auto underlyingType = refType->GetUnderlyingType();
  13859. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13860. }
  13861. if (field.mResolvedType->IsObject())
  13862. {
  13863. result = LoadValue(result);
  13864. result.mKind = BfTypedValueKind_ThisValue;
  13865. }
  13866. else
  13867. {
  13868. if (fieldDef->mIsReadOnly)
  13869. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13870. else
  13871. result.mKind = BfTypedValueKind_ThisAddr;
  13872. }
  13873. return result;
  13874. }
  13875. }
  13876. return BfTypedValue();
  13877. }
  13878. if (useMethodState->mClosureState->mCapturing)
  13879. {
  13880. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13881. if (thisType->IsValueType())
  13882. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13883. else
  13884. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13885. }
  13886. }
  13887. if (mCurMethodInstance == NULL)
  13888. return BfTypedValue();
  13889. auto localDef = useMethodState->mLocals[0];
  13890. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13891. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13892. {
  13893. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating) && (!mCurMethodInstance->ForcingThisPtr()))
  13894. {
  13895. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13896. }
  13897. if (localDef->mIsSplat)
  13898. {
  13899. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13900. }
  13901. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13902. }
  13903. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13904. }
  13905. BfLocalVariable* BfModule::GetThisVariable()
  13906. {
  13907. if (mCurMethodState == NULL)
  13908. return NULL;
  13909. auto methodState = mCurMethodState->GetNonCaptureState();
  13910. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13911. return methodState->mLocals[0];
  13912. return NULL;
  13913. }
  13914. bool BfModule::IsInGeneric()
  13915. {
  13916. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13917. }
  13918. bool BfModule::InDefinitionSection()
  13919. {
  13920. if (mCurTypeInstance != NULL)
  13921. {
  13922. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13923. return false;
  13924. }
  13925. return !IsInSpecializedSection();
  13926. }
  13927. bool BfModule::IsInSpecializedGeneric()
  13928. {
  13929. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13930. return true;
  13931. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13932. return false;
  13933. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13934. }
  13935. bool BfModule::IsInSpecializedSection()
  13936. {
  13937. return IsInSpecializedGeneric() ||
  13938. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13939. }
  13940. bool BfModule::IsInUnspecializedGeneric()
  13941. {
  13942. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13943. return true;
  13944. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13945. return true;
  13946. return false;
  13947. }
  13948. //////////////////////////////////////////////////////////////////////////
  13949. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13950. {
  13951. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13952. if (type->IsValuelessType())
  13953. return mBfIRBuilder->GetFakeVal();
  13954. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13955. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13956. {
  13957. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13958. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13959. }
  13960. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13961. auto typeOptions = GetTypeOptions();
  13962. if (typeOptions != NULL)
  13963. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13964. // Local variable inits are implicitly handled in the Beef Backend
  13965. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13966. {
  13967. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13968. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13969. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13970. mBfIRBuilder->ClearDebugLocation(storeInst);
  13971. mBfIRBuilder->SetInsertPoint(prevBlock);
  13972. }
  13973. return allocaInst;
  13974. }
  13975. BfTypedValue BfModule::CreateOutVariable(BfAstNode* refNode, BfVariableDeclaration* variableDeclaration, BfAstNode* paramNameNode, BfType* variableType, BfTypedValue initValue)
  13976. {
  13977. bool isRef = false;
  13978. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  13979. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  13980. if (variableDeclaration != NULL)
  13981. {
  13982. if (auto varRefTypeReference = BfNodeDynCast<BfVarRefTypeReference>(variableDeclaration->mTypeRef))
  13983. {
  13984. isRef = true;
  13985. isLet = varRefTypeReference->mVarToken->GetToken() == BfToken_Let;
  13986. isVar = varRefTypeReference->mVarToken->GetToken() == BfToken_Var;
  13987. }
  13988. }
  13989. BfLocalVariable* localVar = new BfLocalVariable();
  13990. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  13991. {
  13992. localVar->mName = variableDeclaration->mNameNode->ToString();
  13993. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  13994. }
  13995. else
  13996. {
  13997. if (paramNameNode != NULL)
  13998. {
  13999. localVar->mName = "__";
  14000. paramNameNode->ToString(localVar->mName);
  14001. localVar->mName += "_";
  14002. localVar->mName += StrFormat("%d", mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  14003. }
  14004. else
  14005. localVar->mName = "__" + StrFormat("%d", mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  14006. }
  14007. localVar->mResolvedType = variableType;
  14008. if (isRef)
  14009. {
  14010. localVar->mResolvedType = CreateRefType(localVar->mResolvedType);
  14011. }
  14012. PopulateType(variableType);
  14013. if (!variableType->IsValuelessType())
  14014. localVar->mAddr = CreateAlloca(localVar->mResolvedType);
  14015. localVar->mIsReadOnly = isLet;
  14016. localVar->mReadFromId = 0;
  14017. localVar->mWrittenToId = 0;
  14018. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14019. CheckVariableDef(localVar);
  14020. localVar->Init();
  14021. AddLocalVariableDef(localVar, true);
  14022. BfExprEvaluator exprEvaluator(this);
  14023. exprEvaluator.CheckVariableDeclaration(refNode, false, false, false);
  14024. auto argValue = BfTypedValue(localVar->mAddr, CreateRefType(variableType, BfRefType::RefKind_Out));
  14025. if (isRef)
  14026. {
  14027. initValue = MakeAddressable(initValue, true, true);
  14028. if ((initValue) && (!initValue.mType->IsValuelessType()))
  14029. mBfIRBuilder->CreateStore(initValue.mValue, localVar->mAddr);
  14030. }
  14031. else
  14032. {
  14033. initValue = LoadOrAggregateValue(initValue);
  14034. if ((initValue) && (!initValue.mType->IsValuelessType()))
  14035. mBfIRBuilder->CreateStore(initValue.mValue, localVar->mAddr);
  14036. }
  14037. auto curScope = mCurMethodState->mCurScope;
  14038. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  14039. MoveLocalToParentScope(localVar);
  14040. return argValue;
  14041. }
  14042. void BfModule::MoveLocalToParentScope(BfLocalVariable* localVar)
  14043. {
  14044. auto curScope = mCurMethodState->mCurScope;
  14045. if (mCurMethodState->mLocals.back() != localVar)
  14046. return;
  14047. curScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  14048. if ((!curScope->mDeferredLifetimeEnds.IsEmpty()) && (curScope->mDeferredLifetimeEnds.back() == localVar->mAddr))
  14049. {
  14050. curScope->mDeferredLifetimeEnds.pop_back();
  14051. if (curScope->mPrevScope != NULL)
  14052. curScope->mPrevScope->mDeferredLifetimeEnds.push_back(localVar->mAddr);
  14053. }
  14054. }
  14055. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  14056. {
  14057. BF_ASSERT(localVar->mResolvedType != NULL);
  14058. while (localVar->mName.StartsWith('@'))
  14059. {
  14060. localVar->mNamePrefixCount++;
  14061. localVar->mName.Remove(0);
  14062. }
  14063. if (mCurMethodState->mLocals.mAllocSize == 0)
  14064. {
  14065. mCurMethodState->mLocals.Reserve(16);
  14066. mCurMethodState->mLocalVarSet.Reserve(16);
  14067. }
  14068. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  14069. mCurMethodState->mLocals.push_back(localVar);
  14070. BfLocalVarEntry* localVarEntryPtr;
  14071. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  14072. {
  14073. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  14074. localVarEntryPtr->mLocalVar = localVar;
  14075. }
  14076. }
  14077. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  14078. {
  14079. if (localVarDef->mResolvedType->IsVar())
  14080. return;
  14081. if ((mBfIRBuilder->DbgHasInfo()) &&
  14082. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  14083. (mHasFullDebugInfo) &&
  14084. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  14085. {
  14086. auto varType = localVarDef->mResolvedType;
  14087. if (localVarDef->mResolvedType->IsValuelessType())
  14088. {
  14089. }
  14090. else
  14091. {
  14092. bool isByAddr = false;
  14093. auto diValue = localVarDef->mValue;
  14094. if (localVarDef->mConstValue)
  14095. diValue = localVarDef->mConstValue;
  14096. else if (localVarDef->mAddr)
  14097. {
  14098. diValue = localVarDef->mAddr;
  14099. isByAddr = true;
  14100. }
  14101. if (diValue.IsConst())
  14102. {
  14103. auto constant = mBfIRBuilder->GetConstant(diValue);
  14104. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  14105. {
  14106. // Ignore for now
  14107. return;
  14108. }
  14109. }
  14110. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  14111. bool didConstToMem = false;
  14112. bool isConstant = false;
  14113. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  14114. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14115. else if (localVarDef->mConstValue)
  14116. {
  14117. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  14118. isConstant =
  14119. (constant->mConstType < BfConstType_GlobalVar) ||
  14120. (constant->mConstType == BfConstType_AggZero) ||
  14121. (constant->mConstType == BfConstType_Agg);
  14122. if (isConstant)
  14123. {
  14124. if (localVarDef->mResolvedType->IsComposite())
  14125. {
  14126. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  14127. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  14128. // if (IsTargetingBeefBackend())
  14129. // {
  14130. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  14131. // didConstToMem = true;
  14132. //
  14133. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14134. // }
  14135. //else
  14136. {
  14137. isByAddr = true;
  14138. mBfIRBuilder->SaveDebugLocation();
  14139. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14140. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  14141. mBfIRBuilder->ClearDebugLocation();
  14142. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  14143. auto addrVal = CreateAlloca(ptrType);
  14144. mBfIRBuilder->CreateStore(constMem, addrVal);
  14145. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14146. diValue = addrVal;
  14147. didConstToMem = true;
  14148. mBfIRBuilder->SetInsertPoint(prevBlock);
  14149. mBfIRBuilder->RestoreDebugLocation();
  14150. }
  14151. }
  14152. if (mCompiler->mOptions.IsCodeView())
  14153. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14154. }
  14155. }
  14156. if (!mBfIRBuilder->mIgnoreWrites)
  14157. {
  14158. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  14159. {
  14160. auto refType = CreateRefType(localVarDef->mResolvedType);
  14161. diType = mBfIRBuilder->DbgGetType(refType);
  14162. auto refAlloca = CreateAlloca(refType);
  14163. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  14164. diValue = refAlloca;
  14165. }
  14166. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14167. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  14168. localVarDef->mDbgVarInst = diVariable;
  14169. if (mBfIRBuilder->HasDebugLocation())
  14170. {
  14171. if ((isConstant) && (!didConstToMem))
  14172. {
  14173. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  14174. FixValueActualization(result);
  14175. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  14176. }
  14177. else
  14178. {
  14179. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  14180. {
  14181. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  14182. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  14183. }
  14184. if (isByAddr)
  14185. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  14186. else if (diValue)
  14187. {
  14188. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  14189. }
  14190. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  14191. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14192. }
  14193. }
  14194. }
  14195. }
  14196. }
  14197. }
  14198. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  14199. {
  14200. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  14201. {
  14202. if ((!localVarDef->mValue.IsConst()) &&
  14203. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  14204. {
  14205. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  14206. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  14207. }
  14208. }
  14209. if (addDebugInfo)
  14210. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  14211. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  14212. DoAddLocalVariable(localVarDef);
  14213. auto rootMethodState = mCurMethodState->GetRootMethodState();
  14214. if (localVarDef->mLocalVarId == -1)
  14215. {
  14216. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  14217. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  14218. }
  14219. bool checkLocal = true;
  14220. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  14221. {
  14222. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  14223. checkLocal = false;
  14224. }
  14225. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  14226. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  14227. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  14228. {
  14229. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  14230. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  14231. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  14232. }
  14233. return localVarDef;
  14234. }
  14235. void BfModule::CreateDIRetVal()
  14236. {
  14237. if (!WantsDebugInfo())
  14238. return;
  14239. /*if (!mCurMethodState->mRetVal)
  14240. {
  14241. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  14242. return;
  14243. }*/
  14244. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  14245. {
  14246. BfType* dbgType = mCurMethodInstance->mReturnType;
  14247. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  14248. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14249. {
  14250. BF_ASSERT(mCurMethodState->mRetValAddr);
  14251. dbgType = CreatePointerType(dbgType);
  14252. dbgValue = mCurMethodState->mRetValAddr;
  14253. }
  14254. else
  14255. {
  14256. BF_ASSERT(!mCurMethodState->mRetValAddr);
  14257. }
  14258. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14259. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  14260. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  14261. }
  14262. }
  14263. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  14264. {
  14265. BfTypeVector fieldTypes;
  14266. for (auto arg : values)
  14267. fieldTypes.Add(arg.mType);
  14268. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  14269. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  14270. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  14271. {
  14272. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  14273. if (fieldInstance.mDataIdx <= 0)
  14274. continue;
  14275. auto typedVal = values[fieldIdx];
  14276. typedVal = LoadOrAggregateValue(typedVal);
  14277. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  14278. }
  14279. return tupleTypedValue;
  14280. }
  14281. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  14282. {
  14283. if (variableDef->mName.IsEmpty())
  14284. return;
  14285. BfLocalVarEntry* localVarEntryPtr = NULL;
  14286. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  14287. {
  14288. auto checkLocal = localVarEntryPtr->mLocalVar;
  14289. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  14290. {
  14291. auto _Fail = [&](int warningNum, String str, BfAstNode* refNode)
  14292. {
  14293. BfError* error = Warn(warningNum, str, refNode);
  14294. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  14295. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  14296. };
  14297. auto checkScope = mCurMethodState->mCurScope;
  14298. if (checkScope->mScopeKind == BfScopeKind_StatementTarget)
  14299. checkScope = checkScope->mPrevScope;
  14300. if (checkLocal->mIsImplicitParam)
  14301. return; // Ignore 'redefinition'
  14302. if (checkLocal->IsParam())
  14303. {
  14304. if (variableDef->IsParam())
  14305. _Fail(4200, StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  14306. else
  14307. _Fail(4200, StrFormat("The name '%s' is already used by a parameter. Consider declaring 'var %s;' if you wish to make a mutable copy of that parameter.", variableDef->mName.c_str(), variableDef->mName.c_str()), variableDef->mNameNode);
  14308. }
  14309. else if (checkLocal->mLocalVarIdx < checkScope->mLocalVarStart)
  14310. _Fail(4200, StrFormat("A variable named '%s' has already been declared in an outer scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14311. else
  14312. _Fail(4200, StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  14313. return;
  14314. }
  14315. }
  14316. }
  14317. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  14318. {
  14319. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  14320. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  14321. {
  14322. if (tokenNode->GetToken() == BfToken_Colon)
  14323. {
  14324. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  14325. {
  14326. Fail("Cannot access method scope across deferred block boundary", scopeName);
  14327. return NULL;
  14328. }
  14329. return &mCurMethodState->mHeadScope;
  14330. }
  14331. else if (tokenNode->GetToken() == BfToken_Mixin)
  14332. {
  14333. if (fromMixinState == NULL)
  14334. {
  14335. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  14336. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  14337. return mCurMethodState->mCurScope;
  14338. }
  14339. fromMixinState->mUsedInvocationScope = true;
  14340. return fromMixinState->mTargetScope;
  14341. }
  14342. else if (tokenNode->GetToken() == BfToken_New)
  14343. return NULL;
  14344. }
  14345. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  14346. {
  14347. auto findLabel = scopeName->ToString();
  14348. bool crossedDeferredBlock = false;
  14349. auto checkScope = mCurMethodState->mCurScope;
  14350. while (checkScope != NULL)
  14351. {
  14352. if (checkScope->mIsDeferredBlock)
  14353. crossedDeferredBlock = true;
  14354. if (checkScope->mLabel == findLabel)
  14355. {
  14356. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  14357. {
  14358. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  14359. return NULL;
  14360. }
  14361. return checkScope;
  14362. }
  14363. checkScope = checkScope->mPrevScope;
  14364. }
  14365. if (!inMixinDecl)
  14366. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  14367. return NULL;
  14368. }
  14369. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  14370. {
  14371. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  14372. }
  14373. return mCurMethodState->mCurScope;
  14374. }
  14375. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  14376. {
  14377. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  14378. }
  14379. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  14380. {
  14381. auto scopeData = FindScope(scopeName, false);
  14382. if (scopeData == NULL)
  14383. return NULL;
  14384. int scopeDepth = scopeData->GetDepth();
  14385. // Find the first break data that is at or below the depth of our requested scope
  14386. auto breakData = mCurMethodState->mBreakData;
  14387. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  14388. {
  14389. if (breakData->mScope->mIsConditional)
  14390. return NULL;
  14391. breakData = breakData->mPrevBreakData;
  14392. }
  14393. return breakData;
  14394. }
  14395. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  14396. {
  14397. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  14398. if (!IsTargetingBeefBackend())
  14399. return;
  14400. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  14401. {
  14402. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14403. }
  14404. }
  14405. void BfModule::ClearLifetimeEnds()
  14406. {
  14407. auto scopeData = mCurMethodState->mCurScope;
  14408. while (scopeData != NULL)
  14409. {
  14410. scopeData->mDeferredLifetimeEnds.Clear();
  14411. scopeData = scopeData->mPrevScope;
  14412. }
  14413. }
  14414. bool BfModule::WantsDebugInfo()
  14415. {
  14416. if ((mCurMethodInstance != NULL) &&
  14417. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  14418. return false;
  14419. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  14420. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  14421. }
  14422. BfTypeOptions* BfModule::GetTypeOptions()
  14423. {
  14424. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  14425. return mCurMethodState->mMethodTypeOptions;
  14426. if (mCurMethodInstance == NULL)
  14427. return NULL;
  14428. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  14429. }
  14430. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  14431. {
  14432. BfReflectKind reflectKind = BfReflectKind_None;
  14433. if (attrType->mCustomAttributes != NULL)
  14434. {
  14435. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  14436. {
  14437. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  14438. {
  14439. for (auto& prop : customAttr.mSetProperties)
  14440. {
  14441. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14442. if (propDef->mName == "ReflectUser")
  14443. {
  14444. if (prop.mParam.mValue.IsConst())
  14445. {
  14446. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  14447. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14448. }
  14449. }
  14450. }
  14451. // Check for Flags arg
  14452. if (customAttr.mCtorArgs.size() < 2)
  14453. continue;
  14454. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  14455. if (constant == NULL)
  14456. continue;
  14457. if (constant->mTypeCode == BfTypeCode_Boolean)
  14458. continue;
  14459. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  14460. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  14461. }
  14462. }
  14463. }
  14464. return reflectKind;
  14465. }
  14466. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  14467. {
  14468. auto checkTypeInstance = typeInstance;
  14469. while (checkTypeInstance != NULL)
  14470. {
  14471. if (checkTypeInstance->mCustomAttributes != NULL)
  14472. {
  14473. auto checkReflectKind = BfReflectKind_None;
  14474. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  14475. {
  14476. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  14477. {
  14478. if (customAttr.mCtorArgs.size() > 0)
  14479. {
  14480. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  14481. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  14482. }
  14483. else
  14484. {
  14485. checkReflectKind = BfReflectKind_All;
  14486. }
  14487. }
  14488. else
  14489. {
  14490. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  14491. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  14492. }
  14493. }
  14494. if ((checkTypeInstance == typeInstance) ||
  14495. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  14496. {
  14497. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  14498. }
  14499. }
  14500. for (auto ifaceEntry : typeInstance->mInterfaces)
  14501. {
  14502. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  14503. {
  14504. auto iface = ifaceEntry.mInterfaceType;
  14505. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  14506. if (customAttr != NULL)
  14507. {
  14508. for (auto& prop : customAttr->mSetProperties)
  14509. {
  14510. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  14511. if (propDef->mName == "ReflectImplementer")
  14512. {
  14513. if (prop.mParam.mValue.IsConst())
  14514. {
  14515. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  14516. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  14517. }
  14518. }
  14519. }
  14520. }
  14521. }
  14522. }
  14523. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  14524. }
  14525. return reflectKind;
  14526. }
  14527. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  14528. {
  14529. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14530. while (checkScope != NULL)
  14531. {
  14532. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  14533. return true;
  14534. if (checkScope == scope)
  14535. break;
  14536. checkScope = checkScope->mPrevScope;
  14537. }
  14538. return false;
  14539. }
  14540. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  14541. {
  14542. // Is there anything we need to do here?
  14543. if (mBfIRBuilder->mIgnoreWrites)
  14544. {
  14545. // Just visit deferred blocks
  14546. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14547. while (checkScope != NULL)
  14548. {
  14549. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14550. while (deferredCallEntry != NULL)
  14551. {
  14552. if (deferredCallEntry->mDeferredBlock != NULL)
  14553. {
  14554. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14555. if (checkScope == &mCurMethodState->mHeadScope)
  14556. CreateRetValLocal();
  14557. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  14558. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  14559. }
  14560. deferredCallEntry = deferredCallEntry->mNext;
  14561. }
  14562. if (checkScope == scopeData)
  14563. break;
  14564. checkScope = checkScope->mPrevScope;
  14565. }
  14566. return;
  14567. }
  14568. // Why did we want to do SetIllegalSrcPos here?
  14569. // Don't we always want to step onto these instances?
  14570. // Find a case where we don't and perhaps only do it there.
  14571. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  14572. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  14573. //SetIllegalSrcPos();
  14574. bool setSrcPos = false;
  14575. bool wantsNop = true;
  14576. BfAstNode* deferCloseNode = NULL;
  14577. if (mCurMethodState->mInPostReturn)
  14578. {
  14579. // These won't get used, they are post-return
  14580. return;
  14581. }
  14582. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  14583. BfScopeData* scopeJumpBlock = NULL;
  14584. bool hadExtraDeferredLifetimeEnds = false;
  14585. auto _FlushLifetimeEnds = [&]()
  14586. {
  14587. for (auto lifetimeEnd : deferredLifetimeEnds)
  14588. {
  14589. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14590. mBfIRBuilder->ClearDebugLocation_Last();
  14591. }
  14592. deferredLifetimeEnds.clear();
  14593. };
  14594. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14595. while (checkScope != NULL)
  14596. {
  14597. if (checkScope->mCloseNode != NULL)
  14598. deferCloseNode = checkScope->mCloseNode;
  14599. if (doneBlock)
  14600. {
  14601. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  14602. for (auto& checkHandler : checkScope->mDeferredHandlers)
  14603. {
  14604. if (checkHandler.mDoneBlock == doneBlock)
  14605. {
  14606. scopeJumpBlock = checkScope;
  14607. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  14608. mBfIRBuilder->ClearDebugLocation_Last();
  14609. _FlushLifetimeEnds();
  14610. break;
  14611. }
  14612. }
  14613. if (scopeJumpBlock != NULL)
  14614. break;
  14615. }
  14616. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  14617. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  14618. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  14619. if (hasWork)
  14620. {
  14621. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  14622. if (deferCloseNode != NULL)
  14623. {
  14624. UpdateSrcPos(deferCloseNode);
  14625. }
  14626. if (checkScope == &mCurMethodState->mHeadScope)
  14627. CreateRetValLocal();
  14628. if (doneBlock)
  14629. {
  14630. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  14631. String blockName = "deferredCalls";
  14632. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  14633. BfDeferredHandler deferredHandler;
  14634. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  14635. {
  14636. mBfIRBuilder->SaveDebugLocation();
  14637. mBfIRBuilder->ClearDebugLocation();
  14638. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  14639. mBfIRBuilder->RestoreDebugLocation();
  14640. }
  14641. else
  14642. {
  14643. // Definitely chain
  14644. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  14645. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  14646. mBfIRBuilder->ClearDebugLocation_Last();
  14647. _FlushLifetimeEnds();
  14648. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  14649. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  14650. }
  14651. deferredHandler.mDoneBlock = doneBlock;
  14652. if (!mBfIRBuilder->mIgnoreWrites)
  14653. checkScope->mDeferredHandlers.push_back(deferredHandler);
  14654. if (checkScope == &mCurMethodState->mHeadScope)
  14655. {
  14656. if (!mCurMethodState->mDIRetVal)
  14657. {
  14658. // 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
  14659. // be scoped to the physical method
  14660. /*if (deferCloseNode != NULL)
  14661. {
  14662. UpdateSrcPos(deferCloseNode);
  14663. }*/
  14664. CreateDIRetVal();
  14665. }
  14666. }
  14667. if (checkScope != mCurMethodState->mTailScope)
  14668. {
  14669. if (deferredHandler.mHandlerBlock.IsFake())
  14670. {
  14671. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14672. }
  14673. if (!mBfIRBuilder->mIgnoreWrites)
  14674. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  14675. }
  14676. }
  14677. HashSet<BfDeferredCallEntry*> handledSet;
  14678. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14679. while (deferredCallEntry != NULL)
  14680. {
  14681. BfDeferredCallEmitState deferredCallEmitState;
  14682. deferredCallEmitState.mCloseNode = deferCloseNode;
  14683. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  14684. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  14685. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  14686. if (deferCloseNode != NULL)
  14687. {
  14688. UpdateSrcPos(deferCloseNode);
  14689. }
  14690. if (wantsNop)
  14691. EmitEnsureInstructionAt();
  14692. wantsNop = false;
  14693. if (deferredCallEntry->mDeferredBlock != NULL)
  14694. {
  14695. BfDeferredCallEntry** entryPtr = NULL;
  14696. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  14697. {
  14698. // Already handled, can happen if we defer again within the block
  14699. deferredCallEntry = deferredCallEntry->mNext;
  14700. continue;
  14701. }
  14702. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  14703. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14704. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  14705. {
  14706. // The list changed, start over and ignore anything we've already handled
  14707. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  14708. }
  14709. else
  14710. deferredCallEntry = deferredCallEntry->mNext;
  14711. }
  14712. else
  14713. {
  14714. EmitDeferredCall(checkScope, *deferredCallEntry, true);
  14715. deferredCallEntry = deferredCallEntry->mNext;
  14716. }
  14717. }
  14718. if (checkScope->mSavedStack)
  14719. {
  14720. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  14721. if (mCurMethodState->mDynStackRevIdx)
  14722. {
  14723. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  14724. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14725. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  14726. }
  14727. }
  14728. }
  14729. if (!checkScope->mIsScopeHead)
  14730. {
  14731. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  14732. if (!IsTargetingBeefBackend())
  14733. {
  14734. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14735. {
  14736. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14737. }
  14738. }
  14739. else
  14740. {
  14741. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14742. {
  14743. deferredLifetimeEnds.Add(lifetimeEnd);
  14744. }
  14745. }
  14746. }
  14747. if (checkScope == scopeData)
  14748. break;
  14749. checkScope = checkScope->mPrevScope;
  14750. }
  14751. if ((doneBlock) && (scopeJumpBlock == NULL))
  14752. {
  14753. mBfIRBuilder->CreateBr(doneBlock);
  14754. mBfIRBuilder->ClearDebugLocation_Last();
  14755. }
  14756. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  14757. // may have been created when other scope lifetimes were available
  14758. _FlushLifetimeEnds();
  14759. // Emit lifetimeEnds after the branch for Beef
  14760. /*if (IsTargetingBeefBackend())
  14761. {
  14762. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  14763. BfScopeData* checkScope = mCurMethodState->mCurScope;
  14764. while (checkScope != NULL)
  14765. {
  14766. if (checkScope == scopeJumpBlock)
  14767. break;
  14768. if (!checkScope->mIsScopeHead)
  14769. {
  14770. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  14771. {
  14772. if (needsEnsureInst)
  14773. {
  14774. needsEnsureInst = false;
  14775. }
  14776. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  14777. }
  14778. }
  14779. if (checkScope == scopeData)
  14780. break;
  14781. checkScope = checkScope->mPrevScope;
  14782. }
  14783. }*/
  14784. }
  14785. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  14786. {
  14787. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  14788. {
  14789. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  14790. while (deferredLocalAssignData != NULL)
  14791. {
  14792. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  14793. break;
  14794. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  14795. deferredLocalAssignData->mIsUnconditional = false;
  14796. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  14797. }
  14798. }
  14799. // When we leave a scope, mark those as assigned for deferred assignment purposes
  14800. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  14801. {
  14802. auto localDef = mCurMethodState->mLocals[localIdx];
  14803. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  14804. {
  14805. bool hadAssignment = false;
  14806. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  14807. {
  14808. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  14809. if (entry.mLocalVar == localDef)
  14810. hadAssignment = true;
  14811. }
  14812. if (!hadAssignment)
  14813. {
  14814. if (!isNoReturn)
  14815. localDef->mHadExitBeforeAssign = true;
  14816. mCurMethodState->LocalDefined(localDef);
  14817. }
  14818. }
  14819. }
  14820. }
  14821. void BfModule::CreateReturn(BfIRValue val)
  14822. {
  14823. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14824. {
  14825. // Store to sret
  14826. BF_ASSERT(val);
  14827. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14828. mBfIRBuilder->CreateRetVoid();
  14829. return;
  14830. }
  14831. if (mCurMethodInstance->mReturnType->IsVar())
  14832. return;
  14833. if (mCurMethodInstance->mReturnType->IsValuelessType())
  14834. {
  14835. mBfIRBuilder->CreateRetVoid();
  14836. return;
  14837. }
  14838. if (mCurMethodInstance->mReturnType->IsStruct())
  14839. {
  14840. BfTypeCode loweredReturnType = BfTypeCode_None;
  14841. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  14842. if (!mIsComptimeModule)
  14843. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14844. if (loweredReturnType != BfTypeCode_None)
  14845. {
  14846. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14847. mBfIRBuilder->CreateStore(val, retVal);
  14848. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14849. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14850. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14851. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14852. mBfIRBuilder->CreateRet(loadedReturnValue);
  14853. return;
  14854. }
  14855. }
  14856. BF_ASSERT(val);
  14857. mBfIRBuilder->CreateRet(val);
  14858. }
  14859. void BfModule::EmitReturn(const BfTypedValue& val)
  14860. {
  14861. if (mCurMethodState->mIRExitBlock)
  14862. {
  14863. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14864. {
  14865. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14866. {
  14867. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14868. {
  14869. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14870. if (!mCurMethodState->mRetVal)
  14871. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14872. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14873. }
  14874. else if (mIsComptimeModule)
  14875. {
  14876. if (!val.mType->IsValuelessType())
  14877. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14878. else
  14879. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14880. }
  14881. else
  14882. {
  14883. // Just ignore
  14884. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14885. }
  14886. }
  14887. }
  14888. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14889. }
  14890. else
  14891. {
  14892. EmitDeferredScopeCalls(false, NULL);
  14893. if (val)
  14894. {
  14895. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14896. }
  14897. }
  14898. mCurMethodState->SetHadReturn(true);
  14899. mCurMethodState->mLeftBlockUncond = true;
  14900. }
  14901. void BfModule::EmitDefaultReturn()
  14902. {
  14903. if (mCurMethodState->mInDeferredBlock)
  14904. return;
  14905. if (mCurMethodState->mIRExitBlock)
  14906. {
  14907. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14908. }
  14909. else
  14910. {
  14911. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14912. {
  14913. // Ignore
  14914. }
  14915. else if (mCurMethodInstance->mReturnType->IsVoid())
  14916. mBfIRBuilder->CreateRetVoid();
  14917. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14918. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14919. }
  14920. mCurMethodState->SetHadReturn(true);
  14921. mCurMethodState->mLeftBlockUncond = true;
  14922. }
  14923. void BfModule::AssertErrorState()
  14924. {
  14925. if (mIgnoreErrors)
  14926. return;
  14927. if (mHadBuildError)
  14928. return;
  14929. if (mCurTypeInstance != NULL)
  14930. {
  14931. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14932. return;
  14933. }
  14934. if (mCurMethodInstance != NULL)
  14935. {
  14936. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14937. return;
  14938. if (mCurMethodInstance->mHasFailed)
  14939. return;
  14940. }
  14941. // We want the module to be marked as failed even if it's just an error in the parser
  14942. if (mCurMethodInstance != NULL)
  14943. mCurMethodInstance->mHasFailed = true;
  14944. mHadBuildError = true;
  14945. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14946. if (mCurTypeInstance != NULL)
  14947. {
  14948. if (mCurTypeInstance->mTypeFailed)
  14949. return;
  14950. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14951. return;
  14952. }
  14953. if (mCurMethodInstance != NULL)
  14954. {
  14955. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14956. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14957. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14958. return;
  14959. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14960. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14961. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14962. return;
  14963. }
  14964. if (mCompiler->IsAutocomplete())
  14965. return;
  14966. if (mCompiler->mPassInstance->HasFailed())
  14967. return;
  14968. InternalError("Compiler in invalid state but AssertErrorState failed to detect prior error");
  14969. }
  14970. void BfModule::AssertParseErrorState()
  14971. {
  14972. if (mCompiler->mRevision == 1)
  14973. AssertErrorState();
  14974. }
  14975. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14976. {
  14977. BF_ASSERT(delegateType->IsDelegateOrFunction());
  14978. auto typeInst = delegateType->ToTypeInstance();
  14979. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14980. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14981. if (invokeMethodInstance == NULL)
  14982. return GetPrimitiveType(BfTypeCode_Var);
  14983. return invokeMethodInstance->mReturnType;
  14984. }
  14985. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14986. {
  14987. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14988. }
  14989. void BfModule::CreateDelegateInvokeMethod()
  14990. {
  14991. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14992. //mBfIRBuilder->ClearDebugLocation();
  14993. SetIllegalSrcPos();
  14994. auto typeInstance = mCurTypeInstance;
  14995. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14996. SizedArray<BfIRType, 4> staticParamTypes;
  14997. SizedArray<BfIRValue, 4> staticFuncArgs;
  14998. SizedArray<BfIRValue, 4> memberFuncArgs;
  14999. auto multicastDelegateType = typeInstance->mBaseType;
  15000. if (multicastDelegateType->mFieldInstances.size() != 2)
  15001. {
  15002. AssertErrorState();
  15003. return;
  15004. }
  15005. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  15006. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  15007. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  15008. BfExprEvaluator exprEvaluator(this);
  15009. SizedArray<BfIRType, 8> origParamTypes;
  15010. BfIRType origReturnType;
  15011. BfIRType staticReturnType;
  15012. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  15013. if (mCurMethodInstance->mReturnType->IsValueType())
  15014. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  15015. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  15016. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  15017. int thisIdx = 0;
  15018. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  15019. {
  15020. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  15021. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  15022. }
  15023. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  15024. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  15025. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  15026. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  15027. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  15028. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  15029. {
  15030. if (mCurMethodState->mLocals[i]->mCompositeCount >= 0)
  15031. continue;
  15032. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  15033. exprEvaluator.PushArg(localVal, staticFuncArgs);
  15034. exprEvaluator.PushArg(localVal, memberFuncArgs);
  15035. }
  15036. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  15037. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  15038. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  15039. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  15040. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  15041. auto doneBB = mBfIRBuilder->CreateBlock("done");
  15042. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  15043. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  15044. BfIRValue nonStaticResult;
  15045. BfIRValue staticResult;
  15046. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  15047. auto trueEndBB = trueBB;
  15048. /// Non-static invocation
  15049. {
  15050. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15051. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  15052. mBfIRBuilder->SetInsertPoint(trueBB);
  15053. BfIRValue numVal;
  15054. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule) && (mCompiler->mSystem->mPtrSize == 8))
  15055. {
  15056. numVal = mBfIRBuilder->CreatePtrToInt(fieldVal, BfTypeCode_UInt64);
  15057. auto andVal = mBfIRBuilder->CreateAnd(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)~0x8000000000000000ULL));
  15058. fieldVal = mBfIRBuilder->CreateIntToPtr(andVal, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15059. }
  15060. if ((WantsObjectAccessCheck(mContext->mBfObjectType) && (mCompiler->mSystem->mPtrSize == 8)))
  15061. {
  15062. auto oacDoBB = mBfIRBuilder->CreateBlock("oac.do", true);
  15063. auto oacDoneBB = mBfIRBuilder->CreateBlock("oac.done");
  15064. auto checkGTE = mBfIRBuilder->CreateCmpGTE(numVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL), false);
  15065. mBfIRBuilder->CreateCondBr(checkGTE, oacDoBB, oacDoneBB);
  15066. mBfIRBuilder->SetInsertPoint(oacDoBB);
  15067. mBfIRBuilder->CreateObjectAccessCheck(fieldVal, !IsOptimized());
  15068. mBfIRBuilder->CreateBr(oacDoneBB);
  15069. mBfIRBuilder->AddBlock(oacDoneBB);
  15070. mBfIRBuilder->SetInsertPoint(oacDoneBB);
  15071. trueEndBB = oacDoneBB;
  15072. }
  15073. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  15074. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  15075. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  15076. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  15077. BfExprEvaluator exprEvaluator(this);
  15078. BfTypedValue nonStaticTypedResult = exprEvaluator.CreateCall(NULL, mCurMethodInstance, funcPtr, true, memberFuncArgs, NULL, BfCreateCallFlags_DelegateThunkNonStatic);
  15079. nonStaticResult = nonStaticTypedResult.mValue;
  15080. mCurMethodState->SetHadReturn(false);
  15081. mCurMethodState->mLeftBlockUncond = false;
  15082. mCurMethodState->mLeftBlockCond = false;
  15083. mBfIRBuilder->CreateBr(doneBB);
  15084. }
  15085. // Static invocation
  15086. {
  15087. mBfIRBuilder->AddBlock(falseBB);
  15088. mBfIRBuilder->SetInsertPoint(falseBB);
  15089. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  15090. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  15091. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  15092. BfExprEvaluator exprEvaluator(this);
  15093. BfTypedValue staticTypedResult = exprEvaluator.CreateCall(NULL, mCurMethodInstance, funcPtr, true, staticFuncArgs, NULL, BfCreateCallFlags_DelegateThunkStatic);
  15094. staticResult = staticTypedResult.mValue;
  15095. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  15096. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  15097. {
  15098. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  15099. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  15100. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  15101. }
  15102. mCurMethodState->SetHadReturn(false);
  15103. mCurMethodState->mLeftBlockUncond = false;
  15104. mCurMethodState->mLeftBlockCond = false;
  15105. mBfIRBuilder->CreateBr(doneBB);
  15106. }
  15107. mBfIRBuilder->AddBlock(doneBB);
  15108. mBfIRBuilder->SetInsertPoint(doneBB);
  15109. if (mCurMethodInstance->mReturnType->IsVar())
  15110. {
  15111. // Do nothing
  15112. }
  15113. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  15114. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  15115. {
  15116. mBfIRBuilder->CreateRetVoid();
  15117. }
  15118. else
  15119. {
  15120. BfIRType loweredIRReturnType;
  15121. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15122. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15123. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)) && (loweredTypeCode != BfTypeCode_None))
  15124. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  15125. else
  15126. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  15127. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  15128. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueEndBB);
  15129. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  15130. mBfIRBuilder->CreateRet(phi);
  15131. }
  15132. }
  15133. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  15134. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  15135. {
  15136. auto typeDef = typeInstance->mTypeDef;
  15137. auto methodDeclaration = methodDef->mMethodDeclaration;
  15138. if (!mCompiler->mIsResolveOnly)
  15139. return true;
  15140. if (typeInstance->IsGenericTypeInstance())
  15141. {
  15142. // We only really want to process the unspecialized type for autocompletion
  15143. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  15144. return false;
  15145. }
  15146. BfAstNode* checkNode = methodDeclaration;
  15147. if (methodDeclaration == NULL)
  15148. checkNode = methodDef->mBody;
  15149. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  15150. {
  15151. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  15152. return true;
  15153. }
  15154. return false;
  15155. }
  15156. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  15157. {
  15158. methodInst->mAppendAllocAlign = 1;
  15159. }
  15160. BfAllowAppendKind BfModule::GetBaseAllowAppend(BfMethodInstance* curMethodInstance)
  15161. {
  15162. auto typeInstance = curMethodInstance->GetOwner();
  15163. auto methodDef = curMethodInstance->mMethodDef;
  15164. if (methodDef->mAppendKind == BfAllowAppendKind_No)
  15165. return BfAllowAppendKind_No;
  15166. if ((typeInstance->mInstSize == typeInstance->mBaseType->mInstSize) &&
  15167. (typeInstance->IsZeroGap()) &&
  15168. (typeInstance->mBaseType->IsZeroGap()) &&
  15169. (methodDef->mAppendKind == BfAllowAppendKind_ZeroGap))
  15170. {
  15171. return BfAllowAppendKind_ZeroGap;
  15172. }
  15173. return BfAllowAppendKind_Yes;
  15174. }
  15175. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  15176. {
  15177. BP_ZONE("BfModule::TryConstCalcAppend");
  15178. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  15179. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  15180. return BfTypedValue();
  15181. // We want to regenerate all ctor calls when the method internals change
  15182. {
  15183. auto checkTypeInst = methodInst->GetOwner();
  15184. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  15185. {
  15186. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15187. checkTypeInst = GetBaseType(checkTypeInst);
  15188. }
  15189. }
  15190. if (!methodInst->mMayBeConst)
  15191. return BfTypedValue();
  15192. // Do we need to iterate in order to resolve mAppendAllocAlign?
  15193. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  15194. bool wasAllConst = true;
  15195. int argIdx = 0;
  15196. int paramIdx = 0;
  15197. while (true)
  15198. {
  15199. if (argIdx >= (int)args.size())
  15200. break;
  15201. auto paramType = methodInst->GetParamType(paramIdx);
  15202. PopulateType(paramType);
  15203. int argCount = 0;
  15204. if (!paramType->IsValuelessType())
  15205. {
  15206. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  15207. argCount = paramType->GetSplatCount();
  15208. else
  15209. argCount = 1;
  15210. for (int argOfs = 0; argOfs < argCount; argOfs++)
  15211. {
  15212. auto arg = args[argIdx + argOfs];
  15213. if (!arg.IsConst())
  15214. {
  15215. wasAllConst = false;
  15216. if (!isFirstRun)
  15217. {
  15218. auto& param = methodInst->mParams[argIdx];
  15219. if (param.mReferencedInConstPass)
  15220. {
  15221. // If this param is required as part of the const calculation then
  15222. // we require that it be const...
  15223. return BfTypedValue();
  15224. }
  15225. }
  15226. }
  15227. }
  15228. }
  15229. paramIdx++;
  15230. argIdx += argCount;
  15231. }
  15232. auto methodDef = methodInst->mMethodDef;
  15233. auto methodDecl = methodDef->GetMethodDeclaration();
  15234. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15235. if (methodDeclBlock == NULL)
  15236. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  15237. BfTypedValue constValue;
  15238. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  15239. auto checkState = mCurMethodState->mConstResolveState;
  15240. while (checkState != NULL)
  15241. {
  15242. if (checkState->mMethodInstance == methodInst)
  15243. {
  15244. return BfTypedValue();
  15245. }
  15246. checkState = checkState->mPrevConstResolveState;
  15247. }
  15248. //auto accumValue = GetConstValue(0);
  15249. bool failed = false;
  15250. //
  15251. {
  15252. BfConstResolveState constResolveState;
  15253. constResolveState.mMethodInstance = methodInst;
  15254. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  15255. constResolveState.mInCalcAppend = true;
  15256. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15257. BfMethodState methodState;
  15258. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  15259. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  15260. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15261. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  15262. methodState.mConstResolveState = &constResolveState;
  15263. int argIdx = 0;
  15264. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15265. {
  15266. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  15267. continue;
  15268. auto paramType = methodInst->GetParamType(paramIdx);
  15269. // Fix this after we allow structs to be consts
  15270. //BF_ASSERT(!paramType->IsSplattable());
  15271. BfLocalVariable* localVar = new BfLocalVariable();
  15272. localVar->mName = methodInst->GetParamName(paramIdx);
  15273. localVar->mResolvedType = paramType;
  15274. localVar->mConstValue = args[argIdx];
  15275. localVar->mParamIdx = paramIdx;
  15276. AddLocalVariableDef(localVar);
  15277. argIdx++;
  15278. }
  15279. AppendAllocVisitor appendAllocVisitor;
  15280. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15281. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  15282. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  15283. if (baseCtorAppendValue)
  15284. {
  15285. if (baseCtorAppendValue.mValue.IsFake())
  15286. appendAllocVisitor.mFailed = true;
  15287. else
  15288. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  15289. }
  15290. appendAllocVisitor.mModule = this;
  15291. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15292. if (constResolveState.mFailed)
  15293. appendAllocVisitor.mFailed = true;
  15294. if (!appendAllocVisitor.mFailed)
  15295. constValue = appendAllocVisitor.mConstAccum;
  15296. if (appendAllocVisitor.mHasAppendWantMark)
  15297. methodInst->mHasAppendWantMark = true;
  15298. if (isFirstRun)
  15299. {
  15300. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  15301. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  15302. mCurMethodInstance->mAppendAllocAlign = 1;
  15303. }
  15304. if (isFirstRun)
  15305. {
  15306. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  15307. {
  15308. auto localVar = mCurMethodState->mLocals[paramIdx];
  15309. if (localVar->mReadFromId != -1)
  15310. {
  15311. auto& param = methodInst->mParams[paramIdx];
  15312. param.mReferencedInConstPass = true;
  15313. }
  15314. }
  15315. }
  15316. }
  15317. mBfIRBuilder->SetInsertPoint(prevBlock);
  15318. if (!constValue)
  15319. {
  15320. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  15321. // all-const args
  15322. if (wasAllConst)
  15323. {
  15324. methodInst->mMayBeConst = false;
  15325. }
  15326. }
  15327. return constValue;
  15328. }
  15329. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  15330. {
  15331. // Any errors should only be shown in the actual CTOR call
  15332. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  15333. auto methodDef = mCurMethodInstance->mMethodDef;
  15334. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  15335. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15336. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  15337. BfCustomAttributes* customAttributes = NULL;
  15338. defer(delete customAttributes);
  15339. BfInvocationExpression* ctorInvocation = NULL;
  15340. if (ctorDeclaration != NULL)
  15341. {
  15342. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15343. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15344. {
  15345. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15346. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  15347. }
  15348. }
  15349. BfTypeInstance* targetType = NULL;
  15350. if (ctorInvocation != NULL)
  15351. {
  15352. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15353. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15354. }
  15355. else
  15356. targetType = mCurTypeInstance->mBaseType;
  15357. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  15358. return NULL;
  15359. auto targetRefNode = methodDef->GetRefNode();
  15360. BfType* targetThisType = targetType;
  15361. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  15362. BfExprEvaluator exprEvaluator(this);
  15363. BfResolvedArgs argValues;
  15364. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15365. {
  15366. argValues.Init(&ctorInvocation->mArguments);
  15367. }
  15368. //
  15369. {
  15370. }
  15371. BfFunctionBindResult bindResult;
  15372. bindResult.mSkipThis = true;
  15373. bindResult.mWantsArgs = true;
  15374. {
  15375. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15376. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15377. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15378. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15379. }
  15380. if (bindResult.mMethodInstance == NULL)
  15381. {
  15382. AssertErrorState();
  15383. return BfTypedValue();
  15384. }
  15385. if (!bindResult.mMethodInstance->mMethodDef->HasAppend())
  15386. {
  15387. return BfTypedValue();
  15388. }
  15389. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15390. bindResult.mIRArgs.RemoveAt(0);
  15391. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  15392. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  15393. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  15394. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  15395. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  15396. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  15397. if (appendSizeTypedValue)
  15398. return appendSizeTypedValue;
  15399. if (constOnly)
  15400. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  15401. bool needsRecalc = false;
  15402. for (auto irArg : bindResult.mIRArgs)
  15403. {
  15404. if (irArg.IsFake())
  15405. needsRecalc = true;
  15406. }
  15407. auto calcAppendArgs = bindResult.mIRArgs;
  15408. if (needsRecalc)
  15409. {
  15410. // Do it again, but without mIgnoreWrites set
  15411. BfResolvedArgs argValues;
  15412. argValues.Init(&ctorInvocation->mArguments);
  15413. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15414. BfFunctionBindResult bindResult;
  15415. bindResult.mSkipThis = true;
  15416. bindResult.mWantsArgs = true;
  15417. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  15418. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, NULL);
  15419. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  15420. bindResult.mIRArgs.RemoveAt(0);
  15421. calcAppendArgs = bindResult.mIRArgs;
  15422. }
  15423. if (mBfIRBuilder->mIgnoreWrites)
  15424. {
  15425. appendSizeTypedValue = GetFakeTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  15426. }
  15427. else
  15428. {
  15429. BF_ASSERT(calcAppendMethodModule.mFunc);
  15430. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  15431. }
  15432. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  15433. return appendSizeTypedValue;
  15434. }
  15435. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  15436. void BfModule::EmitCtorCalcAppend()
  15437. {
  15438. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  15439. return;
  15440. auto methodDef = mCurMethodInstance->mMethodDef;
  15441. auto methodDecl = methodDef->GetMethodDeclaration();
  15442. Array<BfAstNode*> deferredNodeList;
  15443. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  15444. if (methodDeclBlock == NULL)
  15445. return;
  15446. AppendAllocVisitor appendAllocVisitor;
  15447. auto baseCalcAppend = CallBaseCtorCalc(false);
  15448. if (baseCalcAppend)
  15449. {
  15450. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  15451. }
  15452. appendAllocVisitor.mModule = this;
  15453. appendAllocVisitor.VisitChild(methodDecl->mBody);
  15454. }
  15455. void BfModule::CreateStaticCtor()
  15456. {
  15457. auto typeDef = mCurTypeInstance->mTypeDef;
  15458. auto methodDef = mCurMethodInstance->mMethodDef;
  15459. BfIRBlock exitBB;
  15460. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15461. {
  15462. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  15463. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  15464. mBfIRBuilder->MapType(boolType),
  15465. false,
  15466. BfIRLinkageType_Internal,
  15467. GetDefaultValue(boolType),
  15468. "didStaticInit");
  15469. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  15470. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15471. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  15472. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  15473. mBfIRBuilder->SetInsertPoint(initBB);
  15474. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  15475. }
  15476. // Do DLL imports
  15477. if (!mDllImportEntries.empty())
  15478. {
  15479. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  15480. PopulateType(internalType);
  15481. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  15482. if (!getSharedProcAddressInstance)
  15483. {
  15484. if (!mCompiler->mPassInstance->HasFailed())
  15485. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  15486. }
  15487. }
  15488. // Fill in initializer values
  15489. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15490. {
  15491. for (auto fieldDef : typeDef->mFields)
  15492. {
  15493. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic))
  15494. {
  15495. // For extensions, only handle these fields in the appropriate extension
  15496. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15497. continue;
  15498. auto initializer = fieldDef->GetInitializer();
  15499. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15500. if (!fieldInst->mFieldIncluded)
  15501. continue;
  15502. if (fieldInst->mResolvedType->IsVar())
  15503. {
  15504. continue;
  15505. }
  15506. if (fieldInst->IsAppendedObject())
  15507. {
  15508. AppendedObjectInit(fieldInst);
  15509. }
  15510. else if (initializer != NULL)
  15511. {
  15512. UpdateSrcPos(initializer);
  15513. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  15514. }
  15515. }
  15516. }
  15517. auto _CheckInitBlock = [&](BfAstNode* node)
  15518. {
  15519. };
  15520. EmitInitBlocks(_CheckInitBlock);
  15521. }
  15522. else
  15523. {
  15524. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15525. {
  15526. if (tempTypeDef->mFullName == typeDef->mFullName)
  15527. {
  15528. for (auto fieldDef : tempTypeDef->mFields)
  15529. {
  15530. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15531. {
  15532. if (fieldDef->GetInitializer() != NULL)
  15533. {
  15534. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  15535. {
  15536. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  15537. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  15538. }
  15539. BfType* wantType = NULL;
  15540. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15541. {
  15542. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15543. }
  15544. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15545. if (fieldDef->mIsAppend)
  15546. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15547. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  15548. }
  15549. }
  15550. }
  15551. }
  15552. }
  15553. }
  15554. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15555. CallChainedMethods(mCurMethodInstance, false);
  15556. }
  15557. void BfModule::EmitDtorBody()
  15558. {
  15559. if (!mCurMethodState->mIRExitBlock)
  15560. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15561. if (mCurTypeInstance->IsClosure())
  15562. {
  15563. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  15564. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  15565. auto thisVal = GetThis();
  15566. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  15567. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  15568. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  15569. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  15570. SizedArray<BfIRValue, 1> args;
  15571. args.push_back(thisVal.mValue);
  15572. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  15573. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15574. // Fall through to Object::~this call
  15575. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  15576. if (mIsComptimeModule)
  15577. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  15578. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  15579. SizedArray<BfIRValue, 1> vals = { basePtr };
  15580. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  15581. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  15582. mBfIRBuilder->SetTailCall(result);
  15583. return;
  15584. }
  15585. auto typeDef = mCurTypeInstance->mTypeDef;
  15586. auto methodDef = mCurMethodInstance->mMethodDef;
  15587. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15588. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15589. CallChainedMethods(mCurMethodInstance, true);
  15590. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15591. {
  15592. VisitEmbeddedStatement(bodyBlock);
  15593. if (bodyBlock->mCloseBrace != NULL)
  15594. {
  15595. UpdateSrcPos(bodyBlock->mCloseBrace);
  15596. }
  15597. }
  15598. else
  15599. {
  15600. if (methodDeclaration != NULL)
  15601. UpdateSrcPos(methodDeclaration);
  15602. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15603. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  15604. else if (typeDef->mTypeDeclaration != NULL)
  15605. UpdateSrcPos(typeDef->mTypeDeclaration);
  15606. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  15607. {
  15608. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  15609. }
  15610. }
  15611. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  15612. {
  15613. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  15614. {
  15615. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  15616. auto fieldDef = fieldInst->GetFieldDef();
  15617. BfFieldDeclaration* fieldDecl = NULL;
  15618. if (fieldDef != NULL)
  15619. fieldDecl = fieldDef->GetFieldDeclaration();
  15620. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  15621. {
  15622. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15623. {
  15624. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15625. continue;
  15626. }
  15627. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  15628. {
  15629. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  15630. }
  15631. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15632. auto fieldDtor = fieldDecl->mFieldDtor;
  15633. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  15634. continue;
  15635. UpdateSrcPos(fieldDtor);
  15636. BfScopeData scopeData;
  15637. mCurMethodState->AddScope(&scopeData);
  15638. NewScopeState();
  15639. UpdateSrcPos(fieldDtor);
  15640. bool hasDbgInfo = (!fieldDef->mIsConst);
  15641. if (hasDbgInfo)
  15642. {
  15643. mBfIRBuilder->SaveDebugLocation();
  15644. mBfIRBuilder->ClearDebugLocation();
  15645. }
  15646. BfIRValue value;
  15647. if (fieldDef->mIsStatic)
  15648. {
  15649. value = ReferenceStaticField(fieldInst).mValue;
  15650. }
  15651. else
  15652. {
  15653. PopulateType(fieldInst->mResolvedType);
  15654. if (fieldInst->mResolvedType->IsValuelessType())
  15655. {
  15656. value = mBfIRBuilder->GetFakeVal();
  15657. }
  15658. else if (!mCurTypeInstance->IsValueType())
  15659. {
  15660. auto thisValue = GetThis();
  15661. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  15662. }
  15663. else
  15664. {
  15665. AssertErrorState();
  15666. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15667. }
  15668. }
  15669. BfIRValue staticVal;
  15670. if (hasDbgInfo)
  15671. {
  15672. BfIRValue dbgShowValue = value;
  15673. BfLocalVariable* localDef = new BfLocalVariable();
  15674. localDef->mName = "_";
  15675. localDef->mResolvedType = fieldInst->mResolvedType;
  15676. if ((fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15677. {
  15678. localDef->mValue = mBfIRBuilder->CreateBitCast(value, mBfIRBuilder->MapType(fieldInst->mResolvedType));
  15679. }
  15680. else
  15681. {
  15682. localDef->mAddr = value;
  15683. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  15684. {
  15685. // Create another pointer indirection, a ref to the gep
  15686. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  15687. auto allocaInst = CreateAlloca(refFieldType);
  15688. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  15689. localDef->mResolvedType = refFieldType;
  15690. localDef->mAddr = allocaInst;
  15691. }
  15692. }
  15693. mBfIRBuilder->RestoreDebugLocation();
  15694. auto defLocalVar = AddLocalVariableDef(localDef, true);
  15695. if ((!fieldInst->IsAppendedObject()) && (!fieldDef->mIsStatic))
  15696. {
  15697. // Put back so we actually modify the correct value*/
  15698. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  15699. defLocalVar->mAddr = value;
  15700. }
  15701. }
  15702. while (fieldDtor != NULL)
  15703. {
  15704. if (mCompiler->mResolvePassData != NULL)
  15705. {
  15706. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15707. {
  15708. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15709. sourceClassifier->VisitChild(fieldDtor);
  15710. }
  15711. }
  15712. UpdateSrcPos(fieldDtor);
  15713. VisitEmbeddedStatement(fieldDtor->mBody);
  15714. fieldDtor = fieldDtor->mNextFieldDtor;
  15715. }
  15716. RestoreScopeState();
  15717. }
  15718. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  15719. {
  15720. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  15721. {
  15722. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  15723. continue;
  15724. }
  15725. auto refNode = fieldDef->GetRefNode();
  15726. UpdateSrcPos(refNode);
  15727. auto objectType = mContext->mBfObjectType;
  15728. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  15729. BfTypedValue val;
  15730. if (fieldDef->mIsStatic)
  15731. {
  15732. val = ReferenceStaticField(fieldInst);
  15733. val = LoadValue(val);
  15734. }
  15735. else
  15736. {
  15737. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  15738. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  15739. }
  15740. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  15741. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  15742. while (checkTypeInst != NULL)
  15743. {
  15744. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  15745. if (dtorMethodDef)
  15746. {
  15747. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  15748. {
  15749. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  15750. }
  15751. }
  15752. checkTypeInst = checkTypeInst->mBaseType;
  15753. allowPrivate = false;
  15754. }
  15755. // call dtor
  15756. BfExprEvaluator expressionEvaluator(this);
  15757. PopulateType(val.mType);
  15758. PopulateType(objectType, BfPopulateType_DataAndMethods);
  15759. EmitObjectAccessCheck(val);
  15760. if (objectType->mVirtualMethodTable.size() == 0)
  15761. {
  15762. if (!mCompiler->IsAutocomplete())
  15763. AssertErrorState();
  15764. }
  15765. else if (!IsSkippingExtraResolveChecks())
  15766. {
  15767. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  15768. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  15769. SizedArray<BfIRValue, 4> llvmArgs;
  15770. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  15771. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  15772. }
  15773. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  15774. {
  15775. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15776. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  15777. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  15778. }
  15779. }
  15780. }
  15781. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  15782. {
  15783. auto checkBaseType = mCurTypeInstance->mBaseType;
  15784. while (checkBaseType != NULL)
  15785. {
  15786. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15787. {
  15788. if (bodyBlock->mCloseBrace != NULL)
  15789. UpdateSrcPos(bodyBlock->mCloseBrace);
  15790. }
  15791. else
  15792. {
  15793. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  15794. }
  15795. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  15796. if (dtorMethodDef != NULL)
  15797. {
  15798. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  15799. if (IsSkippingExtraResolveChecks())
  15800. {
  15801. // Nothing
  15802. }
  15803. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  15804. {
  15805. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  15806. {
  15807. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  15808. SizedArray<BfIRValue, 1> vals = { basePtr };
  15809. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  15810. if (mIsComptimeModule)
  15811. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  15812. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  15813. }
  15814. }
  15815. else
  15816. {
  15817. // Invalid base dtor declaration
  15818. AssertErrorState();
  15819. }
  15820. break;
  15821. }
  15822. checkBaseType = checkBaseType->mBaseType;
  15823. }
  15824. }
  15825. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15826. }
  15827. else
  15828. {
  15829. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15830. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15831. // resolve pass, NOT the autocomplete expression
  15832. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15833. {
  15834. if (tempTypeDef->mFullName == typeDef->mFullName)
  15835. {
  15836. for (auto fieldDef : tempTypeDef->mFields)
  15837. {
  15838. auto fieldDecl = fieldDef->GetFieldDeclaration();
  15839. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  15840. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15841. {
  15842. BfType* fieldType = NULL;
  15843. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  15844. {
  15845. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  15846. auto curFieldDef = curFieldInstance->GetFieldDef();
  15847. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  15848. fieldType = curFieldInstance->GetResolvedType();
  15849. }
  15850. if (fieldType == NULL)
  15851. fieldType = GetPrimitiveType(BfTypeCode_Var);
  15852. auto fieldDtor = fieldDecl->mFieldDtor;
  15853. BfScopeData scopeData;
  15854. mCurMethodState->AddScope(&scopeData);
  15855. NewScopeState();
  15856. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  15857. if (fieldType != NULL)
  15858. {
  15859. BfLocalVariable* localDef = new BfLocalVariable();
  15860. localDef->mName = "_";
  15861. localDef->mResolvedType = fieldType;
  15862. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  15863. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15864. AddLocalVariableDef(localDef);
  15865. }
  15866. while (fieldDtor != NULL)
  15867. {
  15868. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  15869. {
  15870. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  15871. sourceClassifier->VisitChild(fieldDtor);
  15872. }
  15873. UpdateSrcPos(fieldDtor);
  15874. VisitEmbeddedStatement(fieldDtor->mBody);
  15875. fieldDtor = fieldDtor->mNextFieldDtor;
  15876. }
  15877. RestoreScopeState();
  15878. }
  15879. }
  15880. }
  15881. }
  15882. }
  15883. // If there are appends then we just need the rootmost append type to do the Dbg_AppendDeleted
  15884. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  15885. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  15886. {
  15887. auto thisValue = GetThis();
  15888. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  15889. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_AppendDeleted", 2);
  15890. SizedArray<BfIRValue, 1> llvmArgs;
  15891. llvmArgs.Add(appendedObj);
  15892. llvmArgs.Add(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mCurMethodState->mDisableChecks ? 0 : 1));
  15893. if (allocMethod)
  15894. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  15895. }
  15896. }
  15897. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  15898. {
  15899. BF_ASSERT(methodInstance->mIsReified);
  15900. auto typeInstance = methodInstance->GetOwner();
  15901. bool foundDllImportAttr = false;
  15902. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  15903. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15904. {
  15905. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15906. {
  15907. foundDllImportAttr = true;
  15908. }
  15909. }
  15910. if (!foundDllImportAttr)
  15911. {
  15912. AssertErrorState();
  15913. return BfIRValue();
  15914. }
  15915. StringT<512> name = "bf_hs_preserve@";
  15916. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  15917. name += "__imp";
  15918. BfIRType returnType;
  15919. SizedArray<BfIRType, 8> paramTypes;
  15920. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15921. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15922. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15923. BfIRValue initVal;
  15924. if (define)
  15925. {
  15926. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15927. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15928. }
  15929. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15930. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15931. {
  15932. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15933. auto ptrType = CreatePointerType(voidType);
  15934. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15935. }
  15936. return globalVar;
  15937. }
  15938. void BfModule::CreateDllImportMethod()
  15939. {
  15940. if (mBfIRBuilder->mIgnoreWrites)
  15941. return;
  15942. auto globalVar = mFuncReferences[mCurMethodInstance];
  15943. if (!globalVar)
  15944. return;
  15945. bool allowTailCall = true;
  15946. mBfIRBuilder->ClearDebugLocation();
  15947. bool isHotCompile = mCompiler->IsHotCompile();
  15948. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15949. if (isHotCompile)
  15950. {
  15951. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15952. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15953. }
  15954. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15955. BfIRType returnType;
  15956. SizedArray<BfIRType, 8> paramTypes;
  15957. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15958. SizedArray<BfIRValue, 8> args;
  15959. for (int i = 0; i < (int)paramTypes.size(); i++)
  15960. args.push_back(mBfIRBuilder->GetArgument(i));
  15961. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15962. if (isHotCompile)
  15963. {
  15964. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15965. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15966. if (callingConvention == BfIRCallingConv_StdCall)
  15967. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15968. else if (callingConvention == BfIRCallingConv_FastCall)
  15969. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15970. else
  15971. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15972. if (allowTailCall)
  15973. mBfIRBuilder->SetTailCall(result);
  15974. CreateReturn(result);
  15975. mCurMethodState->mHadReturn = true;
  15976. }
  15977. if (HasCompiledOutput())
  15978. {
  15979. BfDllImportEntry dllImportEntry;
  15980. dllImportEntry.mFuncVar = globalVar;
  15981. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15982. mDllImportEntries.push_back(dllImportEntry);
  15983. }
  15984. }
  15985. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15986. {
  15987. auto methodDef = methodInstance->mMethodDef;
  15988. BfTypeInstance* owner = NULL;
  15989. if (!methodDef->mIsStatic)
  15990. owner = methodInstance->GetThisType()->ToTypeInstance();
  15991. if (owner == NULL)
  15992. owner = methodInstance->GetOwner();
  15993. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15994. return BfIRCallingConv_CDecl;
  15995. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15996. return BfIRCallingConv_StdCall;
  15997. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15998. return BfIRCallingConv_FastCall;
  15999. if (!methodDef->mIsStatic)
  16000. {
  16001. if (owner->mIsCRepr)
  16002. return BfIRCallingConv_ThisCall;
  16003. if ((!owner->IsValuelessType()) &&
  16004. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  16005. return BfIRCallingConv_ThisCall;
  16006. }
  16007. return BfIRCallingConv_CDecl;
  16008. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  16009. }
  16010. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  16011. {
  16012. BfMethodDef* methodDef = NULL;
  16013. if (methodInstance != NULL)
  16014. methodDef = methodInstance->mMethodDef;
  16015. if (!func)
  16016. return;
  16017. if (mCompiler->mOptions.mNoFramePointerElim)
  16018. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  16019. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  16020. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  16021. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  16022. if (methodInstance == NULL)
  16023. return;
  16024. if (methodInstance->mReturnType->IsVar())
  16025. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  16026. if (methodDef->mImportKind == BfImportKind_Export)
  16027. {
  16028. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  16029. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  16030. }
  16031. if (methodDef->mIsNoReturn)
  16032. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  16033. auto callingConv = GetIRCallingConvention(methodInstance);
  16034. if (callingConv != BfIRCallingConv_CDecl)
  16035. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  16036. if (isInlined)
  16037. {
  16038. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16039. }
  16040. int argIdx = 0;
  16041. int paramIdx = 0;
  16042. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  16043. paramIdx = -1;
  16044. int argCount = methodInstance->GetIRFunctionParamCount(this);
  16045. while (argIdx < argCount)
  16046. {
  16047. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16048. {
  16049. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  16050. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  16051. argIdx++;
  16052. continue;
  16053. }
  16054. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  16055. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  16056. paramIdx++;
  16057. BfType* resolvedTypeRef = NULL;
  16058. BfType* resolvedTypeRef2 = NULL;
  16059. String paramName;
  16060. bool isSplattable = false;
  16061. bool tryLowering = !mIsComptimeModule;
  16062. if (isThis)
  16063. {
  16064. paramName = "this";
  16065. if (methodInstance->mIsClosure)
  16066. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  16067. else
  16068. resolvedTypeRef = methodInstance->GetThisType();
  16069. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  16070. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  16071. }
  16072. else
  16073. {
  16074. paramName = methodInstance->GetParamName(paramIdx);
  16075. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  16076. if (resolvedTypeRef->IsMethodRef())
  16077. isSplattable = true;
  16078. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  16079. {
  16080. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  16081. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  16082. {
  16083. // crepr splat is always splattable
  16084. isSplattable = true;
  16085. }
  16086. else
  16087. {
  16088. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  16089. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  16090. isSplattable = true;
  16091. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  16092. isSplattable = true;
  16093. }
  16094. }
  16095. }
  16096. if (tryLowering)
  16097. {
  16098. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16099. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16100. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  16101. {
  16102. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  16103. argIdx++;
  16104. if (loweredTypeCode2 != BfTypeCode_None)
  16105. {
  16106. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  16107. argIdx++;
  16108. }
  16109. paramIdx++;
  16110. continue;
  16111. }
  16112. }
  16113. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  16114. {
  16115. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  16116. int addDeref = -1;
  16117. if (resolvedTypeRef->IsRef())
  16118. {
  16119. auto refType = (BfRefType*)resolvedTypeRef;
  16120. auto elementType = refType->mElementType;
  16121. PopulateType(elementType, BfPopulateType_Data);
  16122. addDeref = elementType->mSize;
  16123. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  16124. AssertErrorState();
  16125. }
  16126. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  16127. {
  16128. if (isThis)
  16129. {
  16130. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  16131. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  16132. addDeref = resolvedTypeRef->mSize;
  16133. }
  16134. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  16135. {
  16136. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  16137. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  16138. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  16139. }
  16140. }
  16141. else if (resolvedTypeRef->IsPrimitiveType())
  16142. {
  16143. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  16144. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  16145. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  16146. }
  16147. if (addDeref >= 0)
  16148. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  16149. argIdx++;
  16150. };
  16151. if (isSplattable)
  16152. {
  16153. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  16154. {
  16155. if (checkType->IsStruct())
  16156. {
  16157. auto checkTypeInstance = checkType->ToTypeInstance();
  16158. if (checkTypeInstance->mBaseType != NULL)
  16159. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  16160. if (checkTypeInstance->mIsUnion)
  16161. {
  16162. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  16163. checkTypeLambda(unionInnerType, curName + "_data");
  16164. }
  16165. else
  16166. {
  16167. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16168. {
  16169. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16170. auto fieldDef = fieldInstance->GetFieldDef();
  16171. if (fieldInstance->mDataIdx >= 0)
  16172. {
  16173. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  16174. }
  16175. }
  16176. }
  16177. if (checkTypeInstance->IsEnum())
  16178. {
  16179. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  16180. argIdx++;
  16181. }
  16182. }
  16183. else if (checkType->IsMethodRef())
  16184. {
  16185. auto methodRefType = (BfMethodRefType*)checkType;
  16186. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  16187. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  16188. {
  16189. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  16190. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  16191. {
  16192. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  16193. }
  16194. else
  16195. {
  16196. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  16197. }
  16198. }
  16199. }
  16200. else if (!checkType->IsValuelessType())
  16201. {
  16202. _SetupParam(curName, checkType);
  16203. }
  16204. };
  16205. checkTypeLambda(resolvedTypeRef, paramName);
  16206. paramIdx++;
  16207. continue;
  16208. }
  16209. _SetupParam(paramName, resolvedTypeRef);
  16210. if (resolvedTypeRef2 != NULL)
  16211. _SetupParam(paramName, resolvedTypeRef2);
  16212. paramIdx++;
  16213. }
  16214. }
  16215. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  16216. {
  16217. auto methodDef = mCurMethodInstance->mMethodDef;
  16218. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  16219. BfMemberSetEntry* entry = NULL;
  16220. BfMethodDef* initMethodDef = NULL;
  16221. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16222. if (entry != NULL)
  16223. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16224. SizedArray<BfAstNode*, 8> initBodies;
  16225. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16226. {
  16227. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  16228. continue;
  16229. if (initMethodDef->mMethodType != BfMethodType_Init)
  16230. continue;
  16231. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  16232. continue;
  16233. initBodies.Insert(0, initMethodDef->mBody);
  16234. }
  16235. for (auto body : initBodies)
  16236. {
  16237. initBlockCallback(body);
  16238. VisitEmbeddedStatement(body);
  16239. }
  16240. }
  16241. void BfModule::EmitCtorBody(bool& skipBody)
  16242. {
  16243. auto methodInstance = mCurMethodInstance;
  16244. auto methodDef = methodInstance->mMethodDef;
  16245. auto methodDeclaration = methodDef->mMethodDeclaration;
  16246. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  16247. auto typeDef = mCurTypeInstance->mTypeDef;
  16248. BfCustomAttributes* customAttributes = NULL;
  16249. defer(delete customAttributes);
  16250. BfInvocationExpression* ctorInvocation = NULL;
  16251. BfAttributeState attributeState;
  16252. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  16253. if (ctorDeclaration != NULL)
  16254. {
  16255. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  16256. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  16257. {
  16258. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  16259. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  16260. }
  16261. }
  16262. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  16263. // Prologue
  16264. mBfIRBuilder->ClearDebugLocation();
  16265. bool hadThisInitializer = false;
  16266. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16267. {
  16268. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16269. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16270. if (targetToken->GetToken() == BfToken_This)
  16271. {
  16272. hadThisInitializer = true;
  16273. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  16274. mCurMethodState->LocalDefined(GetThisVariable());
  16275. }
  16276. }
  16277. // Zero out memory for default ctor
  16278. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (!mCurTypeInstance->IsAnonymousInitializerType()) && (methodInstance->mChainType != BfMethodChainType_ChainMember) &&
  16279. (!mCurMethodState->mLocals.IsEmpty()))
  16280. {
  16281. if (mCurTypeInstance->IsTypedPrimitive())
  16282. {
  16283. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16284. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  16285. }
  16286. else if (mCurTypeInstance->mInstSize > 0)
  16287. {
  16288. BfIRValue fillValue = GetConstValue8(0);
  16289. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  16290. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  16291. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  16292. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  16293. }
  16294. }
  16295. BfAstNode* baseCtorNode = NULL;
  16296. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  16297. baseCtorNode = ctorInvocation->mTarget;
  16298. else if (methodDef->mBody != NULL)
  16299. baseCtorNode = methodDef->mBody;
  16300. else if (ctorDeclaration != NULL)
  16301. baseCtorNode = ctorDeclaration;
  16302. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16303. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  16304. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16305. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  16306. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  16307. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  16308. else
  16309. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  16310. bool calledCtorNoBody = false;
  16311. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  16312. {
  16313. // Zero out typed primitives in ctor
  16314. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  16315. }
  16316. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  16317. {
  16318. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  16319. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  16320. {
  16321. BfMethodDef* defaultCtor = NULL;
  16322. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  16323. {
  16324. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  16325. {
  16326. defaultCtor = methodDef;
  16327. }
  16328. }
  16329. if (defaultCtor != NULL)
  16330. {
  16331. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  16332. SetIllegalSrcPos();
  16333. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  16334. BfExprEvaluator exprEvaluator(this);
  16335. SizedArray<BfIRValue, 1> irArgs;
  16336. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  16337. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  16338. if (mIsComptimeModule)
  16339. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  16340. calledCtorNoBody = true;
  16341. }
  16342. }
  16343. }
  16344. // Initialize fields (if applicable)
  16345. if (mCurTypeInstance->IsBoxed())
  16346. {
  16347. skipBody = true;
  16348. }
  16349. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  16350. {
  16351. // Field initializers occur in CtorNoBody methods for extensions
  16352. }
  16353. else if (!hadThisInitializer)
  16354. {
  16355. // If we had a 'this' initializer, that other ctor will have initialized our fields
  16356. //auto
  16357. if ((!mCompiler->mIsResolveOnly) ||
  16358. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  16359. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  16360. {
  16361. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  16362. // to properly set the assigned flags
  16363. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  16364. bool hadInlineInitBlock = false;
  16365. BfScopeData scopeData;
  16366. scopeData.mInInitBlock = true;
  16367. auto _CheckInitBlock = [&](BfAstNode* node)
  16368. {
  16369. if (!hadInlineInitBlock)
  16370. {
  16371. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  16372. {
  16373. UpdateSrcPos(baseCtorNode);
  16374. if (methodDef->mBody == NULL)
  16375. SetIllegalSrcPos();
  16376. // 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
  16377. EmitEnsureInstructionAt();
  16378. BfType* thisType = mCurTypeInstance;
  16379. if (thisType->IsValueType())
  16380. thisType = CreateRefType(thisType);
  16381. SizedArray<BfIRMDNode, 1> diParamTypes;
  16382. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  16383. mCurMethodState->AddScope(&scopeData);
  16384. NewScopeState();
  16385. int flags = 0;
  16386. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  16387. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  16388. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  16389. String linkageName;
  16390. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  16391. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  16392. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  16393. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  16394. UpdateSrcPos(node);
  16395. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16396. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  16397. if (!mCurTypeInstance->IsValuelessType())
  16398. {
  16399. auto loadedThis = GetThis();
  16400. // LLVM can't handle two variables pointing to the same value
  16401. BfIRValue copiedThisPtr;
  16402. copiedThisPtr = CreateAlloca(thisType);
  16403. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  16404. mBfIRBuilder->ClearDebugLocation(storeInst);
  16405. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  16406. }
  16407. hadInlineInitBlock = true;
  16408. }
  16409. else
  16410. {
  16411. // Just do a simple one
  16412. mCurMethodState->AddScope(&scopeData);
  16413. NewScopeState();
  16414. hadInlineInitBlock = true;
  16415. }
  16416. }
  16417. UpdateSrcPos(node);
  16418. };
  16419. for (auto fieldDef : typeDef->mFields)
  16420. {
  16421. // For extensions, only handle these fields in the appropriate extension
  16422. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16423. continue;
  16424. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  16425. {
  16426. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16427. if (!fieldInst->mFieldIncluded)
  16428. continue;
  16429. if (fieldInst->mDataIdx < 0)
  16430. continue;
  16431. auto initializer = fieldDef->GetInitializer();
  16432. if (fieldInst->IsAppendedObject())
  16433. {
  16434. UpdateSrcPos(fieldDef->GetNameNode());
  16435. AppendedObjectInit(fieldInst);
  16436. continue;
  16437. }
  16438. if (initializer == NULL)
  16439. {
  16440. continue;
  16441. // if (fieldDef->mProtection != BfProtection_Hidden)
  16442. // continue;
  16443. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  16444. // continue;
  16445. }
  16446. if (fieldInst->mResolvedType == NULL)
  16447. {
  16448. BF_ASSERT(mHadBuildError);
  16449. continue;
  16450. }
  16451. if (initializer != NULL)
  16452. {
  16453. _CheckInitBlock(initializer);
  16454. }
  16455. BfIRValue fieldAddr;
  16456. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  16457. {
  16458. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  16459. }
  16460. else
  16461. {
  16462. // Failed
  16463. }
  16464. auto assignValue = GetFieldInitializerValue(fieldInst);
  16465. if (mCurTypeInstance->IsUnion())
  16466. {
  16467. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  16468. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  16469. }
  16470. if ((fieldAddr) && (assignValue))
  16471. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  16472. }
  16473. }
  16474. EmitInitBlocks(_CheckInitBlock);
  16475. if (hadInlineInitBlock)
  16476. {
  16477. RestoreScopeState();
  16478. // This gets set to false because of AddScope but we actually are still in the head block
  16479. mCurMethodState->mInHeadScope = true;
  16480. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  16481. mCurMethodState->mHadReturn = false;
  16482. mCurMethodState->mLeftBlockUncond = false;
  16483. }
  16484. }
  16485. else // Autocomplete case
  16486. {
  16487. BfScopeData scopeData;
  16488. scopeData.mInInitBlock = true;
  16489. mCurMethodState->AddScope(&scopeData);
  16490. NewScopeState();
  16491. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  16492. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  16493. // resolve pass, NOT the autocomplete expression
  16494. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  16495. {
  16496. if (tempTypeDef->mFullName == typeDef->mFullName)
  16497. {
  16498. for (auto fieldDef : tempTypeDef->mFields)
  16499. {
  16500. auto initializer = fieldDef->GetInitializer();
  16501. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  16502. {
  16503. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  16504. {
  16505. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  16506. sourceClassifier->VisitChild(initializer);
  16507. }
  16508. BfType* wantType = NULL;
  16509. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  16510. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  16511. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  16512. if ((wantType != NULL) &&
  16513. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  16514. wantType = NULL;
  16515. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  16516. if (fieldDef->mIsAppend)
  16517. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  16518. CreateValueFromExpression(initializer, wantType, exprFlags);
  16519. }
  16520. }
  16521. tempTypeDef->PopulateMemberSets();
  16522. BfMemberSetEntry* entry = NULL;
  16523. BfMethodDef* initMethodDef = NULL;
  16524. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  16525. if (entry != NULL)
  16526. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  16527. SizedArray<BfAstNode*, 8> initBodies;
  16528. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  16529. {
  16530. if (initMethodDef->mMethodType != BfMethodType_Init)
  16531. continue;
  16532. initBodies.Insert(0, initMethodDef->mBody);
  16533. }
  16534. for (auto body : initBodies)
  16535. VisitEmbeddedStatement(body);
  16536. }
  16537. }
  16538. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  16539. for (auto fieldDef : typeDef->mFields)
  16540. {
  16541. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  16542. {
  16543. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  16544. if (fieldDef->GetInitializer() != NULL)
  16545. MarkFieldInitialized(fieldInst);
  16546. }
  16547. }
  16548. RestoreScopeState();
  16549. }
  16550. }
  16551. if (!methodInstance->mIsAutocompleteMethod)
  16552. {
  16553. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  16554. {
  16555. BfExprEvaluator exprEvaluator(this);
  16556. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  16557. {
  16558. auto paramDef = methodDef->mParams[paramIdx];
  16559. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  16560. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  16561. if (fieldInstance.mDataIdx < 0)
  16562. continue;
  16563. if (paramDef->mParamKind != BfParamKind_Normal)
  16564. continue;
  16565. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  16566. BF_ASSERT(localVar->mName == paramDef->mName);
  16567. auto localVal = exprEvaluator.LoadLocal(localVar);
  16568. localVal = LoadOrAggregateValue(localVal);
  16569. if (!localVal.mType->IsVar())
  16570. {
  16571. auto thisVal = GetThis();
  16572. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  16573. if (mCurTypeInstance->IsUnion())
  16574. fieldPtr = mBfIRBuilder->CreateBitCast(fieldPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInstance.mResolvedType)));
  16575. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  16576. }
  16577. MarkFieldInitialized(&fieldInstance);
  16578. }
  16579. }
  16580. }
  16581. // Call base ctor (if applicable)
  16582. BfTypeInstance* targetType = NULL;
  16583. BfAstNode* targetRefNode = NULL;
  16584. if (ctorDeclaration != NULL)
  16585. targetRefNode = ctorDeclaration->mInitializer;
  16586. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  16587. targetRefNode = invocationExpr->mTarget;
  16588. if (targetRefNode == NULL)
  16589. targetRefNode = mCurTypeInstance->mTypeDef->GetRefNode();
  16590. if (baseCtorNode != NULL)
  16591. {
  16592. UpdateSrcPos(baseCtorNode);
  16593. if (methodDef->mBody == NULL)
  16594. SetIllegalSrcPos();
  16595. }
  16596. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16597. {
  16598. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  16599. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  16600. }
  16601. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  16602. {
  16603. auto baseType = mCurTypeInstance->mBaseType;
  16604. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  16605. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  16606. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  16607. {
  16608. // Try to find a ctor without any params first
  16609. BfMethodDef* matchedMethod = NULL;
  16610. bool hadCtorWithAllDefaults = false;
  16611. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  16612. for (int pass = 0; pass < 2; pass++)
  16613. {
  16614. baseType->mTypeDef->PopulateMemberSets();
  16615. BfMemberSetEntry* entry = NULL;
  16616. BfMethodDef* checkMethodDef = NULL;
  16617. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  16618. if (entry != NULL)
  16619. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  16620. while (checkMethodDef != NULL)
  16621. {
  16622. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  16623. if (isHiddenGenerated)
  16624. {
  16625. // Allow calling of the default base ctor if it is implicitly defined
  16626. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  16627. allowMethod = true;
  16628. }
  16629. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  16630. {
  16631. if (checkMethodDef->mParams.size() == 0)
  16632. {
  16633. if (matchedMethod != NULL)
  16634. {
  16635. // Has multiple matched methods - can happen from extensions
  16636. matchedMethod = NULL;
  16637. break;
  16638. }
  16639. matchedMethod = checkMethodDef;
  16640. }
  16641. else if (isHiddenGenerated)
  16642. {
  16643. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  16644. hadCtorWithAllDefaults = true;
  16645. }
  16646. }
  16647. checkMethodDef = checkMethodDef->mNextWithSameName;
  16648. }
  16649. if (matchedMethod != NULL)
  16650. break;
  16651. }
  16652. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  16653. {
  16654. SizedArray<BfIRValue, 1> args;
  16655. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  16656. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  16657. {
  16658. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  16659. args.push_back(basePtr);
  16660. }
  16661. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  16662. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  16663. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  16664. if (callingConv != BfIRCallingConv_CDecl)
  16665. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  16666. if (mIsComptimeModule)
  16667. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  16668. }
  16669. if (matchedMethod == NULL)
  16670. {
  16671. targetType = mCurTypeInstance->mBaseType;
  16672. if (ctorDeclaration != NULL)
  16673. targetRefNode = ctorDeclaration->mThisToken;
  16674. else if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mNameNode != NULL))
  16675. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  16676. }
  16677. }
  16678. }
  16679. if (methodDef->HasAppend())
  16680. {
  16681. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  16682. }
  16683. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  16684. {
  16685. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  16686. {
  16687. if (targetType == mCurTypeInstance)
  16688. {
  16689. auto thisVariable = GetThisVariable();
  16690. if (thisVariable != NULL)
  16691. {
  16692. thisVariable->mUnassignedFieldFlags = 0;
  16693. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16694. }
  16695. }
  16696. targetType = NULL;
  16697. }
  16698. }
  16699. auto autoComplete = mCompiler->GetAutoComplete();
  16700. if ((targetType != NULL) && (!mCurTypeInstance->IsAnonymousInitializerType()))
  16701. {
  16702. BfAstNode* refNode = methodDeclaration;
  16703. if (refNode == NULL)
  16704. refNode = typeDef->mTypeDeclaration;
  16705. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  16706. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16707. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16708. {
  16709. auto invocationExpr = ctorInvocation;
  16710. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16711. }
  16712. BfType* targetThisType = targetType;
  16713. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  16714. BfExprEvaluator exprEvaluator(this);
  16715. BfResolvedArgs argValues;
  16716. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  16717. {
  16718. argValues.Init(&ctorInvocation->mArguments);
  16719. if (gDebugStuff)
  16720. {
  16721. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  16722. }
  16723. }
  16724. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  16725. BfAllowAppendKind allowAppendKind = GetBaseAllowAppend(mCurMethodInstance);
  16726. BfTypedValue appendIdxVal;
  16727. if (methodDef->HasAppend())
  16728. {
  16729. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  16730. BF_ASSERT(localVar->mName == "__appendIdx");
  16731. auto intRefType = localVar->mResolvedType;
  16732. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  16733. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  16734. }
  16735. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, BfMethodGenericArguments(), allowAppendKind, &appendIdxVal);
  16736. if (autoComplete != NULL)
  16737. {
  16738. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16739. {
  16740. if (autoComplete->mMethodMatchInfo != NULL)
  16741. autoComplete->mIsCapturingMethodMatchInfo = true;
  16742. else
  16743. autoComplete->mIsCapturingMethodMatchInfo = false;
  16744. }
  16745. else
  16746. autoComplete->mIsCapturingMethodMatchInfo = false;
  16747. }
  16748. }
  16749. auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration);
  16750. if ((autoComplete != NULL) && (autoComplete->CheckFixit(methodDeclaration)) && (methodDeclaration != NULL) && (autoCtorDecl != NULL))
  16751. {
  16752. auto typeDecl = methodDef->mDeclaringType->mTypeDeclaration;
  16753. BfParserData* parser = typeDecl->GetSourceData()->ToParserData();
  16754. if (parser != NULL)
  16755. {
  16756. String fixitStr = "Expand auto constructor\t";
  16757. int insertPos = typeDecl->mSrcStart;
  16758. bool needsBlock = false;
  16759. if (auto defBlock = BfNodeDynCast<BfBlock>(typeDecl->mDefineNode))
  16760. {
  16761. insertPos = defBlock->mOpenBrace->mSrcStart + 1;
  16762. }
  16763. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(typeDecl->mDefineNode))
  16764. {
  16765. insertPos = tokenNode->mSrcStart;
  16766. fixitStr += StrFormat("delete|%s-%d|\x01",
  16767. autoComplete->FixitGetLocation(parser, tokenNode->mSrcStart).c_str(), tokenNode->mSrcEnd - tokenNode->mSrcStart);
  16768. needsBlock = true;
  16769. }
  16770. int srcStart = methodDeclaration->mSrcStart;
  16771. if ((autoCtorDecl->mPrefix == NULL) && (typeDecl->mColonToken != NULL))
  16772. srcStart = typeDecl->mColonToken->mSrcStart;
  16773. while ((srcStart > 0) && (::isspace((uint8)parser->mSrc[srcStart - 1])))
  16774. srcStart--;
  16775. fixitStr += StrFormat("expand|%s|%d|",
  16776. parser->mFileName.c_str(), insertPos);
  16777. if (needsBlock)
  16778. fixitStr += "\t";
  16779. else
  16780. fixitStr += "\f";
  16781. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16782. {
  16783. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16784. paramStr.Replace('\n', '\r');
  16785. fixitStr += "public ";
  16786. fixitStr += paramStr;
  16787. fixitStr += ";\r";
  16788. }
  16789. fixitStr += "\rpublic this(";
  16790. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16791. {
  16792. if (paramIdx > 0)
  16793. fixitStr += ", ";
  16794. String paramStr = autoCtorDecl->mParams[paramIdx]->ToString();
  16795. paramStr.Replace('\n', '\r');
  16796. fixitStr += paramStr;
  16797. }
  16798. fixitStr += ")\t";
  16799. for (int paramIdx = 0; paramIdx < autoCtorDecl->mParams.mSize; paramIdx++)
  16800. {
  16801. if (paramIdx > 0)
  16802. fixitStr += "\r";
  16803. auto nameNode = autoCtorDecl->mParams[paramIdx]->mNameNode;
  16804. if (nameNode == NULL)
  16805. continue;
  16806. String nameStr = nameNode->ToString();
  16807. fixitStr += "this.";
  16808. fixitStr += nameStr;
  16809. fixitStr += " = ";
  16810. fixitStr += nameStr;
  16811. fixitStr += ";";
  16812. }
  16813. fixitStr += "\b";
  16814. if (needsBlock)
  16815. fixitStr += "\b";
  16816. fixitStr += StrFormat("\x01""delete|%s-%d|",
  16817. autoComplete->FixitGetLocation(parser, srcStart).c_str(), autoCtorDecl->mSrcEnd - srcStart);
  16818. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", fixitStr.c_str()));
  16819. }
  16820. }
  16821. }
  16822. void BfModule::EmitEnumToStringBody()
  16823. {
  16824. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16825. auto strVal = CreateAlloca(stringType);
  16826. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  16827. BfExprEvaluator exprEvaluator(this);
  16828. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16829. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  16830. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  16831. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  16832. BfType* discriminatorType = NULL;
  16833. BfTypedValue rawPayload;
  16834. BfIRValue enumVal;
  16835. if (mCurTypeInstance->IsPayloadEnum())
  16836. {
  16837. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  16838. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  16839. enumTypedValue = LoadValue(enumTypedValue);
  16840. enumVal = enumTypedValue.mValue;
  16841. rawPayload = ExtractValue(GetThis(), NULL, 1);
  16842. }
  16843. else
  16844. enumVal = LoadValue(GetThis()).mValue;
  16845. Array<BfType*> paramTypes;
  16846. paramTypes.Add(stringType);
  16847. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16848. BfIRValue switchVal;
  16849. if (!mCurTypeInstance->IsValuelessType())
  16850. switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  16851. HashSet<int64> handledCases;
  16852. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16853. {
  16854. if (fieldInstance.mIsEnumPayloadCase)
  16855. {
  16856. int tagId = -fieldInstance.mDataIdx - 1;
  16857. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16858. mBfIRBuilder->AddBlock(caseBlock);
  16859. mBfIRBuilder->SetInsertPoint(caseBlock);
  16860. BF_ASSERT(discriminatorType->IsPrimitiveType());
  16861. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  16862. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16863. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16864. auto stringDestVal = LoadValue(stringDestAddr);
  16865. SizedArray<BfIRValue, 2> args;
  16866. args.Add(stringDestVal.mValue);
  16867. args.Add(caseStr);
  16868. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16869. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  16870. BF_ASSERT(payloadType->IsTuple());
  16871. if (payloadType->mFieldInstances.size() != 0)
  16872. {
  16873. auto payload = rawPayload;
  16874. if (payload.mType != payloadType)
  16875. {
  16876. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  16877. }
  16878. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  16879. SizedArray<BfIRValue, 2> irArgs;
  16880. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  16881. stringDestVal = LoadValue(stringDestAddr);
  16882. irArgs.Add(stringDestVal.mValue);
  16883. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  16884. }
  16885. mBfIRBuilder->CreateBr(endBlock);
  16886. continue;
  16887. }
  16888. if (fieldInstance.mConstIdx == -1)
  16889. continue;
  16890. // Only allow compact 'ValA, ValB' enum declaration fields through
  16891. auto fieldDef = fieldInstance.GetFieldDef();
  16892. auto fieldDecl = fieldDef->mFieldDeclaration;
  16893. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  16894. continue;
  16895. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  16896. if (!handledCases.TryAdd(constant->mInt64, NULL))
  16897. {
  16898. // Duplicate
  16899. continue;
  16900. }
  16901. if (switchVal)
  16902. {
  16903. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  16904. mBfIRBuilder->AddBlock(caseBlock);
  16905. mBfIRBuilder->SetInsertPoint(caseBlock);
  16906. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  16907. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  16908. }
  16909. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  16910. mBfIRBuilder->CreateStore(caseStr, strVal);
  16911. mBfIRBuilder->CreateBr(appendBlock);
  16912. }
  16913. mBfIRBuilder->AddBlock(appendBlock);
  16914. mBfIRBuilder->SetInsertPoint(appendBlock);
  16915. SizedArray<BfIRValue, 2> args;
  16916. auto stringDestVal = LoadValue(stringDestAddr);
  16917. args.Add(stringDestVal.mValue);
  16918. args.Add(mBfIRBuilder->CreateLoad(strVal));
  16919. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16920. if (switchVal)
  16921. {
  16922. mBfIRBuilder->CreateBr(endBlock);
  16923. mBfIRBuilder->AddBlock(noMatchBlock);
  16924. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  16925. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  16926. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  16927. args.clear();
  16928. args.Add(int64Val);
  16929. stringDestVal = LoadValue(stringDestAddr);
  16930. args.Add(stringDestVal.mValue);
  16931. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  16932. mBfIRBuilder->CreateBr(endBlock);
  16933. mBfIRBuilder->AddBlock(endBlock);
  16934. mBfIRBuilder->SetInsertPoint(endBlock);
  16935. }
  16936. }
  16937. void BfModule::EmitTupleToStringBody()
  16938. {
  16939. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  16940. BfExprEvaluator exprEvaluator(this);
  16941. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16942. Array<BfType*> paramTypes;
  16943. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  16944. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16945. paramTypes.Clear();
  16946. paramTypes.Add(stringType);
  16947. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  16948. auto _AppendChar = [&](char c)
  16949. {
  16950. SizedArray<BfIRValue, 2> args;
  16951. auto stringDestVal = LoadValue(stringDestRef);
  16952. args.Add(stringDestVal.mValue);
  16953. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  16954. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  16955. };
  16956. int fieldIdx = 0;
  16957. auto thisValue = GetThis();
  16958. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  16959. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  16960. BfIRValue commaStr;
  16961. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  16962. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  16963. _AppendChar('(');
  16964. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  16965. {
  16966. if (fieldInstance.mDataIdx == -1)
  16967. continue;
  16968. if (fieldIdx > 0)
  16969. {
  16970. if (!commaStr)
  16971. commaStr = GetStringObjectValue(", ");
  16972. SizedArray<BfIRValue, 2> args;
  16973. auto stringDestVal = LoadValue(stringDestRef);
  16974. args.Add(stringDestVal.mValue);
  16975. args.Add(commaStr);
  16976. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16977. }
  16978. fieldIdx++;
  16979. if (fieldInstance.mResolvedType->IsValuelessType())
  16980. continue;
  16981. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  16982. if (fieldValue.mType->IsWrappableType())
  16983. {
  16984. auto wrappedType = GetWrappedStructType(fieldValue.mType);
  16985. if ((wrappedType->IsTypedPrimitive()) || (wrappedType->IsValuelessType()))
  16986. {
  16987. fieldValue.mType = wrappedType;
  16988. }
  16989. else
  16990. {
  16991. fieldValue = MakeAddressable(fieldValue, false, true);
  16992. fieldValue.mType = wrappedType;
  16993. fieldValue.mValue = mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapTypeInstPtr(fieldValue.mType->ToTypeInstance()));
  16994. if (!wrappedType->IsValuelessType())
  16995. fieldValue.mKind = BfTypedValueKind_Addr;
  16996. }
  16997. }
  16998. auto typeInstance = fieldValue.mType->ToTypeInstance();
  16999. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  17000. {
  17001. BfExprEvaluator exprEvaluator(this);
  17002. SizedArray<BfResolvedArg, 0> resolvedArgs;
  17003. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  17004. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  17005. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  17006. methodMatcher.TryDevirtualizeCall(fieldValue);
  17007. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  17008. BfResolvedArg resolvedArg;
  17009. auto stringDestVal = LoadValue(stringDestRef);
  17010. resolvedArg.mTypedValue = stringDestVal;
  17011. resolvedArg.mResolvedType = stringDestVal.mType;
  17012. resolvedArgs.Add(resolvedArg);
  17013. exprEvaluator.CreateCall(&methodMatcher, callVal);
  17014. continue;
  17015. }
  17016. if (fieldValue.mType->IsObjectOrInterface())
  17017. {
  17018. fieldValue = LoadValue(fieldValue);
  17019. BF_ASSERT(!fieldValue.IsAddr());
  17020. SizedArray<BfIRValue, 2> args;
  17021. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  17022. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  17023. stringDestVal = LoadValue(stringDestVal);
  17024. args.Add(stringDestVal.mValue);
  17025. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  17026. continue;
  17027. }
  17028. BfExprEvaluator exprEvaluator(this);
  17029. SizedArray<BfResolvedArg, 0> resolvedArgs;
  17030. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  17031. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  17032. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  17033. methodMatcher.TryDevirtualizeCall(fieldValue);
  17034. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  17035. {
  17036. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  17037. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  17038. // Just append the type name
  17039. String typeName = TypeToString(fieldInstance.mResolvedType);
  17040. auto strVal = GetStringObjectValue(typeName);
  17041. SizedArray<BfIRValue, 2> args;
  17042. auto stringDestVal = LoadValue(stringDestRef);
  17043. args.Add(stringDestVal.mValue);
  17044. args.Add(strVal);
  17045. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  17046. continue;
  17047. }
  17048. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  17049. BfResolvedArg resolvedArg;
  17050. auto stringDestVal = LoadValue(stringDestRef);
  17051. resolvedArg.mTypedValue = stringDestVal;
  17052. resolvedArg.mResolvedType = stringDestVal.mType;
  17053. resolvedArgs.Add(resolvedArg);
  17054. exprEvaluator.CreateCall(&methodMatcher, callVal);
  17055. }
  17056. _AppendChar(')');
  17057. }
  17058. void BfModule::EmitIteratorBlock(bool& skipBody)
  17059. {
  17060. auto methodInstance = mCurMethodInstance;
  17061. auto methodDef = methodInstance->mMethodDef;
  17062. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17063. auto typeDef = mCurTypeInstance->mTypeDef;
  17064. BfType* innerRetType = NULL;
  17065. BfTypeInstance* usingInterface = NULL;
  17066. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  17067. if (retTypeInst != NULL)
  17068. {
  17069. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  17070. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  17071. {
  17072. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  17073. }
  17074. }
  17075. if (innerRetType == NULL)
  17076. {
  17077. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  17078. return;
  17079. }
  17080. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  17081. if (blockBody == NULL)
  17082. return;
  17083. }
  17084. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  17085. {
  17086. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17087. if (gcType == NULL)
  17088. return;
  17089. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  17090. if (!markFromGCThreadMethodInstance)
  17091. return;
  17092. SizedArray<BfIRValue, 1> args;
  17093. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  17094. BfExprEvaluator exprEvaluator(this);
  17095. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  17096. }
  17097. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  17098. {
  17099. auto fieldType = markVal.mType;
  17100. auto fieldTypeInst = fieldType->ToTypeInstance();
  17101. if (fieldType == NULL)
  17102. return;
  17103. if (!markVal.mType->IsComposite())
  17104. markVal = LoadValue(markVal);
  17105. BfExprEvaluator exprEvaluator(this);
  17106. PopulateType(markVal.mType, BfPopulateType_Data);
  17107. if (markVal.mType->IsObjectOrInterface())
  17108. {
  17109. BfIRValue val = markVal.mValue;
  17110. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  17111. SizedArray<BfIRValue, 1> args;
  17112. args.push_back(val);
  17113. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  17114. }
  17115. else if (fieldType->IsSizedArray())
  17116. {
  17117. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  17118. if (sizedArrayType->mElementType->WantsGCMarking())
  17119. {
  17120. BfTypedValue arrayValue = markVal;
  17121. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17122. auto itr = CreateAlloca(intPtrType);
  17123. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17124. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17125. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17126. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17127. mBfIRBuilder->CreateBr(loopBB);
  17128. mBfIRBuilder->SetInsertPoint(loopBB);
  17129. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17130. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17131. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17132. mBfIRBuilder->SetInsertPoint(bodyBB);
  17133. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17134. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17135. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17136. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17137. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17138. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17139. mBfIRBuilder->CreateStore(incValue, itr);
  17140. mBfIRBuilder->CreateBr(loopBB);
  17141. mBfIRBuilder->SetInsertPoint(doneBB);
  17142. }
  17143. }
  17144. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  17145. {
  17146. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  17147. if (markMemberMethodInstance)
  17148. {
  17149. SizedArray<BfIRValue, 1> args;
  17150. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  17151. if (markVal.mType != methodOwner)
  17152. markVal = Cast(NULL, markVal, methodOwner);
  17153. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  17154. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  17155. }
  17156. }
  17157. }
  17158. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  17159. {
  17160. Array<BfMethodInstance*> methodInstances;
  17161. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17162. {
  17163. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  17164. auto chainedMethodInst = methodInstGroup.mDefault;
  17165. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  17166. {
  17167. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  17168. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  17169. {
  17170. methodInstances.push_back(chainedMethodInst);
  17171. }
  17172. }
  17173. }
  17174. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  17175. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  17176. {
  17177. bool isBetter;
  17178. bool isWorse;
  17179. CompareDeclTypes(mCurTypeInstance, lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  17180. if (isBetter == isWorse)
  17181. {
  17182. return false;
  17183. }
  17184. return isWorse;
  17185. });
  17186. if (reverse)
  17187. std::reverse(methodInstances.begin(), methodInstances.end());
  17188. for (auto chainedMethodInst : methodInstances)
  17189. {
  17190. auto declModule = this;
  17191. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  17192. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  17193. BfExprEvaluator exprEvaluator(this);
  17194. SizedArray<BfIRValue, 1> args;
  17195. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  17196. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  17197. }
  17198. }
  17199. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  17200. {
  17201. BF_ASSERT(mCurMethodInstance->mIsReified);
  17202. if (mCurTypeInstance->mHotTypeData == NULL)
  17203. {
  17204. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  17205. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  17206. }
  17207. auto hotMethod = mCurMethodInstance->mHotMethod;
  17208. for (auto depData : hotMethod->mReferences)
  17209. {
  17210. // Only virtual decls are allowed to already be there
  17211. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  17212. }
  17213. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  17214. int prevSize = (int)hotMethod->mReferences.size();
  17215. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  17216. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17217. refCount++;
  17218. hotMethod->mReferences.Reserve(refCount);
  17219. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  17220. {
  17221. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  17222. hotThis->mRefCount++;
  17223. hotMethod->mReferences.Insert(0, hotThis);
  17224. prevSize++;
  17225. }
  17226. for (auto val : builder->mAllocatedData)
  17227. {
  17228. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  17229. hotMethod->mReferences.Add(hotAllocation);
  17230. }
  17231. for (auto val : builder->mUsedData)
  17232. hotMethod->mReferences.Add(val);
  17233. for (auto val : builder->mCalledMethods)
  17234. hotMethod->mReferences.Add(val);
  17235. for (auto val : builder->mDevirtualizedCalledMethods)
  17236. {
  17237. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  17238. hotMethod->mReferences.Add(devirtualizedMethod);
  17239. }
  17240. for (auto val : builder->mFunctionPtrs)
  17241. {
  17242. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  17243. hotMethod->mReferences.Add(funcRef);
  17244. }
  17245. for (auto val : builder->mInnerMethods)
  17246. {
  17247. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  17248. hotMethod->mReferences.Add(innerMethod);
  17249. }
  17250. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  17251. {
  17252. auto depData = hotMethod->mReferences[refIdx];
  17253. BF_ASSERT(depData != NULL);
  17254. depData->mRefCount++;
  17255. }
  17256. }
  17257. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  17258. {
  17259. auto methodDef = methodInstance->mMethodDef;
  17260. auto methodDeclaration = methodDef->mMethodDeclaration;
  17261. bool isThisStruct = false;
  17262. if (thisType != NULL)
  17263. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  17264. int argIdx = 0;
  17265. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17266. argIdx++;
  17267. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17268. if (!methodDef->mIsStatic)
  17269. {
  17270. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17271. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17272. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17273. paramVar->mIsBumpAlloc = true;
  17274. paramVar->mResolvedType = thisType;
  17275. paramVar->mName.Reference("this");
  17276. if (!thisType->IsValuelessType())
  17277. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17278. else
  17279. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17280. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  17281. {
  17282. if (!thisType->IsTypedPrimitive())
  17283. paramVar->mIsSplat = true;
  17284. }
  17285. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (!methodInstance->ForcingThisPtr()))
  17286. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17287. auto thisTypeInst = thisType->ToTypeInstance();
  17288. paramVar->mIsStruct = isThisStruct;
  17289. paramVar->mAddr = BfIRValue();
  17290. paramVar->mIsThis = true;
  17291. paramVar->mParamIdx = -1;
  17292. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  17293. {
  17294. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  17295. }
  17296. else
  17297. {
  17298. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17299. }
  17300. paramVar->mReadFromId = -1;
  17301. paramVar->Init();
  17302. if (methodDeclaration == NULL)
  17303. UseDefaultSrcPos();
  17304. AddLocalVariableDef(paramVar);
  17305. if (!thisType->IsValuelessType())
  17306. {
  17307. if (wantsDIData)
  17308. {
  17309. BfType* thisPtrType = thisType;
  17310. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  17311. if (!thisType->IsValueType())
  17312. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17313. else if (!paramVar->mIsSplat)
  17314. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  17315. diParams->push_back(diType);
  17316. }
  17317. if (paramVar->mIsSplat)
  17318. {
  17319. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17320. }
  17321. else
  17322. {
  17323. argIdx++;
  17324. if (loweredTypeCode2 != BfTypeCode_None)
  17325. argIdx++;
  17326. }
  17327. }
  17328. }
  17329. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17330. argIdx++;
  17331. bool hadParams = false;
  17332. bool hasDefault = false;
  17333. int compositeVariableIdx = -1;
  17334. int paramIdx = 0;
  17335. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  17336. {
  17337. // We already issues a type error for this param if we had one in declaration processing
  17338. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17339. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  17340. paramVar->mIsBumpAlloc = true;
  17341. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17342. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17343. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  17344. auto resolvedType = methodInstance->GetParamType(paramIdx);
  17345. if (resolvedType == NULL)
  17346. {
  17347. AssertErrorState();
  17348. paramVar->mParamFailed = true;
  17349. }
  17350. prevIgnoreErrors.Restore();
  17351. PopulateType(resolvedType, BfPopulateType_Declaration);
  17352. paramVar->mResolvedType = resolvedType;
  17353. int namePrefixCount = 0;
  17354. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  17355. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  17356. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  17357. if (!isParamSkipped)
  17358. {
  17359. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  17360. if (resolvedType->IsMethodRef())
  17361. {
  17362. paramVar->mIsSplat = true;
  17363. }
  17364. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  17365. {
  17366. if (methodInstance->AllowsSplatting(paramIdx))
  17367. {
  17368. auto resolveTypeInst = resolvedType->ToTypeInstance();
  17369. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  17370. paramVar->mIsSplat = true;
  17371. else
  17372. {
  17373. int splatCount = resolvedType->GetSplatCount();
  17374. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  17375. paramVar->mIsSplat = true;
  17376. }
  17377. }
  17378. }
  17379. }
  17380. else
  17381. {
  17382. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  17383. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  17384. }
  17385. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  17386. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  17387. paramVar->mParamIdx = paramIdx;
  17388. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  17389. paramVar->mReadFromId = 0;
  17390. if (resolvedType->IsRef())
  17391. {
  17392. auto refType = (BfRefType*)resolvedType;
  17393. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  17394. if (refType->mRefKind == BfRefType::RefKind_In)
  17395. {
  17396. paramVar->mIsReadOnly = true;
  17397. }
  17398. }
  17399. else
  17400. {
  17401. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  17402. if (methodDef->mMethodType != BfMethodType_Mixin)
  17403. paramVar->mIsReadOnly = true;
  17404. }
  17405. if (paramVar->mResolvedType->IsGenericParam())
  17406. {
  17407. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  17408. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  17409. {
  17410. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  17411. paramVar->mResolvedType = typedVal.mType;
  17412. paramVar->mConstValue = typedVal.mValue;
  17413. }
  17414. }
  17415. if (paramVar->mResolvedType->IsConstExprValue())
  17416. {
  17417. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  17418. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  17419. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  17420. BF_ASSERT(unspecParamType->IsGenericParam());
  17421. if (unspecParamType->IsGenericParam())
  17422. {
  17423. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  17424. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  17425. {
  17426. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  17427. if (genericParamInst->mTypeConstraint != NULL)
  17428. {
  17429. BfExprEvaluator exprEvaluator(this);
  17430. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  17431. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  17432. auto checkType = genericParamInst->mTypeConstraint;
  17433. if (checkType->IsTypedPrimitive())
  17434. checkType = checkType->GetUnderlyingType();
  17435. auto typedVal = exprEvaluator.mResult;
  17436. if ((typedVal) && (typedVal.mType != checkType))
  17437. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  17438. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  17439. {
  17440. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17441. paramVar->mConstValue = typedVal.mValue;
  17442. BF_ASSERT(paramVar->mConstValue.IsConst());
  17443. paramVar->mIsConst = true;
  17444. }
  17445. else
  17446. {
  17447. AssertErrorState();
  17448. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  17449. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  17450. paramVar->mIsConst = true;
  17451. }
  17452. if (paramVar->mResolvedType->IsObject())
  17453. {
  17454. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  17455. FixValueActualization(typedVal);
  17456. if (typedVal.mValue.IsConst())
  17457. paramVar->mConstValue = typedVal.mValue;
  17458. }
  17459. }
  17460. }
  17461. }
  17462. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  17463. if (paramVar->mResolvedType->IsConstExprValue())
  17464. {
  17465. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  17466. //AssertErrorState();
  17467. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  17468. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  17469. paramVar->mIsConst = true;
  17470. }
  17471. }
  17472. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  17473. {
  17474. if (compositeVariableIdx == -1)
  17475. {
  17476. auto paramInst = &methodInstance->mParams[paramIdx];
  17477. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  17478. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  17479. BfLocalVariable* localVar = new BfLocalVariable();
  17480. localVar->mName = paramDef->mName;
  17481. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  17482. if (paramDef->mTypeRef != NULL)
  17483. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17484. if (localVar->mResolvedType == NULL)
  17485. localVar->mResolvedType = GetPrimitiveType(BfTypeCode_None);
  17486. localVar->mCompositeCount = 0;
  17487. DoAddLocalVariable(localVar);
  17488. }
  17489. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  17490. paramVar->mIsImplicitParam = true;
  17491. }
  17492. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  17493. {
  17494. if ((paramVar->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)paramVar->mResolvedType)->mModifiedKind == BfToken_Params))
  17495. {
  17496. paramVar->mValue = BfIRValue();
  17497. paramVar->mCompositeCount = 0;
  17498. paramVar->mIsSplat = false;
  17499. }
  17500. }
  17501. if (!mCurTypeInstance->IsDelegateOrFunction())
  17502. CheckVariableDef(paramVar);
  17503. paramVar->Init();
  17504. AddLocalVariableDef(paramVar);
  17505. if (!isParamSkipped)
  17506. {
  17507. if (wantsDIData)
  17508. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  17509. if (paramVar->mIsSplat)
  17510. {
  17511. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17512. }
  17513. else
  17514. {
  17515. argIdx++;
  17516. }
  17517. if (loweredTypeCode2 != BfTypeCode_None)
  17518. argIdx++;
  17519. }
  17520. }
  17521. // Try to find an ending delegate params composite
  17522. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  17523. {
  17524. auto paramDef = methodDef->mParams.back();
  17525. if (paramDef->mParamKind == BfParamKind_Params)
  17526. {
  17527. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  17528. if (paramsType == NULL)
  17529. {
  17530. // Had error or 'var'
  17531. }
  17532. else if (paramsType->IsGenericParam())
  17533. {
  17534. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  17535. if (genericParamInstance->mTypeConstraint != NULL)
  17536. {
  17537. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17538. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  17539. ((typeInstConstraint != NULL) &&
  17540. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  17541. {
  17542. bool doAdd = true;
  17543. // TODO: Remove
  17544. if (!mCurMethodState->mLocals.IsEmpty())
  17545. {
  17546. auto checkVar = mCurMethodState->mLocals.back();
  17547. if (checkVar->mName == paramDef->mName)
  17548. doAdd = false;
  17549. }
  17550. if (doAdd)
  17551. {
  17552. BfLocalVariable* localVar = new BfLocalVariable();
  17553. localVar->mName = paramDef->mName;
  17554. localVar->mResolvedType = paramsType;
  17555. localVar->mCompositeCount = 0;
  17556. DoAddLocalVariable(localVar);
  17557. }
  17558. }
  17559. }
  17560. }
  17561. else if (paramsType->IsDelegate())
  17562. {
  17563. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  17564. if (invokeMethodInstance != NULL)
  17565. {
  17566. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  17567. // and wasn't cleared by the preceding loop
  17568. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  17569. BfLocalVariable* localVar = new BfLocalVariable();
  17570. localVar->mName = paramDef->mName;
  17571. localVar->mResolvedType = paramsType;
  17572. localVar->mCompositeCount = 0;
  17573. DoAddLocalVariable(localVar);
  17574. }
  17575. }
  17576. }
  17577. }
  17578. }
  17579. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  17580. {
  17581. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  17582. // return;
  17583. auto startMethodState = mCurMethodState;
  17584. auto _ClearState = [&]()
  17585. {
  17586. mCurMethodState->mLocalMethods.Clear();
  17587. for (auto& local : mCurMethodState->mLocals)
  17588. {
  17589. if (local->mIsBumpAlloc)
  17590. local->~BfLocalVariable();
  17591. else
  17592. delete local;
  17593. }
  17594. mCurMethodState->mLocals.Clear();
  17595. mCurMethodState->mLocalVarSet.Clear();
  17596. };
  17597. while (true)
  17598. {
  17599. bool didWork = false;
  17600. // 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
  17601. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  17602. // however (compiler bug), so this is the safest way
  17603. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  17604. {
  17605. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  17606. {
  17607. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  17608. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  17609. if (!mHadBuildError)
  17610. {
  17611. // Process as a closure - that allows us to look back and see the const locals and stuff
  17612. BfClosureState closureState;
  17613. mCurMethodState->mClosureState = &closureState;
  17614. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17615. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  17616. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  17617. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  17618. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  17619. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17620. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  17621. _ClearState();
  17622. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  17623. {
  17624. auto localVar = new BfLocalVariable();
  17625. *localVar = constLocal;
  17626. DoAddLocalVariable(localVar);
  17627. }
  17628. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  17629. bool doProcess = !mCompiler->mCanceling;
  17630. if (doProcess)
  17631. {
  17632. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  17633. ProcessMethod(deferredLocalMethod->mMethodInstance);
  17634. }
  17635. }
  17636. delete deferredLocalMethod;
  17637. mContext->CheckLockYield();
  17638. didWork = true;
  17639. }
  17640. mCurMethodState->mDeferredLocalMethods.Clear();
  17641. }
  17642. for (auto& kv : mCurMethodState->mLocalMethodCache)
  17643. {
  17644. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  17645. }
  17646. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  17647. {
  17648. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  17649. {
  17650. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  17651. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  17652. BfClosureState closureState;
  17653. mCurMethodState->mClosureState = &closureState;
  17654. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  17655. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  17656. if (lambdaInstance->mClosureTypeInstance != NULL)
  17657. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  17658. else
  17659. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  17660. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17661. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  17662. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  17663. _ClearState();
  17664. for (auto& constLocal : lambdaInstance->mConstLocals)
  17665. {
  17666. //if (constLocal.mIsThis)
  17667. {
  17668. // Valueless 'this'
  17669. closureState.mConstLocals.Add(constLocal);
  17670. }
  17671. /*else
  17672. {
  17673. auto localVar = new BfLocalVariable();
  17674. *localVar = constLocal;
  17675. DoAddLocalVariable(localVar);
  17676. }*/
  17677. }
  17678. BfMethodInstanceGroup methodInstanceGroup;
  17679. methodInstanceGroup.mOwner = mCurTypeInstance;
  17680. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17681. bool doProcess = !mCompiler->mCanceling;
  17682. if (doProcess)
  17683. {
  17684. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  17685. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17686. ProcessMethod(lambdaInstance->mMethodInstance);
  17687. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  17688. if (lambdaInstance->mDtorMethodInstance != NULL)
  17689. {
  17690. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  17691. auto startMethodState2 = mCurMethodState;
  17692. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  17693. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  17694. }
  17695. }
  17696. didWork = true;
  17697. }
  17698. mContext->CheckLockYield();
  17699. mCurMethodState->mDeferredLambdaInstances.Clear();
  17700. }
  17701. if (!didWork)
  17702. break;
  17703. }
  17704. }
  17705. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  17706. {
  17707. if (checkType->IsComposite())
  17708. PopulateType(checkType, BfPopulateType_Data);
  17709. if (!checkType->WantsGCMarking())
  17710. return;
  17711. if (checkType->IsDeleting())
  17712. {
  17713. mCompiler->RequestExtraCompile();
  17714. InternalError("EmitGCMarkValue deleted type");
  17715. return;
  17716. }
  17717. auto typeInstance = checkType->ToTypeInstance();
  17718. bool callMarkMethod = false;
  17719. // Call the actual marking method
  17720. if (memberDepth == 0)
  17721. {
  17722. // Don't call marking method on self
  17723. }
  17724. else if (checkType->IsObjectOrInterface())
  17725. {
  17726. if (!objectOffsets.Add(curOffset))
  17727. {
  17728. return;
  17729. }
  17730. callMarkMethod = true;
  17731. }
  17732. else if (checkType->IsSizedArray())
  17733. {
  17734. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  17735. if (sizedArrayType->mElementType->WantsGCMarking())
  17736. {
  17737. BfTypedValue arrayValue = thisValue;
  17738. if (thisValue.mType != checkType)
  17739. {
  17740. BfIRValue srcValue = thisValue.mValue;
  17741. if (curOffset != 0)
  17742. {
  17743. if (!thisValue.mType->IsPointer())
  17744. {
  17745. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17746. auto int8PtrType = CreatePointerType(int8Type);
  17747. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  17748. }
  17749. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  17750. }
  17751. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  17752. }
  17753. if (sizedArrayType->mElementCount > 6)
  17754. {
  17755. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  17756. auto itr = CreateAlloca(intPtrType);
  17757. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  17758. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  17759. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  17760. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  17761. mBfIRBuilder->CreateBr(loopBB);
  17762. mBfIRBuilder->SetInsertPoint(loopBB);
  17763. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  17764. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  17765. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  17766. mBfIRBuilder->SetInsertPoint(bodyBB);
  17767. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17768. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17769. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  17770. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17771. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17772. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  17773. mBfIRBuilder->CreateStore(incValue, itr);
  17774. mBfIRBuilder->CreateBr(loopBB);
  17775. mBfIRBuilder->SetInsertPoint(doneBB);
  17776. }
  17777. else
  17778. {
  17779. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  17780. {
  17781. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  17782. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  17783. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  17784. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  17785. HashSet<int> objectOffsets;
  17786. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  17787. }
  17788. }
  17789. }
  17790. }
  17791. else if (typeInstance != NULL)
  17792. {
  17793. typeInstance->mTypeDef->PopulateMemberSets();
  17794. BfMemberSetEntry* entry = NULL;
  17795. BfMethodDef* methodDef = NULL;
  17796. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  17797. {
  17798. methodDef = (BfMethodDef*)entry->mMemberDef;
  17799. if (methodDef->HasBody())
  17800. {
  17801. callMarkMethod = true;
  17802. }
  17803. }
  17804. }
  17805. if (callMarkMethod)
  17806. {
  17807. BfTypedValue markValue;
  17808. auto memberType = checkType;
  17809. if (memberType->IsObjectOrInterface())
  17810. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  17811. auto memberPtrType = CreatePointerType(memberType);
  17812. if (curOffset == 0)
  17813. {
  17814. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17815. }
  17816. else
  17817. {
  17818. if (!thisValue.mType->IsPointer())
  17819. {
  17820. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  17821. auto int8PtrType = CreatePointerType(int8Type);
  17822. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  17823. }
  17824. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  17825. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  17826. }
  17827. if (isAppendObject)
  17828. EmitGCMarkAppended(markValue);
  17829. else
  17830. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17831. return;
  17832. }
  17833. auto methodDef = mCurMethodInstance->mMethodDef;
  17834. if (checkType->IsPayloadEnum())
  17835. {
  17836. for (auto& fieldInst : typeInstance->mFieldInstances)
  17837. {
  17838. if (!fieldInst.mIsEnumPayloadCase)
  17839. continue;
  17840. auto fieldDef = fieldInst.GetFieldDef();
  17841. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17842. }
  17843. return;
  17844. }
  17845. if (typeInstance == NULL)
  17846. return;
  17847. for (auto& fieldInst : typeInstance->mFieldInstances)
  17848. {
  17849. auto fieldDef = fieldInst.GetFieldDef();
  17850. if (fieldDef == NULL)
  17851. continue;
  17852. if (fieldDef->mIsStatic)
  17853. continue;
  17854. if (typeInstance == mCurTypeInstance)
  17855. {
  17856. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  17857. // we may be marking member values that can never contain a value anyway, but this is benign
  17858. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17859. continue;
  17860. }
  17861. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  17862. }
  17863. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  17864. {
  17865. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  17866. }
  17867. }
  17868. void BfModule::EmitGCMarkMembers()
  17869. {
  17870. auto methodDef = mCurMethodInstance->mMethodDef;
  17871. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  17872. BfModuleMethodInstance markFromGCThreadMethodInstance;
  17873. if (gcType != NULL)
  17874. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  17875. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  17876. {
  17877. if (mCurTypeInstance->IsBoxed())
  17878. {
  17879. // This already gets filled in by the normal boxed forwarding
  17880. }
  17881. else
  17882. {
  17883. auto thisValue = GetThis();
  17884. if (thisValue.IsSplat())
  17885. {
  17886. BfIRFunction func = mCurMethodInstance->mIRFunction;
  17887. int argIdx = 0;
  17888. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  17889. {
  17890. if (checkType->IsStruct())
  17891. {
  17892. auto checkTypeInstance = checkType->ToTypeInstance();
  17893. if (checkTypeInstance->mBaseType != NULL)
  17894. checkTypeLambda(checkTypeInstance->mBaseType);
  17895. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  17896. {
  17897. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  17898. if (fieldInstance->mDataIdx >= 0)
  17899. checkTypeLambda(fieldInstance->GetResolvedType());
  17900. }
  17901. }
  17902. else if (checkType->IsMethodRef())
  17903. {
  17904. BFMODULE_FATAL(this, "Not handled");
  17905. }
  17906. else if (checkType->WantsGCMarking())
  17907. {
  17908. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  17909. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  17910. argIdx++;
  17911. }
  17912. };
  17913. checkTypeLambda(thisValue.mType);
  17914. }
  17915. else if (!methodDef->mIsStatic)
  17916. {
  17917. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  17918. {
  17919. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  17920. if (moduleMethodInst)
  17921. {
  17922. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  17923. bool wantsBaseMarking = true;
  17924. if (methodBaseType == mContext->mBfObjectType)
  17925. {
  17926. wantsBaseMarking = false;
  17927. PopulateType(methodBaseType);
  17928. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  17929. {
  17930. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  17931. (fieldInstance.mResolvedType->WantsGCMarking()))
  17932. wantsBaseMarking = true;
  17933. }
  17934. }
  17935. if (wantsBaseMarking)
  17936. {
  17937. auto thisValue = GetThis();
  17938. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  17939. SizedArray<BfIRValue, 1> args;
  17940. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  17941. {
  17942. BfExprEvaluator exprEvaluator(this);
  17943. exprEvaluator.SplatArgs(baseValue, args);
  17944. }
  17945. else
  17946. {
  17947. args.push_back(baseValue.mValue);
  17948. }
  17949. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  17950. }
  17951. }
  17952. }
  17953. }
  17954. if (!methodDef->mIsStatic)
  17955. {
  17956. HashSet<int> objectOffsets;
  17957. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  17958. }
  17959. else
  17960. {
  17961. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  17962. {
  17963. if (thisValue.IsSplat())
  17964. break;
  17965. auto fieldDef = fieldInst.GetFieldDef();
  17966. if (fieldDef == NULL)
  17967. continue;
  17968. if (IsThreadLocal(&fieldInst))
  17969. continue;
  17970. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  17971. {
  17972. // For extensions, only handle these fields in the appropriate extension
  17973. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  17974. continue;
  17975. if (!fieldInst.mFieldIncluded)
  17976. continue;
  17977. auto fieldType = fieldInst.mResolvedType;
  17978. auto fieldDef = fieldInst.GetFieldDef();
  17979. BfTypedValue markVal;
  17980. if (fieldDef->mIsConst)
  17981. continue;
  17982. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  17983. continue;
  17984. mBfIRBuilder->PopulateType(fieldType);
  17985. if (fieldType->IsValuelessType())
  17986. continue;
  17987. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  17988. {
  17989. StringT<512> staticVarName;
  17990. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  17991. if (staticVarName.StartsWith('#'))
  17992. continue;
  17993. markVal = ReferenceStaticField(&fieldInst);
  17994. }
  17995. else if (!fieldDef->mIsStatic)
  17996. {
  17997. if (fieldInst.IsAppendedObject())
  17998. {
  17999. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  18000. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  18001. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  18002. }
  18003. else
  18004. {
  18005. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  18006. }
  18007. }
  18008. if (markVal)
  18009. {
  18010. if ((fieldInst.IsAppendedObject()) && (!fieldDef->mIsStatic))
  18011. EmitGCMarkAppended(markVal);
  18012. else
  18013. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  18014. }
  18015. }
  18016. }
  18017. }
  18018. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  18019. CallChainedMethods(mCurMethodInstance, false);
  18020. }
  18021. }
  18022. // If there are appends then we just need the rootmost append type to do the Dbg_MarkAppended
  18023. if ((!mIsComptimeModule) && (!methodDef->mIsStatic) && (mCompiler->mOptions.mDebugAlloc) &&
  18024. (mCurTypeInstance->HasAppendCtor()) && (!mCurTypeInstance->BaseHasAppendCtor()))
  18025. {
  18026. auto thisValue = GetThis();
  18027. auto appendedObj = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  18028. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_MarkAppended", 1);
  18029. SizedArray<BfIRValue, 1> llvmArgs;
  18030. llvmArgs.push_back(appendedObj);
  18031. if (allocMethod)
  18032. mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  18033. }
  18034. }
  18035. void BfModule::EmitGCFindTLSMembers()
  18036. {
  18037. auto methodDef = mCurMethodInstance->mMethodDef;
  18038. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  18039. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  18040. BF_ASSERT(reportTLSMark);
  18041. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  18042. {
  18043. auto fieldDef = fieldInst.GetFieldDef();
  18044. if (fieldDef == NULL)
  18045. continue;
  18046. if (!IsThreadLocal(&fieldInst))
  18047. continue;
  18048. // For extensions, only handle these fields in the appropriate extension
  18049. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  18050. continue;
  18051. if (!fieldInst.mFieldIncluded)
  18052. continue;
  18053. if (fieldDef->mIsConst)
  18054. continue;
  18055. auto fieldType = fieldInst.mResolvedType;
  18056. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  18057. continue;
  18058. if (fieldType->IsValuelessType())
  18059. continue;
  18060. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  18061. if (markVal)
  18062. {
  18063. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  18064. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  18065. SizedArray<BfIRValue, 2> llvmArgs;
  18066. llvmArgs.push_back(fieldRefPtr);
  18067. llvmArgs.push_back(markFuncPtr);
  18068. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  18069. }
  18070. }
  18071. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  18072. CallChainedMethods(mCurMethodInstance, false);
  18073. }
  18074. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  18075. {
  18076. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  18077. if (mIsComptimeModule)
  18078. {
  18079. BF_ASSERT(!mCompiler->IsAutocomplete());
  18080. }
  18081. if (mAwaitingInitFinish)
  18082. FinishInit();
  18083. if ((methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  18084. {
  18085. BfLogSysM("REIFIED(ProcessMethod): %s %p Module: %s\n", methodInstance->mMethodDef->mName.c_str(), methodInstance, mModuleName.c_str());
  18086. }
  18087. // Reify types that are actually used - they don't get reified during method declaration
  18088. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  18089. {
  18090. auto _CheckType = [&](BfType* type)
  18091. {
  18092. if (!type->IsReified())
  18093. PopulateType(type, BfPopulateType_Declaration);
  18094. };
  18095. _CheckType(methodInstance->mReturnType);
  18096. for (auto& param : methodInstance->mParams)
  18097. {
  18098. _CheckType(param.mResolvedType);
  18099. }
  18100. }
  18101. if (!methodInstance->mIsReified)
  18102. BF_ASSERT(!mIsReified);
  18103. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  18104. if (methodInstance->mMethodInfoEx != NULL)
  18105. {
  18106. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18107. {
  18108. if (methodGenericArg->IsMethodRef())
  18109. {
  18110. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  18111. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  18112. }
  18113. }
  18114. }
  18115. if (mBfIRBuilder == NULL)
  18116. {
  18117. BfLogSysM("ProcessMethod %p calling EnsureIRBuilder\n", methodInstance);
  18118. EnsureIRBuilder();
  18119. }
  18120. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  18121. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  18122. {
  18123. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  18124. }
  18125. SetAndRestoreValue<bool> prevIsClassifying;
  18126. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  18127. (mCompiler->mResolvePassData != NULL))
  18128. {
  18129. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  18130. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  18131. }
  18132. if (methodInstance->mHasBeenProcessed)
  18133. {
  18134. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  18135. return;
  18136. }
  18137. if (methodInstance->mFailedConstraints)
  18138. {
  18139. // The only way this should be able to happen is if we fail our generic param check
  18140. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  18141. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  18142. methodInstance->mHasBeenProcessed = true;
  18143. return;
  18144. }
  18145. if (HasExecutedOutput())
  18146. {
  18147. BF_ASSERT(mIsModuleMutable);
  18148. }
  18149. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  18150. if (!mIsComptimeModule)
  18151. {
  18152. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  18153. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  18154. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  18155. {
  18156. auto owningModule = methodInstance->GetOwner()->mModule;
  18157. if (owningModule->mIsScratchModule)
  18158. {
  18159. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  18160. }
  18161. else
  18162. {
  18163. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  18164. if (owningModule->mOnDemandMethodCount > 0)
  18165. owningModule->mOnDemandMethodCount--;
  18166. }
  18167. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  18168. VerifyOnDemandMethods();
  18169. }
  18170. }
  18171. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  18172. // self-referencing append allocations in ctor@calcAppend
  18173. methodInstance->mHasBeenProcessed = true;
  18174. mIncompleteMethodCount--;
  18175. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  18176. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  18177. auto methodDef = methodInstance->mMethodDef;
  18178. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18179. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18180. mBfIRBuilder->mIgnoreWrites = true;
  18181. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  18182. {
  18183. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  18184. // so we get the new vdata for it
  18185. methodInstance->GetOwner()->mDirty = true;
  18186. }
  18187. int dependentGenericStartIdx = 0;
  18188. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  18189. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  18190. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  18191. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  18192. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  18193. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  18194. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  18195. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  18196. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  18197. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  18198. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  18199. {
  18200. mCurTypeInstance->mHasBeenInstantiated = true;
  18201. }
  18202. // Warnings are shown in the capture phase
  18203. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  18204. mIgnoreWarnings = true;
  18205. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  18206. UseDefaultSrcPos();
  18207. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  18208. {
  18209. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  18210. }
  18211. else
  18212. {
  18213. // We may not actually be populated in relatively rare autocompelte cases
  18214. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  18215. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  18216. }
  18217. BfAstNode* nameNode = NULL;
  18218. if (methodDeclaration != NULL)
  18219. {
  18220. nameNode = methodDeclaration->mNameNode;
  18221. if (nameNode == NULL)
  18222. {
  18223. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  18224. nameNode = ctorDeclaration->mThisToken;
  18225. }
  18226. }
  18227. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  18228. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  18229. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  18230. {
  18231. if (methodInstance->GetExplicitInterface() == NULL)
  18232. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  18233. else
  18234. {
  18235. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  18236. {
  18237. auto ifaceInst = ifaceEntry.mInterfaceType;
  18238. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  18239. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  18240. if (methodInstance->GetExplicitInterface() != ifaceInst)
  18241. continue;
  18242. ifaceInst->mTypeDef->PopulateMemberSets();
  18243. BfMethodDef* nextMethod = NULL;
  18244. BfMemberSetEntry* entry = NULL;
  18245. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18246. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18247. while (nextMethod != NULL)
  18248. {
  18249. auto checkMethod = nextMethod;
  18250. nextMethod = nextMethod->mNextWithSameName;
  18251. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  18252. if (implMethodInst == methodInstance)
  18253. {
  18254. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  18255. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  18256. }
  18257. }
  18258. }
  18259. }
  18260. if (methodDef->mIsOverride)
  18261. {
  18262. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  18263. {
  18264. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  18265. if (ventry.mDeclaringMethod.mMethodNum == -1)
  18266. continue;
  18267. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  18268. if (virtMethod != NULL)
  18269. {
  18270. if (virtMethod == methodInstance)
  18271. {
  18272. // Is matching method
  18273. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  18274. {
  18275. auto baseType = mCurTypeInstance->mBaseType;
  18276. if (baseType != NULL)
  18277. {
  18278. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  18279. baseType = baseType->mBaseType;
  18280. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  18281. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  18282. }
  18283. }
  18284. break;
  18285. }
  18286. }
  18287. }
  18288. }
  18289. }
  18290. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  18291. int importStrNum = -1;
  18292. auto importKind = methodInstance->GetImportKind();
  18293. if ((!mCompiler->mIsResolveOnly) &&
  18294. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  18295. {
  18296. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  18297. {
  18298. if (customAttr->mCtorArgs.size() == 1)
  18299. {
  18300. auto fileNameArg = customAttr->mCtorArgs[0];
  18301. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  18302. if (constant != NULL)
  18303. {
  18304. if (!constant->IsNull())
  18305. importStrNum = constant->mInt32;
  18306. }
  18307. else
  18308. {
  18309. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  18310. }
  18311. if (importStrNum != -1)
  18312. {
  18313. if (!mStringPoolRefs.Contains(importStrNum))
  18314. mStringPoolRefs.Add(importStrNum);
  18315. }
  18316. }
  18317. }
  18318. }
  18319. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  18320. {
  18321. if (mBfIRBuilder->mIgnoreWrites)
  18322. return;
  18323. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  18324. if (!methodInstance->mIRFunction)
  18325. {
  18326. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  18327. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  18328. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  18329. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  18330. }
  18331. if (HasCompiledOutput())
  18332. {
  18333. BfDllImportEntry dllImportEntry;
  18334. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  18335. dllImportEntry.mMethodInstance = mCurMethodInstance;
  18336. mDllImportEntries.push_back(dllImportEntry);
  18337. }
  18338. return;
  18339. }
  18340. auto _SanityCheckType = [&](BfType* type)
  18341. {
  18342. if ((type != NULL) && (type->IsDeleting()))
  18343. {
  18344. InternalError("Method references deleted type", methodDef->GetRefNode());
  18345. return false;
  18346. }
  18347. return true;
  18348. };
  18349. if (!_SanityCheckType(methodInstance->mReturnType))
  18350. return;
  18351. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  18352. if (!_SanityCheckType(methodInstance->GetParamType(paramIdx)))
  18353. return;
  18354. StringT<512> mangledName;
  18355. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18356. if (!methodInstance->mIRFunction)
  18357. {
  18358. bool isIntrinsic = false;
  18359. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  18360. }
  18361. if (methodInstance->mIsIntrinsic)
  18362. return;
  18363. if (mCurTypeInstance->IsFunction())
  18364. return;
  18365. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  18366. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  18367. if (methodDef->mBody != NULL)
  18368. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18369. else if (methodDeclaration != NULL)
  18370. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18371. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18372. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18373. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18374. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18375. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  18376. {
  18377. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  18378. {
  18379. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  18380. {
  18381. SetAndRestoreValue<bool> prevSkipAnonTypes(sourceClassifier->mSkipAnonymousTypes, true);
  18382. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  18383. }
  18384. }
  18385. }
  18386. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  18387. BfMethodState methodState;
  18388. if (mCurMethodState != NULL)
  18389. methodState.mClosureState = mCurMethodState->mClosureState;
  18390. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  18391. {
  18392. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  18393. if (methodInstance->mHotMethod == NULL)
  18394. CheckHotMethod(methodInstance, mangledName);
  18395. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  18396. }
  18397. methodState.mPrevMethodState = mCurMethodState;
  18398. methodState.mMethodInstance = methodInstance;
  18399. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18400. if (methodInstance->GetCustomAttributes() != NULL)
  18401. {
  18402. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  18403. if (typeOptionsIdx != -1)
  18404. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  18405. }
  18406. BfTypeState typeState(mCurTypeInstance);
  18407. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  18408. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  18409. BfMethodInstance* unspecializedMethodInstance = NULL;
  18410. if ((prevMethodState.mPrevVal != NULL) &&
  18411. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  18412. {
  18413. // This is 'inner' (probably a closure) - use binding from outer function
  18414. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  18415. }
  18416. else if ((methodInstance->mIsUnspecialized) ||
  18417. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  18418. {
  18419. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18420. }
  18421. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  18422. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  18423. {
  18424. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  18425. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  18426. {
  18427. // This will have already been populated by CeMachine
  18428. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18429. }
  18430. else
  18431. {
  18432. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  18433. if (!unspecializedMethodInstance->mHasBeenProcessed)
  18434. {
  18435. // Make sure the unspecialized method is processed so we can take its bindings
  18436. // Clear mCurMethodState so we don't think we're in a local method
  18437. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  18438. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  18439. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  18440. mContext->ProcessMethod(unspecializedMethodInstance);
  18441. }
  18442. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  18443. }
  18444. }
  18445. if (methodDef->mMethodType == BfMethodType_Operator)
  18446. {
  18447. auto operatorDef = (BfOperatorDef*) methodDef;
  18448. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  18449. auto paramErrorRefNode = refNode;
  18450. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  18451. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  18452. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  18453. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  18454. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  18455. {
  18456. if (methodDef->mParams.size() != 2)
  18457. {
  18458. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  18459. }
  18460. else
  18461. {
  18462. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18463. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18464. checkParam0 = checkParam0->GetUnderlyingType();
  18465. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  18466. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  18467. checkParam1 = checkParam1->GetUnderlyingType();
  18468. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18469. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  18470. {
  18471. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  18472. }
  18473. }
  18474. BfType* wantType = NULL;
  18475. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  18476. {
  18477. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  18478. }
  18479. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  18480. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  18481. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  18482. }
  18483. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  18484. {
  18485. if (methodDef->mIsStatic)
  18486. {
  18487. if (methodDef->mParams.size() != 1)
  18488. {
  18489. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  18490. }
  18491. else
  18492. {
  18493. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18494. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18495. checkParam0 = checkParam0->GetUnderlyingType();
  18496. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  18497. {
  18498. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  18499. }
  18500. }
  18501. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  18502. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  18503. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  18504. {
  18505. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  18506. }
  18507. }
  18508. else
  18509. {
  18510. if (methodDef->mParams.size() != 0)
  18511. {
  18512. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  18513. }
  18514. if (!mCurMethodInstance->mReturnType->IsVoid())
  18515. {
  18516. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18517. }
  18518. }
  18519. }
  18520. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  18521. {
  18522. if (methodDef->mParams.size() != 1)
  18523. {
  18524. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  18525. }
  18526. if (!mCurMethodInstance->mReturnType->IsVoid())
  18527. {
  18528. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  18529. }
  18530. }
  18531. else // Conversion
  18532. {
  18533. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  18534. {
  18535. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  18536. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  18537. }
  18538. if (methodDef->mParams.size() != 1)
  18539. {
  18540. auto refNode = paramErrorRefNode;
  18541. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  18542. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  18543. Fail("Conversion operators must declare one parameter", refNode);
  18544. }
  18545. else if ((methodInstance->mMethodInfoEx == NULL) ||
  18546. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  18547. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  18548. {
  18549. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  18550. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  18551. checkParam0 = checkParam0->GetUnderlyingType();
  18552. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  18553. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  18554. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  18555. if (checkParam0 == mCurMethodInstance->mReturnType)
  18556. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  18557. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  18558. // happened here
  18559. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  18560. {
  18561. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  18562. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  18563. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  18564. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  18565. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  18566. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  18567. }
  18568. }
  18569. }
  18570. }
  18571. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  18572. if (methodDef->mMethodType == BfMethodType_Mixin)
  18573. wantsDIData = false;
  18574. if (mCurTypeInstance->IsUnspecializedType())
  18575. wantsDIData = false;
  18576. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  18577. wantsDIData = false;
  18578. bool wantsDIVariables = wantsDIData;
  18579. if (methodDef->mIsExtern)
  18580. wantsDIVariables = false;
  18581. SizedArray<BfIRMDNode, 8> diParams;
  18582. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  18583. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  18584. BfType* thisType = NULL;
  18585. if (!methodDef->mIsStatic)
  18586. {
  18587. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  18588. thisType = methodState.mClosureState->mClosureType;
  18589. else
  18590. thisType = mCurTypeInstance;
  18591. }
  18592. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18593. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  18594. //////////////////////////////////////////////////////////////////////////
  18595. //
  18596. {
  18597. if (methodDeclaration != NULL)
  18598. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18599. else if (methodDef->mBody != NULL)
  18600. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18601. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18602. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  18603. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18604. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  18605. }
  18606. BfIRMDNode diFunction;
  18607. if (wantsDIData)
  18608. {
  18609. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  18610. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  18611. int defLine = mCurFilePosition.mCurLine;
  18612. if (mDICompileUnit)
  18613. {
  18614. // Note: for comptime we need to ensure we don't force type population with DbgGetTypeInst here, as that
  18615. // can generate a CeMachine InitType circular data reference
  18616. int flags = 0;
  18617. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance, BfIRPopulateType_Identity);
  18618. if (methodDef->mProtection == BfProtection_Public)
  18619. flags = llvm::DINode::FlagPublic;
  18620. else if (methodDef->mProtection == BfProtection_Protected)
  18621. flags = llvm::DINode::FlagProtected;
  18622. else
  18623. flags = llvm::DINode::FlagPrivate;
  18624. if (methodDef->mIsOverride)
  18625. {
  18626. //flags |= llvm::DINode::FlagVirtual;
  18627. }
  18628. else if (methodDef->mIsVirtual)
  18629. flags |= llvm::DINode::FlagIntroducedVirtual;
  18630. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  18631. flags |= llvm::DINode::FlagStaticMember;
  18632. else
  18633. {
  18634. if ((mCurTypeInstance->IsValuelessType()) ||
  18635. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  18636. flags |= llvm::DINode::FlagStaticMember;
  18637. }
  18638. flags |= llvm::DINode::FlagPrototyped;
  18639. if (methodDef->mMethodType == BfMethodType_Ctor)
  18640. {
  18641. flags |= llvm::DINode::FlagArtificial;
  18642. }
  18643. auto llvmFunction = methodInstance->mIRFunction;
  18644. SizedArray<BfIRMDNode, 1> genericArgs;
  18645. SizedArray<BfIRValue, 1> genericConstValueArgs;
  18646. String methodName;
  18647. if (methodInstance->GetForeignType() != NULL)
  18648. {
  18649. methodName += TypeToString(methodInstance->GetForeignType());
  18650. methodName += ".";
  18651. }
  18652. if (methodInstance->GetExplicitInterface() != NULL)
  18653. {
  18654. methodName += TypeToString(methodInstance->GetExplicitInterface());
  18655. methodName += ".";
  18656. }
  18657. methodName += methodDef->mName;
  18658. if (methodInstance->GetNumGenericArguments() != 0)
  18659. {
  18660. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  18661. {
  18662. if (genericArg->IsConstExprValue())
  18663. {
  18664. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  18665. while (genericConstValueArgs.size() < genericArgs.size())
  18666. genericConstValueArgs.push_back(BfIRValue());
  18667. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  18668. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  18669. }
  18670. else
  18671. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  18672. }
  18673. methodName += "<";
  18674. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  18675. {
  18676. if (i > 0)
  18677. methodName += ", ";
  18678. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  18679. methodName += TypeToString(type);
  18680. }
  18681. methodName += ">";
  18682. }
  18683. if ((methodName.empty()) && (methodDeclaration != NULL))
  18684. {
  18685. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18686. {
  18687. methodName += "operator";
  18688. if (operatorDecl->mIsConvOperator)
  18689. {
  18690. methodName += " ";
  18691. methodName += TypeToString(methodInstance->mReturnType);
  18692. }
  18693. else if (operatorDecl->mOpTypeToken != NULL)
  18694. methodName += operatorDecl->mOpTypeToken->ToString();
  18695. }
  18696. }
  18697. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  18698. methodName += "$CHK";
  18699. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  18700. methodName += "$UCHK";
  18701. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18702. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18703. // defLine + 1, diFuncType, false, true,
  18704. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  18705. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  18706. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18707. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  18708. defLine + 1, diFuncType, false, true,
  18709. llvm::dwarf::DW_VIRTUALITY_none,
  18710. 0,
  18711. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  18712. }
  18713. else
  18714. {
  18715. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  18716. }
  18717. }
  18718. //////////////////////////////////////////////////////////////////////////
  18719. // Head and Init get rolled into Entry afterwards.
  18720. methodState.mIRFunction = methodInstance->mIRFunction;
  18721. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  18722. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  18723. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  18724. methodState.mCurScope->mDIScope = diFunction;
  18725. auto llvmEntryBlock = methodState.mIREntryBlock;
  18726. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  18727. if (methodDef->mName == "__MALFORMED")
  18728. {
  18729. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  18730. mBfIRBuilder->SetInsertPoint(newBlock);
  18731. }
  18732. if (methodDef->mBody != NULL)
  18733. {
  18734. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  18735. }
  18736. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  18737. {
  18738. // We want to be able to step into delegate invokes -- we actually step over them
  18739. if (methodDef->mName != "Invoke")
  18740. {
  18741. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18742. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  18743. }
  18744. }
  18745. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18746. mBfIRBuilder->ClearDebugLocation();
  18747. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  18748. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  18749. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  18750. {
  18751. int localIdx = 0;
  18752. int argIdx = 0;
  18753. Array<BfIRValue> splatAddrValues;
  18754. for ( ; argIdx < irParamCount; localIdx++)
  18755. {
  18756. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18757. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18758. isThis = false;
  18759. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  18760. {
  18761. argIdx++;
  18762. if (argIdx == irParamCount)
  18763. break;
  18764. }
  18765. BfLocalVariable* paramVar = NULL;
  18766. while (true)
  18767. {
  18768. BF_ASSERT(localIdx < methodState.mLocals.size());
  18769. paramVar = methodState.mLocals[localIdx];
  18770. if ((paramVar->mCompositeCount == -1) &&
  18771. (!paramVar->mIsConst) &&
  18772. ((!paramVar->mResolvedType->IsValuelessNonOpaqueType()) || (paramVar->mResolvedType->IsMethodRef())))
  18773. break;
  18774. localIdx++;
  18775. }
  18776. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  18777. {
  18778. paramVar->mIsReadOnly = true;
  18779. }
  18780. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  18781. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  18782. if (paramVar->mResolvedType->IsMethodRef())
  18783. wantsAddr = false;
  18784. // if ((methodDef->mHasAppend) && (argIdx == 1))
  18785. // {
  18786. // BF_ASSERT(paramVar->mName == "appendIdx");
  18787. // wantsAddr = true;
  18788. // }
  18789. if (paramVar->mIsSplat)
  18790. {
  18791. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18792. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18793. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18794. {
  18795. BfIRType splatIRType;
  18796. if (checkType->IsComposite())
  18797. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  18798. else
  18799. splatIRType = mBfIRBuilder->MapType(checkType);
  18800. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  18801. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  18802. if (!paramVar->mAddr)
  18803. paramVar->mAddr = allocaInst;
  18804. if (WantsLifetimes())
  18805. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18806. splatAddrValues.push_back(allocaInst);
  18807. }, paramVar->mResolvedType);
  18808. mBfIRBuilder->SetInsertPoint(prevInsert);
  18809. }
  18810. else if (isThis)
  18811. {
  18812. if (wantsAddr)
  18813. {
  18814. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18815. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18816. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  18817. if (paramVar->mIsSplat)
  18818. {
  18819. //
  18820. }
  18821. else
  18822. {
  18823. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  18824. if ((thisType->IsTypedPrimitive()) &&
  18825. ((methodDef->HasNoThisSplat()) || (methodInstance->ForcingThisPtr())))
  18826. wantPtr = true;
  18827. if (wantPtr)
  18828. {
  18829. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  18830. }
  18831. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  18832. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18833. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  18834. paramVar->mAddr = allocaInst;
  18835. if (WantsLifetimes())
  18836. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18837. }
  18838. mBfIRBuilder->SetInsertPoint(prevInsert);
  18839. }
  18840. }
  18841. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  18842. {
  18843. // Address doesn't change so we don't have to alloca it
  18844. BfIRType allocType;
  18845. int alignSize = mSystem->mPtrSize;
  18846. if (paramVar->mResolvedType->IsRef())
  18847. {
  18848. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18849. }
  18850. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  18851. {
  18852. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  18853. alignSize = paramVar->mResolvedType->mAlign;
  18854. }
  18855. else
  18856. {
  18857. paramVar->mHasLocalStructBacking = true;
  18858. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  18859. if (typeInst != NULL)
  18860. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  18861. else
  18862. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  18863. }
  18864. if (wantsAddr)
  18865. {
  18866. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  18867. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  18868. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18869. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  18870. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18871. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  18872. paramVar->mAddr = allocaInst;
  18873. mBfIRBuilder->SetInsertPoint(prevInsert);
  18874. if (WantsLifetimes())
  18875. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  18876. }
  18877. }
  18878. else if (wantsAddr)
  18879. {
  18880. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  18881. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  18882. paramVar->mAddr = allocaInst;
  18883. }
  18884. if (paramVar->mIsSplat)
  18885. {
  18886. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18887. }
  18888. else if (paramVar->mIsLowered)
  18889. {
  18890. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18891. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18892. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18893. argIdx++;
  18894. if (loweredTypeCode2 != BfTypeCode_None)
  18895. argIdx++;
  18896. }
  18897. else
  18898. {
  18899. argIdx++;
  18900. }
  18901. }
  18902. if (methodDef->mBody != NULL)
  18903. UpdateSrcPos(methodDef->mBody);
  18904. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  18905. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  18906. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  18907. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  18908. localIdx = 0;
  18909. argIdx = 0;
  18910. int splatAddrIdx = 0;
  18911. while (localIdx < (int)methodState.mLocals.size())
  18912. {
  18913. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  18914. argIdx++;
  18915. int curLocalIdx = localIdx++;
  18916. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  18917. if (paramVar->mIsConst)
  18918. continue;
  18919. if (!paramVar->IsParam())
  18920. continue;
  18921. if (paramVar->mCompositeCount != -1)
  18922. continue;
  18923. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  18924. if ((isThis) && (thisType->IsValuelessNonOpaqueType()))
  18925. isThis = false;
  18926. if (paramVar->mValue.IsArg())
  18927. BF_ASSERT(paramVar->mValue.mId == argIdx);
  18928. BfIRMDNode diVariable;
  18929. if (wantsDIData)
  18930. {
  18931. String paramName = paramVar->mName;
  18932. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18933. if (isThis)
  18934. {
  18935. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  18936. paramName = "__closure";
  18937. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18938. {
  18939. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18940. bool wantRef = paramVar->mResolvedType->IsComposite();
  18941. if ((paramVar->mResolvedType->IsTypedPrimitive()) &&
  18942. ((methodDef->HasNoThisSplat()) || (methodInstance->ForcingThisPtr())))
  18943. wantRef = true;
  18944. if (wantRef)
  18945. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18946. }
  18947. else if (!paramVar->mResolvedType->IsValueType())
  18948. {
  18949. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  18950. }
  18951. }
  18952. else
  18953. {
  18954. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  18955. {
  18956. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18957. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  18958. diType = mBfIRBuilder->DbgCreateConstType(diType);
  18959. }
  18960. }
  18961. if (!paramVar->mIsSplat)
  18962. {
  18963. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  18964. {
  18965. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  18966. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  18967. if ((constant != NULL) &&
  18968. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  18969. {
  18970. int64 writeVal = constant->mInt64;
  18971. if (constant->mTypeCode == BfTypeCode_Float)
  18972. {
  18973. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  18974. float floatVal = (float)constant->mDouble;
  18975. writeVal = *(uint32*)&floatVal;
  18976. }
  18977. if (writeVal < 0)
  18978. paramName += StrFormat("$_%llu", -writeVal);
  18979. else
  18980. paramName += StrFormat("$%llu", writeVal);
  18981. }
  18982. }
  18983. if (paramVar->mResolvedType->IsValuelessNonOpaqueType())
  18984. {
  18985. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  18986. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18987. }
  18988. else if (paramVar->mIsImplicitParam)
  18989. {
  18990. // Annotate this specially?
  18991. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18992. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18993. }
  18994. else
  18995. {
  18996. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  18997. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  18998. }
  18999. paramVar->mDbgVarInst = diVariable;
  19000. }
  19001. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  19002. {
  19003. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  19004. // {
  19005. // // Only add this placeholder if we don't have any values
  19006. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  19007. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19008. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  19009. // }
  19010. }
  19011. }
  19012. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  19013. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  19014. {
  19015. // Write our argument value into the .addr
  19016. mBfIRBuilder->ClearDebugLocation();
  19017. if (paramVar->mIsSplat)
  19018. {
  19019. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  19020. //
  19021. }
  19022. else
  19023. {
  19024. bool handled = false;
  19025. if (paramVar->mIsLowered)
  19026. {
  19027. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19028. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19029. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  19030. {
  19031. BfIRValue targetAddr = paramVar->mAddr;
  19032. bool isTempTarget = false;
  19033. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  19034. if (paramVar->mResolvedType->mSize < loweredSize)
  19035. {
  19036. isTempTarget = true;
  19037. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  19038. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  19039. BF_MAX(paramVar->mResolvedType->mAlign,
  19040. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  19041. }
  19042. // We have a lowered type coming in, so we have to cast the .addr before storing
  19043. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  19044. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  19045. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  19046. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  19047. if (loweredTypeCode2 != BfTypeCode_None)
  19048. {
  19049. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  19050. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  19051. BfIRValue primPtrVal2;
  19052. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  19053. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  19054. else
  19055. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  19056. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  19057. }
  19058. if (isTempTarget)
  19059. {
  19060. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  19061. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  19062. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  19063. }
  19064. // We don't want to allow directly using value
  19065. paramVar->mValue = BfIRValue();
  19066. handled = true;
  19067. }
  19068. else
  19069. {
  19070. BF_ASSERT("Expected lowered");
  19071. }
  19072. }
  19073. if (!handled)
  19074. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  19075. }
  19076. }
  19077. if (methodDef->mBody != NULL)
  19078. UpdateSrcPos(methodDef->mBody);
  19079. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19080. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19081. else if (methodDeclaration == NULL)
  19082. UseDefaultSrcPos();
  19083. // Write our argument value into the .addr
  19084. if (paramVar->mIsSplat)
  19085. {
  19086. int splatComponentIdx = 0;
  19087. auto curArgIdx = argIdx;
  19088. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  19089. {
  19090. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  19091. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  19092. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  19093. mBfIRBuilder->ClearDebugLocation(storeInst);
  19094. if (wantsDIData)
  19095. {
  19096. BfIRMDNode diType;
  19097. if (checkType->IsComposite())
  19098. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  19099. else
  19100. diType = mBfIRBuilder->DbgGetType(checkType);
  19101. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  19102. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19103. if (wantsDIVariables)
  19104. {
  19105. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  19106. }
  19107. }
  19108. curArgIdx++;
  19109. splatComponentIdx++;
  19110. };
  19111. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  19112. {
  19113. if (checkType->IsStruct())
  19114. {
  19115. auto checkTypeInstance = checkType->ToTypeInstance();
  19116. if (checkTypeInstance->mBaseType != NULL)
  19117. {
  19118. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  19119. }
  19120. if (checkTypeInstance->mIsUnion)
  19121. {
  19122. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  19123. if (!unionInnerType->IsValuelessType())
  19124. {
  19125. _FinishSplatsIterate(unionInnerType, name + "$u");
  19126. }
  19127. if (checkTypeInstance->IsEnum())
  19128. {
  19129. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  19130. _FinishSplatsIterate(dscrType, name + "$d");
  19131. }
  19132. }
  19133. else
  19134. {
  19135. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  19136. {
  19137. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  19138. auto fieldDef = fieldInstance->GetFieldDef();
  19139. if (fieldInstance->mDataIdx >= 0)
  19140. {
  19141. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  19142. }
  19143. }
  19144. }
  19145. }
  19146. else if (checkType->IsMethodRef())
  19147. {
  19148. auto methodRefType = (BfMethodRefType*)checkType;
  19149. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  19150. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  19151. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  19152. // {
  19153. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  19154. // if (!paramType->IsValuelessType())
  19155. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  19156. // }
  19157. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  19158. {
  19159. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  19160. String paramName = methodInstance->GetParamName(paramIdx);
  19161. if (paramName == "this")
  19162. paramName = "__this";
  19163. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  19164. {
  19165. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19166. }
  19167. else
  19168. {
  19169. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  19170. }
  19171. }
  19172. }
  19173. else if (!checkType->IsValuelessType())
  19174. {
  19175. _FinishSplats(checkType, name);
  19176. }
  19177. };
  19178. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  19179. if (!paramVar->mConstValue)
  19180. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  19181. }
  19182. BfIRValue declareCall;
  19183. if (diVariable)
  19184. {
  19185. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  19186. {
  19187. if (!paramVar->mAddr)
  19188. {
  19189. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  19190. {
  19191. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19192. {
  19193. // We don't need to set the location for this
  19194. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19195. }
  19196. }
  19197. else
  19198. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  19199. }
  19200. else
  19201. {
  19202. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  19203. }
  19204. }
  19205. }
  19206. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  19207. {
  19208. // We don't allow actually assignment to "this", so we just do a single load
  19209. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  19210. // we need to store it in the stack frame for debugging purposes
  19211. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  19212. mBfIRBuilder->ClearDebugLocation(loadedThis);
  19213. paramVar->mValue = loadedThis;
  19214. }
  19215. if ((wantsDIData) && (declareCall))
  19216. mBfIRBuilder->UpdateDebugLocation(declareCall);
  19217. if (paramVar->mIsSplat)
  19218. {
  19219. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  19220. }
  19221. else if (paramVar->mIsLowered)
  19222. {
  19223. argIdx++;
  19224. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19225. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19226. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19227. if (loweredTypeCode2 != BfTypeCode_None)
  19228. argIdx++;
  19229. }
  19230. else if ((isThis) && (paramVar->mResolvedType->IsOpaque()))
  19231. {
  19232. if ((methodDef->mIsMutating) || (methodInstance->ForcingThisPtr()))
  19233. argIdx++;
  19234. }
  19235. else if (!paramVar->mResolvedType->IsValuelessNonOpaqueType())
  19236. {
  19237. argIdx++;
  19238. }
  19239. }
  19240. if (wantsDIData)
  19241. {
  19242. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  19243. }
  19244. }
  19245. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  19246. {
  19247. auto paramVar = mCurMethodState->mLocals[varIdx];
  19248. // 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
  19249. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  19250. // if (paramVar->mIsSplat)
  19251. // {
  19252. // if (wantsDIVariables)
  19253. // {
  19254. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  19255. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  19256. // }
  19257. // }
  19258. if (paramVar->mResolvedType->IsValuelessType())
  19259. {
  19260. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  19261. {
  19262. // Only add this placeholder if we don't have any values
  19263. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  19264. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  19265. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  19266. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  19267. }
  19268. }
  19269. }
  19270. if (IsTargetingBeefBackend())
  19271. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  19272. if (methodState.mClosureState != NULL)
  19273. {
  19274. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  19275. {
  19276. BfLocalVariable* localVar = new BfLocalVariable();
  19277. *localVar = constLocal;
  19278. localVar->mIsBumpAlloc = false;
  19279. AddLocalVariableDef(localVar, true);
  19280. }
  19281. }
  19282. bool wantsRemoveBody = false;
  19283. bool skipBody = false;
  19284. bool skipUpdateSrcPos = false;
  19285. bool skipEndChecks = false;
  19286. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  19287. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19288. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  19289. hasExternSpecifier = true;
  19290. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  19291. {
  19292. // We need to be able to mark deleted objects
  19293. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19294. }
  19295. auto customAttributes = methodInstance->GetCustomAttributes();
  19296. if (customAttributes != NULL)
  19297. {
  19298. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  19299. mCurMethodState->mIgnoreObjectAccessCheck = true;
  19300. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  19301. mCurMethodState->mDisableChecks = true;
  19302. }
  19303. // Allocate, clear, set classVData
  19304. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  19305. {
  19306. CreateStaticCtor();
  19307. }
  19308. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19309. {
  19310. skipBody = true;
  19311. skipEndChecks = true;
  19312. if (HasExecutedOutput())
  19313. {
  19314. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  19315. mBfIRBuilder->ClearDebugLocation();
  19316. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  19317. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  19318. PopulateType(innerType, BfPopulateType_DataAndMethods);
  19319. mBfIRBuilder->PopulateType(mCurTypeInstance);
  19320. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  19321. if (methodInstance->mIsForeignMethodDef)
  19322. {
  19323. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  19324. }
  19325. BfTypeVector methodGenericArguments;
  19326. if (methodInstance->mMethodInfoEx != NULL)
  19327. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  19328. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  19329. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  19330. {
  19331. if (!methodInstance->mReturnType->IsValuelessType())
  19332. {
  19333. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  19334. CreateReturn(retVal);
  19335. }
  19336. else
  19337. mBfIRBuilder->CreateRetVoid();
  19338. }
  19339. else
  19340. {
  19341. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  19342. if ((innerMethodDef == methodDef != NULL) && (!CompareMethodSignatures(methodInstance, innerMethodInstance.mMethodInstance)))
  19343. {
  19344. InternalError("Boxing method passthrough error");
  19345. }
  19346. else
  19347. {
  19348. SizedArray<BfIRValue, 8> innerParams;
  19349. BfExprEvaluator exprEvaluator(this);
  19350. if (!innerType->IsValuelessType())
  19351. {
  19352. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  19353. BfTypedValue innerVal(thisValue, innerType, true);
  19354. if (boxedType->IsBoxedStructPtr())
  19355. {
  19356. innerVal = LoadValue(innerVal);
  19357. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  19358. }
  19359. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  19360. }
  19361. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  19362. {
  19363. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  19364. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  19365. exprEvaluator.PushArg(localVal, innerParams);
  19366. }
  19367. if (!innerMethodInstance.mFunc)
  19368. {
  19369. BF_ASSERT(innerType->IsUnspecializedType());
  19370. }
  19371. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  19372. {
  19373. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19374. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  19375. exprEvaluator.mReceivingValue = &returnType;
  19376. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19377. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  19378. mBfIRBuilder->CreateRetVoid();
  19379. }
  19380. else
  19381. {
  19382. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  19383. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  19384. if (mCurMethodInstance->mReturnType->IsValueType())
  19385. retVal = LoadValue(retVal);
  19386. CreateReturn(retVal.mValue);
  19387. }
  19388. }
  19389. }
  19390. }
  19391. mCurMethodState->SetHadReturn(true);
  19392. mCurMethodState->mLeftBlockUncond = true;
  19393. }
  19394. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  19395. {
  19396. SetIllegalSrcPos();
  19397. mBfIRBuilder->ClearDebugLocation();
  19398. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  19399. auto thisVal = GetThis();
  19400. int prevSize = 0;
  19401. if ((mContext->mBfObjectType != NULL) && (mCurTypeInstance->IsObject()))
  19402. {
  19403. prevSize = mContext->mBfObjectType->mInstSize;
  19404. PopulateType(mContext->mBfObjectType);
  19405. // If we have object extensions, clear out starting at the extension
  19406. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  19407. {
  19408. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  19409. {
  19410. prevSize = fieldInstance.mDataOffset;
  19411. break;
  19412. }
  19413. }
  19414. }
  19415. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  19416. int curSize = mCurTypeInstance->mInstSize;
  19417. if (curSize > prevSize)
  19418. {
  19419. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  19420. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  19421. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  19422. }
  19423. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  19424. {
  19425. auto useThis = mCurMethodState->mLocals[0]->mValue;
  19426. auto useThisType = mCurTypeInstance;
  19427. auto checkTypeInst = mCurTypeInstance;
  19428. while (checkTypeInst != NULL)
  19429. {
  19430. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  19431. {
  19432. auto fieldDef = fieldInstance.GetFieldDef();
  19433. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  19434. continue;
  19435. if (fieldInstance.IsAppendedObject())
  19436. {
  19437. if (checkTypeInst != useThisType)
  19438. {
  19439. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  19440. useThisType = checkTypeInst;
  19441. }
  19442. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  19443. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  19444. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  19445. }
  19446. }
  19447. checkTypeInst = checkTypeInst->mBaseType;
  19448. }
  19449. }
  19450. skipUpdateSrcPos = true;
  19451. }
  19452. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  19453. {
  19454. EmitCtorBody(skipBody);
  19455. }
  19456. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  19457. {
  19458. EmitDtorBody();
  19459. skipBody = true;
  19460. }
  19461. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  19462. {
  19463. EmitIteratorBlock(skipBody);
  19464. }
  19465. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  19466. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  19467. {
  19468. // We chain even non-default ctors to the default ctors
  19469. auto defaultCtor = methodInstance;
  19470. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  19471. CallChainedMethods(defaultCtor, false);
  19472. }
  19473. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19474. if (!mCompiler->mHasRequiredTypes)
  19475. {
  19476. // Skip processing to avoid errors
  19477. }
  19478. else if (methodDef->mBody == NULL)
  19479. {
  19480. if (methodDeclaration != NULL)
  19481. {
  19482. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  19483. {
  19484. if (operatorDeclaration->mIsConvOperator)
  19485. wantsRemoveBody = true;
  19486. }
  19487. }
  19488. bool isDllImport = false;
  19489. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  19490. {
  19491. if (importStrNum != -1)
  19492. {
  19493. if (importKind == BfImportKind_Import_Static)
  19494. {
  19495. if (!mImportFileNames.Contains(importStrNum))
  19496. {
  19497. mImportFileNames.Add(importStrNum);
  19498. }
  19499. }
  19500. }
  19501. }
  19502. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  19503. {
  19504. CreateDllImportMethod();
  19505. }
  19506. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  19507. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  19508. {
  19509. if (mCurTypeInstance->mTypeDef->mIsFunction)
  19510. {
  19511. // Emit nothing
  19512. }
  19513. else
  19514. {
  19515. CreateDelegateInvokeMethod();
  19516. mCurMethodState->SetHadReturn(true);
  19517. mCurMethodState->mLeftBlockUncond = true;
  19518. }
  19519. }
  19520. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  19521. {
  19522. if (mCurTypeInstance->IsObject())
  19523. {
  19524. CreateDynamicCastMethod();
  19525. }
  19526. else
  19527. {
  19528. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  19529. mCurMethodState->mHadReturn = true;
  19530. }
  19531. }
  19532. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19533. {
  19534. BfIRValue ret;
  19535. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  19536. {
  19537. // This can happen if we provide an invalid name
  19538. AssertErrorState();
  19539. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  19540. }
  19541. else
  19542. {
  19543. // Unfortunate DebugLoc shenanigans-
  19544. // 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,
  19545. // so we only set the loc on the CreateRet which gets inlined out
  19546. mBfIRBuilder->SaveDebugLocation();
  19547. mBfIRBuilder->ClearDebugLocation();
  19548. BfIRValue fromBool;
  19549. if ((!mCurTypeInstance->IsTypedPrimitive()) || (mCurTypeInstance->IsValuelessType()))
  19550. {
  19551. fromBool = GetDefaultValue(methodInstance->mReturnType);
  19552. }
  19553. else
  19554. {
  19555. BfIRValue thisValue = LoadValue(GetThis()).mValue;
  19556. auto andResult = mBfIRBuilder->CreateAnd(thisValue, mCurMethodState->mLocals[1]->mValue);
  19557. auto toBool = mBfIRBuilder->CreateCmpEQ(andResult, mCurMethodState->mLocals[1]->mValue);
  19558. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  19559. }
  19560. mBfIRBuilder->RestoreDebugLocation();
  19561. ret = mBfIRBuilder->CreateRet(fromBool);
  19562. //ExtendLocalLifetimes(0);
  19563. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19564. }
  19565. mCurMethodState->SetHadReturn(true);
  19566. mCurMethodState->mLeftBlockUncond = true;
  19567. }
  19568. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  19569. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  19570. {
  19571. BfIRValue ret;
  19572. // Unfortunate DebugLoc shenanigans-
  19573. // 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,
  19574. // so we only set the loc on the CreateRet which gets inlined out
  19575. mBfIRBuilder->SaveDebugLocation();
  19576. mBfIRBuilder->ClearDebugLocation();
  19577. BfIRValue fromBool;
  19578. mBfIRBuilder->RestoreDebugLocation();
  19579. if ((!mCompiler->mIsResolveOnly) || (mIsComptimeModule))
  19580. {
  19581. if (!mCurTypeInstance->IsValuelessType())
  19582. {
  19583. auto thisValueOrAddr = GetThis();
  19584. BfIRValue thisValue;
  19585. if (!methodInstance->mReturnType->IsRef())
  19586. thisValue = LoadValue(thisValueOrAddr).mValue;
  19587. else
  19588. thisValue = thisValueOrAddr.mValue;
  19589. ret = mBfIRBuilder->CreateRet(thisValue);
  19590. }
  19591. else
  19592. mBfIRBuilder->CreateRetVoid();
  19593. }
  19594. //ExtendLocalLifetimes(0);
  19595. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19596. mCurMethodState->SetHadReturn(true);
  19597. mCurMethodState->mLeftBlockUncond = true;
  19598. }
  19599. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19600. {
  19601. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19602. if (HasExecutedOutput())
  19603. {
  19604. EmitEnumToStringBody();
  19605. }
  19606. mBfIRBuilder->CreateRetVoid();
  19607. mCurMethodState->SetHadReturn(true);
  19608. mCurMethodState->mLeftBlockUncond = true;
  19609. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19610. }
  19611. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  19612. {
  19613. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  19614. if (HasExecutedOutput())
  19615. {
  19616. EmitTupleToStringBody();
  19617. }
  19618. mBfIRBuilder->CreateRetVoid();
  19619. mCurMethodState->SetHadReturn(true);
  19620. mCurMethodState->mLeftBlockUncond = true;
  19621. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19622. }
  19623. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  19624. {
  19625. CreateValueTypeEqualsMethod(false);
  19626. skipBody = true;
  19627. skipEndChecks = true;
  19628. }
  19629. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  19630. {
  19631. CreateValueTypeEqualsMethod(true);
  19632. skipBody = true;
  19633. skipEndChecks = true;
  19634. }
  19635. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  19636. {
  19637. CreateValueTypeEqualsMethod(false);
  19638. skipBody = true;
  19639. skipEndChecks = true;
  19640. }
  19641. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  19642. {
  19643. CreateDelegateEqualsMethod();
  19644. skipBody = true;
  19645. skipEndChecks = true;
  19646. }
  19647. else
  19648. {
  19649. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19650. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  19651. {
  19652. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  19653. Fail("Body expected", methodDef->GetRefNode());
  19654. }
  19655. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19656. {
  19657. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  19658. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  19659. if (methodInstance->mReturnType->IsValuelessType())
  19660. {
  19661. mBfIRBuilder->CreateRetVoid();
  19662. }
  19663. else if (HasExecutedOutput())
  19664. {
  19665. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19666. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19667. BfFieldDef* fieldDef = NULL;
  19668. if (fieldInstance != NULL)
  19669. fieldDef = fieldInstance->GetFieldDef();
  19670. BfType* retType = methodInstance->mReturnType;
  19671. if (retType->IsRef())
  19672. retType = retType->GetUnderlyingType();
  19673. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  19674. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19675. {
  19676. BfTypedValue lookupValue;
  19677. if (fieldDef->IsNonConstStatic())
  19678. lookupValue = ReferenceStaticField(fieldInstance);
  19679. else if (mCurTypeInstance->IsObject())
  19680. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  19681. else
  19682. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  19683. if (methodInstance->mReturnType->IsRef())
  19684. {
  19685. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  19686. lookupValue = MakeAddressable(lookupValue);
  19687. }
  19688. else
  19689. lookupValue = LoadOrAggregateValue(lookupValue);
  19690. CreateReturn(lookupValue.mValue);
  19691. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19692. }
  19693. else
  19694. {
  19695. // This can happen if we have two properties with the same name but different types
  19696. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19697. EmitDefaultReturn();
  19698. }
  19699. }
  19700. else
  19701. {
  19702. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  19703. EmitDefaultReturn();
  19704. }
  19705. mCurMethodState->SetHadReturn(true);
  19706. }
  19707. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  19708. {
  19709. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  19710. {
  19711. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  19712. }
  19713. else if (!mCompiler->IsAutocomplete())
  19714. {
  19715. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  19716. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  19717. auto fieldDef = fieldInstance->GetFieldDef();
  19718. auto& lastParam = mCurMethodState->mLocals.back();
  19719. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  19720. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  19721. {
  19722. BfIRValue lookupAddr;
  19723. if (fieldDef->IsNonConstStatic())
  19724. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  19725. else
  19726. {
  19727. auto thisValue = GetThis();
  19728. if (thisValue.IsSplat())
  19729. {
  19730. BFMODULE_FATAL(this, "Should not happen");
  19731. }
  19732. if (mCurTypeInstance->IsObject())
  19733. thisValue = LoadValue(thisValue);
  19734. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  19735. }
  19736. BfExprEvaluator exprEvaluator(this);
  19737. auto localVal = exprEvaluator.LoadLocal(lastParam);
  19738. localVal = LoadOrAggregateValue(localVal);
  19739. if (!localVal.mType->IsValuelessType())
  19740. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  19741. }
  19742. else if (!fieldInstance->mResolvedType->IsValuelessType())
  19743. {
  19744. // This can happen if we have two properties with the same name but different types
  19745. AssertErrorState();
  19746. }
  19747. }
  19748. }
  19749. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  19750. {
  19751. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19752. {
  19753. if (HasCompiledOutput())
  19754. EmitGCMarkMembers();
  19755. }
  19756. else if (!mCurTypeInstance->IsObject())
  19757. {
  19758. }
  19759. }
  19760. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  19761. {
  19762. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  19763. {
  19764. if (HasCompiledOutput())
  19765. EmitGCFindTLSMembers();
  19766. }
  19767. }
  19768. }
  19769. }
  19770. else if (!skipBody)
  19771. {
  19772. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  19773. bool wantsRetVal = true;
  19774. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  19775. wantsRetVal = false;
  19776. else if (mCurMethodInstance->mReturnType->IsVar())
  19777. wantsRetVal = false;
  19778. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  19779. {
  19780. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  19781. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  19782. {
  19783. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  19784. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  19785. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  19786. mBfIRBuilder->ClearDebugLocation(storeInst);
  19787. mCurMethodState->mRetValAddr = allocaInst;
  19788. }
  19789. else if (wantsRetVal)
  19790. {
  19791. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  19792. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  19793. }
  19794. }
  19795. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19796. {
  19797. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19798. BfGetSymbolReferenceKind prevSymbolKind;
  19799. BfAutoComplete* prevAutoComplete;
  19800. if (mCompiler->mResolvePassData != NULL)
  19801. {
  19802. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  19803. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19804. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  19805. }
  19806. EmitCtorCalcAppend();
  19807. if (mCompiler->mResolvePassData != NULL)
  19808. {
  19809. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  19810. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  19811. }
  19812. }
  19813. else if (!isEmptyBodied)
  19814. {
  19815. if (!mCurMethodState->mIRExitBlock)
  19816. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  19817. bool isExpressionBody = false;
  19818. if (methodDeclaration != NULL)
  19819. {
  19820. if (methodDeclaration->mFatArrowToken != NULL)
  19821. isExpressionBody = true;
  19822. }
  19823. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19824. {
  19825. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19826. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  19827. isExpressionBody = true;
  19828. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  19829. {
  19830. isExpressionBody = true;
  19831. }
  19832. }
  19833. else
  19834. {
  19835. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  19836. {
  19837. if (!block->mChildArr.IsEmpty())
  19838. {
  19839. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  19840. {
  19841. if (exprStmt->mTrailingSemicolon == NULL)
  19842. isExpressionBody = true;
  19843. }
  19844. }
  19845. }
  19846. else
  19847. isExpressionBody = true;
  19848. }
  19849. DoCEEmit(methodInstance);
  19850. if (methodInstance->mCeCancelled)
  19851. mIgnoreErrors = true;
  19852. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  19853. {
  19854. while (fieldDtorBody != NULL)
  19855. {
  19856. VisitEmbeddedStatement(fieldDtorBody->mBody);
  19857. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  19858. }
  19859. }
  19860. else if (!isExpressionBody)
  19861. {
  19862. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  19863. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  19864. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  19865. VisitCodeBlock(bodyBlock);
  19866. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19867. }
  19868. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  19869. {
  19870. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  19871. // {
  19872. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  19873. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  19874. // }
  19875. auto expectingType = mCurMethodInstance->mReturnType;
  19876. // What was this error for?
  19877. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  19878. // {
  19879. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  19880. // }
  19881. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  19882. if (expectingType->IsVoid())
  19883. {
  19884. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  19885. bool wasReturnGenericParam = false;
  19886. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  19887. {
  19888. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  19889. }
  19890. else
  19891. {
  19892. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  19893. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  19894. wasReturnGenericParam = true;
  19895. }
  19896. // If we the void return was from a generic specialization, allow us to return a void result,
  19897. // otherwise treat expression as though it must be a statement
  19898. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  19899. if (isStatement)
  19900. expectingType = NULL;
  19901. }
  19902. BfExprEvaluator exprEvaluator(this);
  19903. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  19904. exprEvaluator.mAllowReadOnlyReference = true;
  19905. UpdateSrcPos(expressionBody);
  19906. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  19907. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  19908. {
  19909. mCurMethodState->mHadReturn = true;
  19910. if (!mCurMethodState->mLeftBlockUncond)
  19911. {
  19912. retVal = LoadOrAggregateValue(retVal);
  19913. EmitReturn(retVal);
  19914. }
  19915. }
  19916. }
  19917. }
  19918. }
  19919. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  19920. if (skipUpdateSrcPos)
  19921. {
  19922. // Skip
  19923. }
  19924. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19925. UpdateSrcPos(bodyBlock->mCloseBrace);
  19926. else if (methodDef->mBody != NULL)
  19927. UpdateSrcPos(methodDef->mBody);
  19928. else if (methodDeclaration != NULL)
  19929. UpdateSrcPos(methodDeclaration);
  19930. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  19931. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  19932. else
  19933. UseDefaultSrcPos();
  19934. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  19935. {
  19936. if (mCurMethodState->mRetVal)
  19937. {
  19938. mCurMethodState->SetHadReturn(true);
  19939. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  19940. mBfIRBuilder->CreateRet(retVal);
  19941. }
  19942. else
  19943. AssertErrorState();
  19944. }
  19945. mCurMethodState->mHeadScope.mDone = true;
  19946. if (!mCurMethodState->mHadReturn)
  19947. {
  19948. // Clear off the stackallocs that have occurred after a scopeData break
  19949. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  19950. }
  19951. EmitDeferredCallProcessorInstances(&mCurMethodState->mHeadScope);
  19952. if (mCurMethodState->mIRExitBlock)
  19953. {
  19954. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  19955. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  19956. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  19957. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  19958. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  19959. CreateDIRetVal();
  19960. }
  19961. for (auto localVar : mCurMethodState->mLocals)
  19962. {
  19963. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19964. {
  19965. //
  19966. }
  19967. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  19968. break;
  19969. LocalVariableDone(localVar, true);
  19970. }
  19971. if (mCurMethodState->mIRExitBlock)
  19972. {
  19973. if ((mCurMethodState->mRetVal) &&
  19974. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  19975. {
  19976. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  19977. CreateReturn(loadedVal);
  19978. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19979. if (mCurMethodState->mDIRetVal)
  19980. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  19981. }
  19982. else
  19983. {
  19984. // Have something on the last line to step onto
  19985. if (mHasFullDebugInfo)
  19986. {
  19987. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  19988. UpdateSrcPos(bodyBlock->mCloseBrace);
  19989. EmitEnsureInstructionAt();
  19990. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  19991. {
  19992. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  19993. mBfIRBuilder->EnsureFunctionPatchable();
  19994. }
  19995. }
  19996. mBfIRBuilder->CreateRetVoid();
  19997. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  19998. if (mCurMethodState->mDIRetVal)
  19999. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  20000. }
  20001. }
  20002. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  20003. {
  20004. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  20005. {
  20006. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  20007. {
  20008. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  20009. mBfIRBuilder->EnsureFunctionPatchable();
  20010. }
  20011. mBfIRBuilder->CreateRetVoid();
  20012. }
  20013. }
  20014. else
  20015. {
  20016. if (!mCurMethodState->mHadReturn)
  20017. {
  20018. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  20019. if (bodyBlock != NULL)
  20020. {
  20021. if (bodyBlock->mCloseBrace != NULL)
  20022. {
  20023. BfAstNode* target = bodyBlock->mCloseBrace;
  20024. if (!mCompiler->mHasRequiredTypes)
  20025. {
  20026. AddFailType(mCurTypeInstance);
  20027. mHadBuildError = true;
  20028. }
  20029. else
  20030. Fail("Method must return value", target);
  20031. }
  20032. else
  20033. {
  20034. // It's possible to not have a closing brace if the method ends in an EOF
  20035. AssertErrorState();
  20036. }
  20037. }
  20038. }
  20039. }
  20040. // Move 'init' into 'entry'
  20041. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  20042. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  20043. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  20044. (!mIsComptimeModule))
  20045. {
  20046. // Don't keep instructions for unspecialized types
  20047. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20048. }
  20049. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  20050. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  20051. wantsRemoveBody = true;*/
  20052. if ((hasExternSpecifier) && (!skipBody))
  20053. {
  20054. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  20055. // incase it gets called later by some hot-loaded coded
  20056. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  20057. {
  20058. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  20059. CreateFakeCallerMethod(mangledName);
  20060. }
  20061. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20062. }
  20063. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  20064. {
  20065. // We only need the DLL stub when we may be hot swapping
  20066. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20067. }
  20068. else if (wantsRemoveBody)
  20069. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  20070. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  20071. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  20072. // unspecialized types
  20073. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  20074. (mCurTypeInstance->IsInterface()))
  20075. {
  20076. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  20077. methodInstance->mIRFunction = BfIRFunction();
  20078. }
  20079. CheckAddFailType();
  20080. if (mHadBuildError)
  20081. prevHadBuildError.CancelRestore();
  20082. if (mHadBuildWarning)
  20083. prevHadWarning.CancelRestore();
  20084. if (!methodDef->mIsLocalMethod)
  20085. ProcessMethod_ProcessDeferredLocals();
  20086. prevIgnoreWrites.Restore();
  20087. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20088. if (methodState.mHotDataReferenceBuilder != NULL)
  20089. {
  20090. AddHotDataReferences(&hotDataReferenceBuilder);
  20091. }
  20092. else
  20093. {
  20094. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  20095. {
  20096. // Remove the hot method data
  20097. auto hotMethod = methodInstance->mHotMethod;
  20098. auto prevMethod = hotMethod->mPrevVersion;
  20099. if (prevMethod != NULL)
  20100. {
  20101. // If there's a prev method then pull its data into the main HotMethod.
  20102. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  20103. // over to the main HotMethod definition to keep the HotMethod address
  20104. // invariant
  20105. for (auto ref : hotMethod->mReferences)
  20106. ref->Deref();
  20107. hotMethod->mReferences.Clear();
  20108. BF_ASSERT(prevMethod->mRefCount == 1);
  20109. hotMethod->mReferences = prevMethod->mReferences;
  20110. if (hotMethod->mSrcTypeVersion != NULL)
  20111. hotMethod->mSrcTypeVersion->Deref();
  20112. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  20113. prevMethod->mSrcTypeVersion = NULL;
  20114. prevMethod->mReferences.Clear();
  20115. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  20116. prevMethod->mPrevVersion = NULL;
  20117. prevMethod->Deref();
  20118. }
  20119. hotMethod->Deref();
  20120. methodInstance->mHotMethod = NULL;
  20121. }
  20122. }
  20123. }
  20124. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  20125. {
  20126. String name;
  20127. bool found = false;
  20128. auto checkMethodState = mCurMethodState;
  20129. while (checkMethodState != NULL)
  20130. {
  20131. if (checkMethodState->mClosureState == NULL)
  20132. break;
  20133. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  20134. {
  20135. found = true;
  20136. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  20137. break;
  20138. }
  20139. checkMethodState = checkMethodState->mPrevMethodState;
  20140. }
  20141. if (!found)
  20142. name += mCurMethodInstance->mMethodDef->mName;
  20143. int prevSepPos = (int)name.LastIndexOf('$');
  20144. if (prevSepPos != -1)
  20145. {
  20146. name.RemoveToEnd(prevSepPos);
  20147. }
  20148. name += "@";
  20149. name += baseName;
  20150. HashContext hashCtx;
  20151. if (anchorNode != NULL)
  20152. {
  20153. hashCtx.Mixin(anchorNode->GetStartCharId());
  20154. }
  20155. //
  20156. {
  20157. auto checkMethodState = declMethodState;
  20158. auto checkMixinState = declMixinState;
  20159. while (checkMethodState != NULL)
  20160. {
  20161. if (checkMixinState != NULL)
  20162. {
  20163. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  20164. }
  20165. checkMethodState = checkMethodState->mPrevMethodState;
  20166. if (checkMethodState != NULL)
  20167. checkMixinState = checkMethodState->mMixinState;
  20168. }
  20169. }
  20170. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20171. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20172. {
  20173. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  20174. {
  20175. StringT<512> genericTypeName;
  20176. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  20177. hashCtx.MixinStr(genericTypeName);
  20178. }
  20179. }
  20180. uint64 hashVal = hashCtx.Finish64();
  20181. name += "$";
  20182. name += BfTypeUtils::HashEncode64(hashVal);
  20183. return name;
  20184. }
  20185. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  20186. {
  20187. if (localMethod->mMethodDef != NULL)
  20188. return localMethod->mMethodDef;
  20189. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20190. auto declMethodState = localMethod->mDeclMethodState;
  20191. auto declMixinState = localMethod->mDeclMixinState;
  20192. auto typeInst = mCurTypeInstance;
  20193. BfAstNode* body = NULL;
  20194. BfAstNode* anchorNode = NULL;
  20195. auto _AllocDirectTypeRef = [&](BfType* type)
  20196. {
  20197. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  20198. directTypeRef->Init(type);
  20199. return directTypeRef;
  20200. };
  20201. auto methodDeclaration = localMethod->mMethodDeclaration;
  20202. if (methodDeclaration != NULL)
  20203. {
  20204. body = methodDeclaration->mBody;
  20205. anchorNode = methodDeclaration->mOpenParen;
  20206. }
  20207. else
  20208. {
  20209. body = localMethod->mLambdaBindExpr->mBody;
  20210. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  20211. }
  20212. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  20213. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  20214. BfMethodDef* methodDef;
  20215. BfMethodDef* outerMethodDef = NULL;
  20216. if (localMethod->mOuterLocalMethod != NULL)
  20217. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  20218. else if (rootMethodState->mMethodInstance != NULL)
  20219. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  20220. if (methodDeclaration != NULL)
  20221. {
  20222. BfDefBuilder defBuilder(mCompiler->mSystem);
  20223. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  20224. defBuilder.mPassInstance = mCompiler->mPassInstance;
  20225. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  20226. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  20227. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  20228. }
  20229. else
  20230. {
  20231. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  20232. methodDef = new BfMethodDef();
  20233. methodDef->mName = localMethod->mMethodName;
  20234. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  20235. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  20236. methodDef->mBody = body;
  20237. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  20238. {
  20239. auto paramType = invokeMethod->GetParamType(paramIdx);
  20240. String paramName;
  20241. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  20242. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  20243. else
  20244. paramName = invokeMethod->GetParamName(paramIdx);
  20245. auto paramDef = new BfParameterDef();
  20246. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  20247. paramDef->mName = paramName;
  20248. methodDef->mParams.Add(paramDef);
  20249. }
  20250. if (outerMethodDef != NULL)
  20251. {
  20252. for (auto genericParam : outerMethodDef->mGenericParams)
  20253. {
  20254. auto* copiedGenericParamDef = new BfGenericParamDef();
  20255. *copiedGenericParamDef = *genericParam;
  20256. methodDef->mGenericParams.Add(copiedGenericParamDef);
  20257. }
  20258. }
  20259. }
  20260. methodDef->mIdx = ~methodLocalIdx;
  20261. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  20262. methodDef->mName = localMethod->mExpectedFullName;
  20263. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  20264. //
  20265. // if (!localMethod->mExpectedFullName.IsEmpty())
  20266. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  20267. methodDef->mIsStatic = true;
  20268. methodDef->mIsLocalMethod = true;
  20269. methodDef->mIsVirtual = false;
  20270. localMethod->mMethodDef = methodDef;
  20271. auto methodInstanceGroup = new BfMethodInstanceGroup();
  20272. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  20273. methodInstanceGroup->mMethodIdx = -1;
  20274. methodInstanceGroup->mOwner = mCurTypeInstance;
  20275. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  20276. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  20277. {
  20278. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  20279. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  20280. }
  20281. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  20282. {
  20283. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  20284. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20285. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  20286. {
  20287. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  20288. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  20289. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  20290. autoComplete->mDefType = typeInst->mTypeDef;
  20291. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  20292. autoComplete->mReplaceLocalId = methodLocalIdx;
  20293. }
  20294. }
  20295. return localMethod->mMethodDef;
  20296. }
  20297. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  20298. {
  20299. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  20300. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  20301. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20302. auto declMethodState = localMethod->mDeclMethodState;
  20303. auto declMixinState = localMethod->mDeclMixinState;
  20304. auto callerMethodState = mCurMethodState;
  20305. auto typeInst = mCurTypeInstance;
  20306. if (mCurMethodState->mMixinState != NULL)
  20307. {
  20308. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  20309. }
  20310. auto methodDef = GetLocalMethodDef(localMethod);
  20311. BfAstNode* body = NULL;
  20312. auto methodDeclaration = localMethod->mMethodDeclaration;
  20313. if (methodDeclaration != NULL)
  20314. {
  20315. body = methodDeclaration->mBody;
  20316. }
  20317. else
  20318. {
  20319. body = localMethod->mLambdaBindExpr->mBody;
  20320. }
  20321. bool hadConcreteInterfaceGenericArgument = false;
  20322. BfTypeVector sanitizedMethodGenericArguments;
  20323. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  20324. // version of this method for this pass through the outermost method
  20325. int dependentGenericStartIdx = 0;
  20326. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20327. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20328. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  20329. if (methodGenericArguments.size() == 0)
  20330. {
  20331. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  20332. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  20333. }
  20334. else
  20335. {
  20336. int genericArgIdx = 0;
  20337. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  20338. // {
  20339. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  20340. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  20341. // }
  20342. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20343. {
  20344. auto genericArgType = methodGenericArguments[genericArgIdx];
  20345. BF_ASSERT(!genericArgType->IsRef());
  20346. if (genericArgType->IsConcreteInterfaceType())
  20347. {
  20348. hadConcreteInterfaceGenericArgument = true;
  20349. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  20350. genericArgType = concreteInterfaceType->mInterface;
  20351. }
  20352. sanitizedMethodGenericArguments.push_back(genericArgType);
  20353. }
  20354. }
  20355. bool wantPrematureMethodInstance = false;
  20356. if (!force)
  20357. {
  20358. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  20359. }
  20360. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  20361. bool isDefaultPass = true;
  20362. BfTypeVector lookupMethodGenericArguments;
  20363. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  20364. {
  20365. auto genericArgType = methodGenericArguments[genericArgIdx];
  20366. BF_ASSERT(!genericArgType->IsRef());
  20367. lookupMethodGenericArguments.Add(genericArgType);
  20368. if (genericArgType->IsGenericParam())
  20369. {
  20370. auto genericParam = (BfGenericParamType*)genericArgType;
  20371. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20372. isDefaultPass = false;
  20373. }
  20374. else
  20375. {
  20376. isDefaultPass = false;
  20377. }
  20378. }
  20379. bool hadExistingMethodInstance = false;
  20380. if (methodInstance != NULL)
  20381. {
  20382. hadExistingMethodInstance = true;
  20383. }
  20384. else
  20385. {
  20386. if (isDefaultPass)
  20387. {
  20388. methodInstance = methodInstGroup->mDefault;
  20389. if (methodInstance != NULL)
  20390. {
  20391. hadExistingMethodInstance = true;
  20392. }
  20393. else
  20394. {
  20395. methodInstance = new BfMethodInstance();
  20396. methodInstGroup->mDefault = methodInstance;
  20397. }
  20398. }
  20399. else
  20400. {
  20401. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  20402. if (methodInstGroup->mMethodSpecializationMap == NULL)
  20403. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  20404. BfMethodInstance** methodInstancePtr = NULL;
  20405. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  20406. {
  20407. methodInstance = *methodInstancePtr;
  20408. hadExistingMethodInstance = true;
  20409. }
  20410. else
  20411. {
  20412. methodInstance = new BfMethodInstance();
  20413. *methodInstancePtr = methodInstance;
  20414. }
  20415. }
  20416. }
  20417. if (hadExistingMethodInstance)
  20418. {
  20419. if ((!methodInstance->mDisallowCalling) ||
  20420. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  20421. return BfModuleMethodInstance(methodInstance);
  20422. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  20423. }
  20424. else
  20425. {
  20426. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  20427. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  20428. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  20429. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  20430. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  20431. methodInstance->mMethodDef = methodDef;
  20432. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  20433. if (hadConcreteInterfaceGenericArgument)
  20434. methodInstance->mIgnoreBody = true;
  20435. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  20436. for (auto genericArg : sanitizedMethodGenericArguments)
  20437. {
  20438. if (genericArg->IsPrimitiveType())
  20439. genericArg = GetWrappedStructType(genericArg);
  20440. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  20441. }
  20442. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20443. {
  20444. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20445. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  20446. }
  20447. SetupMethodIdHash(methodInstance);
  20448. }
  20449. auto _SetupMethodInstance = [&]()
  20450. {
  20451. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  20452. // Generic constraints
  20453. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  20454. {
  20455. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  20456. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20457. }
  20458. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  20459. {
  20460. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  20461. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  20462. }
  20463. };
  20464. //////////////////////////////////////////////////////////////////////////
  20465. auto _VisitLambdaBody = [&]()
  20466. {
  20467. if (localMethod->mDeclOnly)
  20468. return;
  20469. if (mCompiler->mCanceling)
  20470. return;
  20471. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20472. {
  20473. VisitCodeBlock(blockBody);
  20474. }
  20475. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  20476. {
  20477. BfType* expectType = NULL;
  20478. if (!methodInstance->mReturnType->IsVoid())
  20479. expectType = methodInstance->mReturnType;
  20480. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  20481. }
  20482. };
  20483. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  20484. {
  20485. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  20486. auto result = ResolveTypeRef(typeRef);
  20487. if (result == NULL)
  20488. result = mContext->mBfObjectType;
  20489. return result;
  20490. };
  20491. BfTypeInstance* outerClosure = NULL;
  20492. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  20493. outerClosure = declMethodState->mClosureState->mClosureType;
  20494. BfMethodState methodState;
  20495. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  20496. BfIRFunctionType funcType;
  20497. auto voidType = GetPrimitiveType(BfTypeCode_None);
  20498. SizedArray<BfIRType, 0> paramTypes;
  20499. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  20500. mBfIRBuilder->SaveDebugLocation();
  20501. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  20502. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  20503. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  20504. BfDeferredLocalAssignData deferredLocalAssignData;
  20505. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  20506. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  20507. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  20508. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20509. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  20510. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  20511. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  20512. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  20513. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  20514. methodState.mIRFunction = declMethodState->mIRFunction;
  20515. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  20516. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  20517. {
  20518. methodState.mCurScope->mAstBlock = blockBody;
  20519. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  20520. }
  20521. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  20522. BfClosureState closureState;
  20523. if (methodDef->mMethodType == BfMethodType_Mixin)
  20524. {
  20525. if (declMethodState != NULL)
  20526. {
  20527. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  20528. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  20529. else if (declMethodState->mMethodInstance != NULL)
  20530. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  20531. }
  20532. }
  20533. if (closureState.mReturnType == NULL)
  20534. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  20535. closureState.mCapturing = true;
  20536. closureState.mLocalMethod = localMethod;
  20537. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  20538. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  20539. methodState.mClosureState = &closureState;
  20540. closureState.mClosureType = outerClosure;
  20541. int outerLocalsCount = (int)methodState.mLocals.size();
  20542. if (!hadExistingMethodInstance)
  20543. {
  20544. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  20545. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  20546. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  20547. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  20548. auto declareModule = this;
  20549. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20550. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20551. BF_ASSERT(declareModule != NULL);
  20552. methodInstance->mDeclModule = declareModule;
  20553. _SetupMethodInstance();
  20554. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20555. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  20556. }
  20557. if (wantPrematureMethodInstance)
  20558. {
  20559. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  20560. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  20561. // its true method instance
  20562. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  20563. //BF_ASSERT(moduleMethodInstance);
  20564. return BfModuleMethodInstance(methodInstance);
  20565. }
  20566. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  20567. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  20568. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  20569. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  20570. closureState.mClosureMethodDef = methodDef;
  20571. bool wantsVisitBody = true;
  20572. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  20573. wantsVisitBody = false;
  20574. if (methodInstance->IsOrInUnspecializedVariation())
  20575. wantsVisitBody = false;
  20576. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  20577. if (wantsVisitBody)
  20578. {
  20579. BP_ZONE("VisitLambdaBody");
  20580. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  20581. // this capture stage for each of those times
  20582. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  20583. /*
  20584. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  20585. // that will not occur during the actual lambda method generation, for example: returning a value
  20586. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  20587. // our AST nodes will still be visited
  20588. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  20589. */
  20590. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20591. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  20592. mBfIRBuilder->SaveDebugLocation();
  20593. closureState.mCaptureVisitingBody = true;
  20594. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  20595. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  20596. methodState.mMethodInstance = methodInstance;
  20597. NewScopeState();
  20598. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  20599. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  20600. {
  20601. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  20602. for (auto localDef : methodState.mLocals)
  20603. {
  20604. if (localDef->mResolvedType->IsVar())
  20605. continue;
  20606. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  20607. }
  20608. }
  20609. // Keep outs from being marked as assigned
  20610. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20611. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  20612. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  20613. auto prevDLA = rootMethodState->mDeferredLocalAssignData;
  20614. while ((prevDLA != NULL) && (prevDLA->mIsChained))
  20615. prevDLA = prevDLA->mChainedAssignData;
  20616. if (prevDLA != NULL)
  20617. {
  20618. deferredLocalAssignData.mAssignedLocals = prevDLA->mAssignedLocals;
  20619. deferredLocalAssignData.mLeftBlockUncond = prevDLA->mLeftBlockUncond;
  20620. }
  20621. SetAndRestoreValue<BfDeferredLocalAssignData*> sarDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20622. if (!mIgnoreErrors)
  20623. localMethod->mDidBodyErrorPass = true;
  20624. _VisitLambdaBody();
  20625. RestoreScopeState();
  20626. closureState.mCaptureVisitingBody = false;
  20627. mBfIRBuilder->RestoreDebugLocation();
  20628. }
  20629. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  20630. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  20631. {
  20632. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  20633. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  20634. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  20635. }
  20636. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  20637. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  20638. closureState.mClosureMethodDef = NULL;
  20639. for (auto methodInstance : closureState.mLocalMethodRefs)
  20640. {
  20641. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  20642. }
  20643. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  20644. prevIgnoreWrites.Restore();
  20645. std::multiset<BfClosureCapturedEntry> capturedEntries;
  20646. //
  20647. {
  20648. auto varMethodState = declMethodState;
  20649. while (varMethodState != NULL)
  20650. {
  20651. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  20652. {
  20653. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  20654. methodDef->mIsStatic = false;
  20655. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20656. methodDef->mIsMutating = true;
  20657. }
  20658. bool copyOuterCaptures = false;
  20659. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  20660. {
  20661. auto localVar = varMethodState->mLocals[localIdx];
  20662. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20663. {
  20664. if (!allowCapture)
  20665. {
  20666. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  20667. continue;
  20668. }
  20669. if (localVar->mIsThis)
  20670. {
  20671. // We can only set mutating if our owning type is mutating
  20672. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  20673. {
  20674. if (typeInst->IsValueType())
  20675. {
  20676. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  20677. methodDef->mIsMutating = true;
  20678. }
  20679. }
  20680. methodDef->mIsStatic = false;
  20681. continue;
  20682. }
  20683. if ((localVar->mIsThis) && (outerClosure != NULL))
  20684. {
  20685. continue;
  20686. }
  20687. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  20688. {
  20689. closureState.mConstLocals.push_back(*localVar);
  20690. continue;
  20691. }
  20692. BfClosureCapturedEntry capturedEntry;
  20693. auto capturedType = localVar->mResolvedType;
  20694. bool captureByRef = false;
  20695. if (!capturedType->IsRef())
  20696. {
  20697. if (localVar->mIsThis)
  20698. {
  20699. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  20700. captureByRef = true;
  20701. }
  20702. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  20703. captureByRef = true;
  20704. }
  20705. else
  20706. {
  20707. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  20708. {
  20709. capturedType = ((BfRefType*)capturedType)->mElementType;
  20710. }
  20711. }
  20712. if (captureByRef)
  20713. {
  20714. //capturedEntry.mIsByReference = true;
  20715. capturedType = CreateRefType(capturedType);
  20716. }
  20717. else
  20718. {
  20719. //capturedEntry.mIsByReference = false;
  20720. }
  20721. capturedEntry.mNameNode = localVar->mNameNode;
  20722. capturedEntry.mType = capturedType;
  20723. capturedEntry.mName = localVar->mName;
  20724. //capturedEntry.mLocalVarDef = localVar;
  20725. capturedEntries.insert(capturedEntry);
  20726. }
  20727. }
  20728. varMethodState = varMethodState->mPrevMethodState;
  20729. if ((varMethodState == NULL) ||
  20730. (varMethodState->mMixinState != NULL) ||
  20731. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  20732. break;
  20733. }
  20734. }
  20735. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  20736. {
  20737. auto fieldDef = copyField->GetFieldDef();
  20738. BfClosureCapturedEntry capturedEntry;
  20739. capturedEntry.mName = copyField->GetFieldDef()->mName;
  20740. capturedEntry.mType = copyField->mResolvedType;
  20741. if (capturedEntry.mType->IsRef())
  20742. {
  20743. // Keep by ref
  20744. }
  20745. else if (!fieldDef->mIsReadOnly)
  20746. {
  20747. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  20748. }
  20749. capturedEntries.insert(capturedEntry);
  20750. }
  20751. int captureIdx = 0;
  20752. for (auto& capturedEntry : capturedEntries)
  20753. {
  20754. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  20755. }
  20756. /*if (isDefaultPass)
  20757. {
  20758. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  20759. int captureIdx = 0;
  20760. for (auto& capturedEntry : capturedEntries)
  20761. {
  20762. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  20763. BfParameterDef* paramDef = new BfParameterDef();
  20764. paramDef->mName = capturedEntry.mName;
  20765. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  20766. directTypeRef->mType = capturedEntry.mType;
  20767. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  20768. paramDef->mTypeRef = directTypeRef;
  20769. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  20770. methodDef->mParams.Insert(captureIdx, paramDef);
  20771. captureIdx++;
  20772. }
  20773. }
  20774. else
  20775. {
  20776. auto defaultMethodInstance = methodInstGroup->mDefault;
  20777. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  20778. }*/
  20779. methodState.Reset();
  20780. closureState.mCapturing = false;
  20781. //////////////////////////////////////////////////////////////////////////
  20782. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  20783. if (methodInstance->mReturnType != NULL)
  20784. {
  20785. BF_ASSERT(methodInstance->mDisallowCalling);
  20786. // We did a premature declaration (without captures)
  20787. methodInstance->UndoDeclaration();
  20788. methodInstance->mDisallowCalling = false;
  20789. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  20790. }
  20791. auto declareModule = this;
  20792. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  20793. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  20794. BF_ASSERT(declareModule != NULL);
  20795. methodInstance->mDeclModule = declareModule;
  20796. _SetupMethodInstance();
  20797. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  20798. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  20799. closureState.mReturnType = methodInstance->mReturnType;
  20800. mCompiler->mStats.mMethodsQueued++;
  20801. mCompiler->UpdateCompletion();
  20802. declareModule->mIncompleteMethodCount++;
  20803. mCompiler->mStats.mMethodsProcessed++;
  20804. if (!methodInstance->mIsReified)
  20805. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  20806. auto deferMethodState = rootMethodState;
  20807. // 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)
  20808. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  20809. (methodDef->mMethodType != BfMethodType_Mixin) &&
  20810. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  20811. (!mCompiler->IsDataResolvePass()))
  20812. {
  20813. BP_ZONE("BfDeferredLocalMethod:create");
  20814. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  20815. deferredLocalMethod->mLocalMethod = localMethod;
  20816. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  20817. deferredLocalMethod->mMethodInstance = methodInstance;
  20818. auto checkMethodState = declMethodState;
  20819. while (checkMethodState != NULL)
  20820. {
  20821. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  20822. {
  20823. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  20824. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20825. }
  20826. if (checkMethodState->mMixinState != NULL)
  20827. {
  20828. BfMixinRecord mixinRecord;
  20829. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  20830. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  20831. }
  20832. checkMethodState = checkMethodState->mPrevMethodState;
  20833. }
  20834. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  20835. }
  20836. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  20837. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  20838. mBfIRBuilder->RestoreDebugLocation();
  20839. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  20840. {
  20841. auto checkMethodState = mCurMethodState;
  20842. while (checkMethodState != NULL)
  20843. {
  20844. BfLocalMethod* nextLocalMethod = NULL;
  20845. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  20846. {
  20847. while (nextLocalMethod != NULL)
  20848. {
  20849. auto checkLocalMethod = nextLocalMethod;
  20850. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  20851. if (checkLocalMethod == localMethod)
  20852. continue;
  20853. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  20854. continue;
  20855. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  20856. if (checkMethodInstance == NULL)
  20857. continue; // Not generated yet
  20858. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  20859. {
  20860. String error = "Method already declared with the same parameter types";
  20861. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  20862. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  20863. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  20864. }
  20865. }
  20866. }
  20867. checkMethodState = checkMethodState->mPrevMethodState;
  20868. }
  20869. }
  20870. return BfModuleMethodInstance(methodInstance);
  20871. }
  20872. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  20873. {
  20874. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  20875. return 0;
  20876. auto rootMethodState = mCurMethodState->GetRootMethodState();
  20877. int rootMethodGenericParamCount = 0;
  20878. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  20879. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  20880. if (mCurMethodInstance == NULL)
  20881. return rootMethodGenericParamCount;
  20882. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  20883. return rootMethodGenericParamCount;
  20884. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  20885. if (callerLocalMethod == NULL)
  20886. return rootMethodGenericParamCount;
  20887. BfLocalMethod* calledLocalMethod = NULL;
  20888. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  20889. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  20890. {
  20891. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  20892. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  20893. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  20894. }
  20895. return rootMethodGenericParamCount;
  20896. }
  20897. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  20898. {
  20899. auto methodDef = methodInstance->mMethodDef;
  20900. auto customAttributes = methodInstance->GetCustomAttributes();
  20901. if (customAttributes != NULL)
  20902. return;
  20903. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20904. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  20905. auto typeInstance = methodInstance->GetOwner();
  20906. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  20907. return;
  20908. BfTypeState typeState(typeInstance);
  20909. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20910. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  20911. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  20912. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  20913. BfAttributeDirective* attributeDirective = NULL;
  20914. if (methodDeclaration != NULL)
  20915. attributeDirective = methodDeclaration->mAttributes;
  20916. else if (propertyMethodDeclaration != NULL)
  20917. {
  20918. attributeDirective = propertyMethodDeclaration->mAttributes;
  20919. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  20920. {
  20921. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  20922. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  20923. }
  20924. }
  20925. if (attributeDirective != NULL)
  20926. {
  20927. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20928. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20929. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  20930. {
  20931. // Take over previously-generated custom attributes
  20932. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  20933. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  20934. }
  20935. else
  20936. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  20937. }
  20938. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  20939. {
  20940. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  20941. {
  20942. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20943. }
  20944. else
  20945. {
  20946. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20947. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  20948. }
  20949. }
  20950. if (methodDeclaration != NULL)
  20951. {
  20952. if (auto inlineTypeRef = BfNodeDynCast<BfInlineTypeReference>(methodDeclaration->mReturnType))
  20953. {
  20954. if (inlineTypeRef->mTypeDeclaration->mAttributes != NULL)
  20955. {
  20956. // Apply multiuse attributes from anonymous return type
  20957. auto returnType = ResolveTypeRef(inlineTypeRef);
  20958. if ((returnType != NULL) && (returnType->ToTypeInstance()))
  20959. {
  20960. auto returnTypeInst = returnType->ToTypeInstance();
  20961. if ((returnTypeInst->IsAnonymous()) && (returnTypeInst->mCustomAttributes != NULL))
  20962. {
  20963. bool hasPendingAttributes = false;
  20964. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20965. {
  20966. if (customAttribute.mAwaitingValidation)
  20967. {
  20968. hasPendingAttributes = true;
  20969. break;
  20970. }
  20971. }
  20972. if (hasPendingAttributes)
  20973. {
  20974. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20975. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20976. if (methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes == NULL)
  20977. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = new BfCustomAttributes();
  20978. for (const auto& customAttribute : returnTypeInst->mCustomAttributes->mAttributes)
  20979. {
  20980. if (!customAttribute.mAwaitingValidation)
  20981. continue;
  20982. BfCustomAttribute copiedCustomAttribute = customAttribute;
  20983. copiedCustomAttribute.mIsMultiUse = false;
  20984. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes.Add(copiedCustomAttribute);
  20985. }
  20986. ValidateCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, attrTarget);
  20987. }
  20988. }
  20989. }
  20990. }
  20991. }
  20992. }
  20993. customAttributes = methodInstance->GetCustomAttributes();
  20994. if (customAttributes == NULL)
  20995. {
  20996. auto owner = methodInstance->GetOwner();
  20997. if ((owner->IsDelegate()) || (owner->IsFunction()))
  20998. customAttributes = owner->mCustomAttributes;
  20999. }
  21000. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  21001. if ((typeInstance->IsValueType()) && (methodDef->mIsOverride) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS))
  21002. {
  21003. // Make sure we we pass 'this' as a pointer into GCMarkMembers so it's compatible with the mark function pointer
  21004. methodInstance->mCallingConvention = BfCallingConvention_Cdecl;
  21005. }
  21006. if (customAttributes != NULL)
  21007. {
  21008. if (customAttributes->Contains(mCompiler->mIntrinsicAttributeTypeDef))
  21009. methodInstance->mIsIntrinsic = true;
  21010. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  21011. if (linkNameAttr != NULL)
  21012. {
  21013. if (linkNameAttr->mCtorArgs.size() == 1)
  21014. {
  21015. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  21016. if (constant != NULL)
  21017. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  21018. }
  21019. }
  21020. if (methodDef->mHasComptime)
  21021. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  21022. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  21023. if (comptimeAttr != NULL)
  21024. {
  21025. for (auto setProp : comptimeAttr->mSetProperties)
  21026. {
  21027. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  21028. if (propertyDef->mName == "OnlyFromComptime")
  21029. {
  21030. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  21031. if ((constant != NULL) && (constant->mBool))
  21032. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  21033. }
  21034. else if (propertyDef->mName == "ConstEval")
  21035. {
  21036. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  21037. if ((constant != NULL) && (constant->mBool))
  21038. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  21039. }
  21040. }
  21041. }
  21042. }
  21043. auto delegateInfo = typeInstance->GetDelegateInfo();
  21044. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  21045. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  21046. }
  21047. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  21048. {
  21049. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  21050. {
  21051. // Don't create a func
  21052. return;
  21053. }
  21054. auto typeInstance = methodInstance->GetOwner();
  21055. auto methodDef = methodInstance->mMethodDef;
  21056. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  21057. if (isTemporaryFunc)
  21058. {
  21059. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  21060. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  21061. mangledName = "autocomplete_tmp";
  21062. }
  21063. if (!mBfIRBuilder->mIgnoreWrites)
  21064. {
  21065. BfIRFunction prevFunc;
  21066. // Remove old version (if we have one)
  21067. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  21068. if (prevFunc)
  21069. {
  21070. auto owner = methodInstance->GetOwner();
  21071. if ((methodDef->mIsOverride) && (owner->mTypeDef->mIsCombinedPartial))
  21072. {
  21073. bool takeover = false;
  21074. owner->mTypeDef->PopulateMemberSets();
  21075. BfMethodDef* nextMethod = NULL;
  21076. BfMemberSetEntry* entry = NULL;
  21077. if (owner->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21078. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21079. while (nextMethod != NULL)
  21080. {
  21081. auto checkMethod = nextMethod;
  21082. nextMethod = nextMethod->mNextWithSameName;
  21083. if (checkMethod == methodDef)
  21084. continue;
  21085. if (checkMethod->mIsOverride)
  21086. {
  21087. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21088. if (checkMethodInstance == NULL)
  21089. continue;
  21090. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  21091. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  21092. (checkMethodInstance->mVirtualTableIdx < 0))
  21093. {
  21094. BfAstNode* refNode = methodDef->GetRefNode();
  21095. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21096. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  21097. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21098. refNode = methodDeclaration->mVirtualSpecifier;
  21099. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(methodInstance).c_str()), refNode);
  21100. if (error != NULL)
  21101. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  21102. takeover = false;
  21103. break;
  21104. }
  21105. }
  21106. if (!checkMethod->mIsExtern)
  21107. continue;
  21108. auto checkMethodInstance = owner->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21109. if (checkMethodInstance == NULL)
  21110. continue;
  21111. if (!CompareMethodSignatures(checkMethodInstance, methodInstance))
  21112. continue;
  21113. // Take over function
  21114. takeover = true;
  21115. BfLogSysM("Method %p setting mHasBeenProcessed due to funcId takeover from method %p\n", checkMethodInstance, prevFunc.mId, methodInstance);
  21116. checkMethodInstance->mHasBeenProcessed = true;
  21117. }
  21118. if (takeover)
  21119. {
  21120. BfLogSysM("Method %p takover of previous funcId: %d\n", methodInstance, prevFunc.mId);
  21121. methodInstance->mIRFunction = prevFunc;
  21122. }
  21123. if (!methodInstance->mIRFunction)
  21124. {
  21125. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  21126. if (!mIsComptimeModule)
  21127. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  21128. }
  21129. }
  21130. else if (methodDef->mIsExtern)
  21131. {
  21132. // Allow this
  21133. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  21134. }
  21135. else if (typeInstance->IsIRFuncUsed(prevFunc))
  21136. {
  21137. // We can have a collision of names when we have generic methods that differ only in
  21138. // their constraints, but they should only collide in their unspecialized form
  21139. // since only one will be chosen for a given concrete type
  21140. if (!mIsComptimeModule)
  21141. methodInstance->mMangleWithIdx = true;
  21142. mangledName.Clear();
  21143. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21144. BfLogSysM("Function collision forced mangleWithIdx for %p: %d GenericArgs: %d Unspecialized: %d\n", methodInstance, prevFunc.mId, methodInstance->GetNumGenericArguments(), methodInstance->mIsUnspecialized);
  21145. }
  21146. else
  21147. {
  21148. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  21149. if (!mIsComptimeModule)
  21150. mBfIRBuilder->Func_SafeRenameFrom(prevFunc, mangledName);
  21151. }
  21152. }
  21153. }
  21154. if (typeInstance != mContext->mBfObjectType)
  21155. {
  21156. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  21157. GetMethodCustomAttributes(methodInstance);
  21158. }
  21159. bool isIntrinsic = false;
  21160. if (!methodInstance->mIRFunction)
  21161. {
  21162. BfIRFunction func;
  21163. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  21164. (!methodDef->IsEmptyPartial())) && (funcType);
  21165. if (wantsLLVMFunc)
  21166. {
  21167. func = GetIntrinsic(methodInstance, true);
  21168. if (func)
  21169. {
  21170. isIntrinsic = true;
  21171. }
  21172. else
  21173. {
  21174. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  21175. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  21176. if (methodInstance->mAlwaysInline)
  21177. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  21178. }
  21179. methodInstance->mIRFunction = func;
  21180. }
  21181. }
  21182. if (outIsIntrinsic != NULL)
  21183. *outIsIntrinsic = isIntrinsic;
  21184. if (!isIntrinsic)
  21185. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  21186. }
  21187. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  21188. {
  21189. if (methodInstance->mHotMethod != NULL)
  21190. return;
  21191. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  21192. {
  21193. auto srcTypeInst = methodInstance->GetOwner();
  21194. if (srcTypeInst->mHotTypeData == NULL)
  21195. return;
  21196. StringT<128> mangledName = inMangledName;
  21197. if (mangledName.IsEmpty())
  21198. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21199. // We always keep the current primary method at the same address
  21200. BfHotMethod* hotMethod;
  21201. BfHotMethod** hotMethodPtr;
  21202. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  21203. {
  21204. hotMethod = new BfHotMethod();
  21205. *hotMethodPtr = hotMethod;
  21206. hotMethod->mRefCount = 1;
  21207. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21208. #ifdef BF_DBG_HOTMETHOD_IDX
  21209. static int sMethodIdx = 0;
  21210. hotMethod->mMethodIdx = sMethodIdx++;
  21211. #endif
  21212. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21213. }
  21214. else
  21215. {
  21216. hotMethod = *hotMethodPtr;
  21217. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  21218. {
  21219. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  21220. auto prevHotMethod = *hotMethodPtr;
  21221. hotMethod = new BfHotMethod();
  21222. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21223. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  21224. hotDupMethod->mRefCount++;
  21225. prevHotMethod->mReferences.Add(hotDupMethod);
  21226. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  21227. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21228. }
  21229. else if (mCompiler->IsHotCompile())
  21230. {
  21231. // Link the previous version into the mPrevVersion
  21232. BfHotMethod* prevMethod = new BfHotMethod();
  21233. prevMethod->mRefCount = 1;
  21234. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  21235. hotMethod->mPrevVersion = prevMethod;
  21236. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  21237. hotMethod->mSrcTypeVersion = NULL;
  21238. prevMethod->mFlags = hotMethod->mFlags;
  21239. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  21240. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  21241. #ifdef BF_DBG_HOTMETHOD_NAME
  21242. prevMethod->mMangledName = hotMethod->mMangledName;
  21243. #endif
  21244. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  21245. }
  21246. else
  21247. {
  21248. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  21249. hotMethod->Clear(true);
  21250. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  21251. }
  21252. }
  21253. if (methodInstance->mIsClosure)
  21254. {
  21255. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  21256. }
  21257. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  21258. hotMethod->mSrcTypeVersion->mRefCount++;
  21259. hotMethod->mRefCount++;
  21260. #ifdef BF_DBG_HOTMETHOD_NAME
  21261. hotMethod->mMangledName = mangledName;
  21262. #endif
  21263. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  21264. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  21265. methodInstance->mHotMethod = hotMethod;
  21266. }
  21267. }
  21268. static void StackOverflow()
  21269. {
  21270. int i = 0;
  21271. if (i == 0)
  21272. StackOverflow();
  21273. }
  21274. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  21275. {
  21276. methodInstance->mHasStartedDeclaration = true;
  21277. auto methodDef = methodInstance->mMethodDef;
  21278. auto typeInstance = methodInstance->GetOwner();
  21279. bool hasNonGenericParams = false;
  21280. bool hasGenericParams = false;
  21281. int dependentGenericStartIdx = 0;
  21282. if (methodDef->mIsLocalMethod)
  21283. {
  21284. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  21285. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  21286. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  21287. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  21288. // over the local method each time
  21289. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  21290. dependentGenericStartIdx = 0;
  21291. if (rootMethodInstance != NULL)
  21292. {
  21293. if (rootMethodInstance->mMethodInfoEx != NULL)
  21294. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  21295. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  21296. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  21297. }
  21298. }
  21299. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  21300. {
  21301. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  21302. if (genericArgType->IsGenericParam())
  21303. {
  21304. hasGenericParams = true;
  21305. auto genericParam = (BfGenericParamType*)genericArgType;
  21306. methodInstance->mIsUnspecialized = true;
  21307. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  21308. methodInstance->mIsUnspecializedVariation = true;
  21309. }
  21310. else
  21311. {
  21312. hasNonGenericParams = true;
  21313. if (genericArgType->IsUnspecializedType())
  21314. {
  21315. methodInstance->mIsUnspecialized = true;
  21316. methodInstance->mIsUnspecializedVariation = true;
  21317. }
  21318. }
  21319. }
  21320. if ((hasGenericParams) && (hasNonGenericParams))
  21321. {
  21322. methodInstance->mIsUnspecializedVariation = true;
  21323. }
  21324. if (typeInstance->IsUnspecializedType())
  21325. {
  21326. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  21327. // actually want to do method processing on it
  21328. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  21329. methodInstance->mIsUnspecializedVariation = true;
  21330. methodInstance->mIsUnspecialized = true;
  21331. }
  21332. if (methodInstance->mIsUnspecializedVariation)
  21333. BF_ASSERT(methodInstance->mIsUnspecialized);
  21334. //TODO: Why did we do this?
  21335. if (methodDef->mMethodType == BfMethodType_Mixin)
  21336. {
  21337. if (methodInstance->IsSpecializedGenericMethod())
  21338. methodInstance->mIsUnspecializedVariation = true;
  21339. methodInstance->mIsUnspecialized = true;
  21340. }
  21341. }
  21342. // methodDeclaration is NULL for default constructors
  21343. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  21344. {
  21345. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  21346. BP_ZONE("BfModule::DoMethodDeclaration");
  21347. auto typeInstance = mCurTypeInstance;
  21348. auto typeDef = typeInstance->mTypeDef;
  21349. auto methodDef = mCurMethodInstance->mMethodDef;
  21350. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  21351. // to effectively make mIgnoreWrites method-scoped
  21352. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  21353. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  21354. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  21355. BfTypeState typeState(mCurTypeInstance);
  21356. typeState.mPrevState = mContext->mCurTypeState;
  21357. typeState.mCurMethodDef = methodDef;
  21358. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21359. BfModule* resolveModule = mContext->mUnreifiedModule;
  21360. if (mCompiler->IsAutocomplete())
  21361. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  21362. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  21363. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21364. BfMethodState methodState;
  21365. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  21366. methodState.mTempKind = BfMethodState::TempKind_Static;
  21367. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  21368. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  21369. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  21370. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  21371. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  21372. // {
  21373. // BF_ASSERT(mContext->mResolvingVarField);
  21374. // isTemporaryFunc = true;
  21375. // }
  21376. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  21377. FinishInit();
  21378. if (methodDef->mName.StartsWith('_'))
  21379. {
  21380. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  21381. if (methodDef->mName == "__FATALERRORNAME")
  21382. BFMODULE_FATAL(this, "__FATALERRORNAME");
  21383. if (methodDef->mName == "__STACKOVERFLOW")
  21384. StackOverflow();
  21385. if (methodDef->mName == "__INTERNALERROR")
  21386. InternalError("Bad method name", methodDef->GetRefNode());
  21387. }
  21388. if (typeInstance->IsClosure())
  21389. {
  21390. if (methodDef->mName == "Invoke")
  21391. return;
  21392. }
  21393. auto methodInstance = mCurMethodInstance;
  21394. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  21395. addToWorkList = false;
  21396. if (!methodInstance->mHasStartedDeclaration)
  21397. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  21398. BfAutoComplete* bfAutocomplete = NULL;
  21399. if (mCompiler->mResolvePassData != NULL)
  21400. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  21401. if (methodInstance->mMethodInfoEx != NULL)
  21402. {
  21403. BfTypeInstance* unspecializedTypeInstance = NULL;
  21404. Array<BfTypeReference*> deferredResolveTypes;
  21405. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  21406. {
  21407. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  21408. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21409. {
  21410. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  21411. }
  21412. else
  21413. {
  21414. auto externConstraintDef = genericParam->GetExternConstraintDef();
  21415. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  21416. auto autoComplete = mCompiler->GetAutoComplete();
  21417. if (autoComplete != NULL)
  21418. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  21419. if (genericParam->mExternType != NULL)
  21420. {
  21421. //
  21422. }
  21423. else
  21424. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  21425. }
  21426. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  21427. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  21428. {
  21429. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  21430. if (bfAutocomplete != NULL)
  21431. {
  21432. for (auto nameNode : genericParamDef->mNameNodes)
  21433. {
  21434. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  21435. }
  21436. }
  21437. }
  21438. }
  21439. for (auto typeRef : deferredResolveTypes)
  21440. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  21441. if (methodInstance->mMethodInfoEx != NULL)
  21442. {
  21443. ValidateGenericParams(BfGenericParamKind_Method,
  21444. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  21445. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  21446. }
  21447. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  21448. AddDependency(genericParam, mCurTypeInstance);
  21449. }
  21450. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  21451. {
  21452. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  21453. BfAstNode* nameNode = methodDeclaration->mNameNode;
  21454. if (nameNode == NULL)
  21455. {
  21456. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  21457. nameNode = ctorDeclaration->mThisToken;
  21458. }
  21459. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  21460. {
  21461. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  21462. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  21463. autoComplete->mDefType = typeDef;
  21464. autoComplete->mDefMethod = methodDef;
  21465. autoComplete->SetDefinitionLocation(nameNode);
  21466. if (methodDef->mIsOverride)
  21467. {
  21468. bool found = false;
  21469. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  21470. {
  21471. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  21472. if (ventry.mDeclaringMethod.mMethodNum == -1)
  21473. continue;
  21474. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  21475. if (virtMethod != NULL)
  21476. {
  21477. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  21478. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  21479. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  21480. {
  21481. // Is matching method
  21482. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  21483. {
  21484. auto baseType = typeInstance->mBaseType;
  21485. if (baseType != NULL)
  21486. {
  21487. found = true;
  21488. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  21489. baseType = baseType->mBaseType;
  21490. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  21491. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  21492. autoComplete->mDefType = baseType->mTypeDef;
  21493. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  21494. }
  21495. }
  21496. break;
  21497. }
  21498. }
  21499. }
  21500. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  21501. {
  21502. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  21503. {
  21504. auto defaultMethod = methodGroup.mDefault;
  21505. if (defaultMethod == NULL)
  21506. continue;
  21507. if (!defaultMethod->mMethodDef->mIsExtern)
  21508. continue;
  21509. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  21510. continue;
  21511. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  21512. autoComplete->mDefType = typeInstance->mTypeDef;
  21513. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  21514. }
  21515. }
  21516. }
  21517. }
  21518. }
  21519. bool reportErrors = true;
  21520. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  21521. reportErrors = true;
  21522. // Only the defining contexts needs to report errors here
  21523. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  21524. if (methodDef->mMethodType == BfMethodType_Dtor)
  21525. {
  21526. if (methodDef->mIsStatic)
  21527. {
  21528. }
  21529. else
  21530. {
  21531. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  21532. {
  21533. BfAstNode* refNode = methodDeclaration;
  21534. if (refNode == NULL)
  21535. {
  21536. // Whatever caused this ctor to be generated should have caused another failure
  21537. // But that failure might not be generated until the ctor is generated
  21538. }
  21539. else
  21540. {
  21541. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  21542. if (dtorDecl != NULL)
  21543. refNode = dtorDecl->mThisToken;
  21544. Fail("Structs cannot have destructors", refNode);
  21545. }
  21546. }
  21547. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21548. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  21549. (mCurTypeInstance != mContext->mBfObjectType))
  21550. {
  21551. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  21552. }
  21553. }
  21554. }
  21555. BfType* resolvedReturnType = NULL;
  21556. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  21557. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  21558. (methodDef->mReturnTypeRef != NULL))
  21559. {
  21560. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  21561. if (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>())
  21562. {
  21563. // An invalid 'var' error would not have been caught in the original property type pass
  21564. mIgnoreErrors = false;
  21565. }
  21566. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_NoReify);
  21567. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  21568. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  21569. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21570. else
  21571. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  21572. if (resolvedReturnType == NULL)
  21573. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  21574. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  21575. {
  21576. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  21577. if (methodDeclaration->mReadOnlySpecifier != NULL)
  21578. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  21579. }
  21580. }
  21581. else
  21582. {
  21583. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  21584. }
  21585. BF_ASSERT(resolvedReturnType != NULL);
  21586. mCurMethodInstance->mReturnType = resolvedReturnType;
  21587. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  21588. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  21589. //if (!methodInstance->IsSpecializedGenericMethod())
  21590. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21591. if (methodDef->mExplicitInterface != NULL)
  21592. {
  21593. auto autoComplete = mCompiler->GetAutoComplete();
  21594. if (autoComplete != NULL)
  21595. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  21596. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  21597. BfTypeInstance* explicitInterface = NULL;
  21598. if (explicitType != NULL)
  21599. explicitInterface = explicitType->ToTypeInstance();
  21600. if (explicitInterface != NULL)
  21601. {
  21602. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  21603. if (autoComplete != NULL)
  21604. {
  21605. BfTokenNode* dotToken = NULL;
  21606. BfAstNode* nameNode = NULL;
  21607. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  21608. {
  21609. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  21610. nameNode = methodDeclaration->mNameNode;
  21611. }
  21612. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  21613. }
  21614. }
  21615. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  21616. {
  21617. bool interfaceFound = false;
  21618. for (auto ifaceInst : typeInstance->mInterfaces)
  21619. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  21620. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  21621. {
  21622. if (methodDef->mMethodDeclaration != NULL)
  21623. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  21624. else
  21625. {
  21626. // For property decls, we should have already given the error during type population
  21627. if (mCompiler->mRevision == 1)
  21628. AssertErrorState();
  21629. }
  21630. }
  21631. }
  21632. }
  21633. bool isThisStruct = mCurTypeInstance->IsStruct();
  21634. BfType* thisType = NULL;
  21635. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  21636. {
  21637. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  21638. {
  21639. thisType = mCurTypeInstance;
  21640. if (thisType == NULL)
  21641. return;
  21642. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  21643. {
  21644. BfTypeUtils::SplatIterate([&](BfType* checkType)
  21645. {
  21646. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  21647. }, thisType);
  21648. }
  21649. }
  21650. else
  21651. {
  21652. thisType = mCurTypeInstance;
  21653. resolveModule->PopulateType(thisType, BfPopulateType_Declaration);
  21654. }
  21655. }
  21656. int implicitParamCount = 0;
  21657. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  21658. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  21659. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  21660. bool hadDelegateParams = false;
  21661. bool hadParams = false;
  21662. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  21663. {
  21664. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  21665. BfParameterDef* paramDef = NULL;
  21666. int paramDefIdx = -1;
  21667. if (paramIdx < implicitParamCount)
  21668. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  21669. else
  21670. {
  21671. paramDefIdx = paramIdx - implicitParamCount;
  21672. paramDef = methodDef->mParams[paramDefIdx];
  21673. }
  21674. if (hadParams)
  21675. break;
  21676. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  21677. continue;
  21678. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  21679. (paramDef->mParamKind != BfParamKind_AppendIdx))
  21680. {
  21681. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  21682. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  21683. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  21684. }
  21685. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  21686. {
  21687. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  21688. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  21689. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  21690. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  21691. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  21692. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  21693. }
  21694. BfType* resolvedParamType = NULL;
  21695. if (closureCaptureEntry != NULL)
  21696. resolvedParamType = closureCaptureEntry->mType;
  21697. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  21698. {
  21699. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  21700. resolvedParamType = mContext->mBfObjectType;
  21701. }
  21702. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  21703. {
  21704. if (methodDef->mMethodType != BfMethodType_Mixin)
  21705. {
  21706. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  21707. resolvedParamType = mContext->mBfObjectType;
  21708. }
  21709. else
  21710. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21711. }
  21712. BfType* unresolvedParamType = resolvedParamType;
  21713. bool wasGenericParam = false;
  21714. if (resolvedParamType == NULL)
  21715. {
  21716. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue | BfResolveTypeRefFlag_NoReify);
  21717. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  21718. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  21719. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  21720. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  21721. resolvedParamType = resolvedParamType->GetUnderlyingType();
  21722. }
  21723. if (resolvedParamType == NULL)
  21724. {
  21725. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  21726. unresolvedParamType = resolvedParamType;
  21727. if (mCurTypeInstance->IsBoxed())
  21728. {
  21729. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  21730. // If we failed a lookup here then we better have also failed it in the original type
  21731. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.ContainsKey(boxedType->mElementType->ToTypeInstance()));
  21732. }
  21733. }
  21734. BF_ASSERT(!resolvedParamType->IsDeleting());
  21735. if (!methodInstance->IsSpecializedGenericMethod())
  21736. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21737. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  21738. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  21739. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  21740. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  21741. {
  21742. if (paramDef->mParamKind == BfParamKind_Params)
  21743. {
  21744. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  21745. if (refNode != NULL)
  21746. refNode = paramDef->mParamDeclaration->mModToken;
  21747. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  21748. }
  21749. BfTypedValue defaultValue;
  21750. if (resolvedParamType->IsConstExprValue())
  21751. {
  21752. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  21753. BfExprEvaluator exprEvaluator(this);
  21754. exprEvaluator.mExpectingType = constExprType->mType;
  21755. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  21756. defaultValue = exprEvaluator.GetResult();
  21757. }
  21758. else
  21759. {
  21760. BfTypeState typeState;
  21761. typeState.mType = mCurTypeInstance;
  21762. typeState.mCurTypeDef = methodDef->mDeclaringType;
  21763. //typeState.mCurMethodDef = methodDef;
  21764. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  21765. BfConstResolver constResolver(this);
  21766. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  21767. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  21768. {
  21769. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  21770. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  21771. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  21772. {
  21773. defaultValue = castedDefaultValue; // Good!
  21774. }
  21775. else if (!CanCast(defaultValue, resolvedParamType))
  21776. {
  21777. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  21778. // a conversion operator.
  21779. // This should throw an error
  21780. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  21781. AssertErrorState();
  21782. if (!defaultValue.mValue.IsConst())
  21783. defaultValue = BfTypedValue();
  21784. }
  21785. }
  21786. }
  21787. if (!defaultValue)
  21788. {
  21789. defaultValue = GetDefaultTypedValue(resolvedParamType);
  21790. if (!defaultValue.mValue.IsConst())
  21791. defaultValue = BfTypedValue();
  21792. }
  21793. if (defaultValue)
  21794. {
  21795. if (defaultValue.mType->IsVar())
  21796. {
  21797. AssertErrorState();
  21798. }
  21799. else
  21800. {
  21801. BF_ASSERT(defaultValue.mValue.IsConst());
  21802. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  21803. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  21804. CurrentAddToConstHolder(defaultValue.mValue);
  21805. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  21806. }
  21807. }
  21808. }
  21809. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  21810. {
  21811. bool addParams = true;
  21812. bool isValid = false;
  21813. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  21814. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  21815. {
  21816. // Span<T>
  21817. isValid = true;
  21818. }
  21819. else if (resolvedParamType->IsArray())
  21820. {
  21821. // Array is the 'normal' params type
  21822. isValid = true;
  21823. }
  21824. else if (resolvedParamType->IsSizedArray())
  21825. {
  21826. isValid = true;
  21827. }
  21828. else if (resolvedParamType->IsVar())
  21829. {
  21830. isValid = true;
  21831. }
  21832. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  21833. {
  21834. hadDelegateParams = true;
  21835. // This means we copy the params from a delegate
  21836. BfMethodParam methodParam;
  21837. methodParam.mResolvedType = resolvedParamType;
  21838. methodParam.mParamDefIdx = paramDefIdx;
  21839. methodParam.mDelegateParamIdx = 0;
  21840. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21841. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  21842. {
  21843. methodParam.mDelegateParamIdx = delegateParamIdx;
  21844. mCurMethodInstance->mParams.Add(methodParam);
  21845. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  21846. if (!methodInstance->IsSpecializedGenericMethod())
  21847. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21848. }
  21849. isValid = true;
  21850. addParams = false;
  21851. }
  21852. else if (resolvedParamType->IsTuple())
  21853. {
  21854. auto tupleType = (BfTupleType*)resolvedParamType;
  21855. PopulateType(tupleType);
  21856. hadDelegateParams = true;
  21857. // This means we copy the params from a delegate
  21858. BfMethodParam methodParam;
  21859. methodParam.mResolvedType = resolvedParamType;
  21860. methodParam.mParamDefIdx = paramDefIdx;
  21861. methodParam.mDelegateParamIdx = 0;
  21862. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21863. for (int delegateParamIdx = 0; delegateParamIdx < tupleType->mFieldInstances.mSize; delegateParamIdx++)
  21864. {
  21865. auto& fieldInstance = tupleType->mFieldInstances[delegateParamIdx];
  21866. methodParam.mDelegateParamIdx = delegateParamIdx;
  21867. mCurMethodInstance->mParams.Add(methodParam);
  21868. if (!methodInstance->IsSpecializedGenericMethod())
  21869. AddDependency(fieldInstance.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21870. }
  21871. isValid = true;
  21872. addParams = false;
  21873. }
  21874. else if (resolvedParamType->IsGenericParam())
  21875. {
  21876. bool isGenericDelegateParams = false;
  21877. bool addDelegateParamsType = false;
  21878. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType, false, BfFailHandleKind_Ignore);
  21879. if (genericParamInstance == NULL)
  21880. {
  21881. // Delegate case with a 'params T'?
  21882. isGenericDelegateParams = true;
  21883. addDelegateParamsType = true;
  21884. }
  21885. else if (genericParamInstance->mTypeConstraint != NULL)
  21886. {
  21887. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  21888. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  21889. {
  21890. BfMethodParam methodParam;
  21891. methodParam.mResolvedType = resolvedParamType;
  21892. methodParam.mParamDefIdx = paramDefIdx;
  21893. mCurMethodInstance->mParams.Add(methodParam);
  21894. isValid = true;
  21895. }
  21896. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) || (genericParamInstance->mTypeConstraint->IsTuple()) ||
  21897. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  21898. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef)))))
  21899. {
  21900. isGenericDelegateParams = true;
  21901. //addDelegateParamsType = typeInstConstraint->IsInstanceOf(mCompiler->mTupleTypeDef);
  21902. addDelegateParamsType = true;
  21903. }
  21904. }
  21905. if (isGenericDelegateParams)
  21906. {
  21907. mCurMethodInstance->mHadGenericDelegateParams = true;
  21908. isValid = true;
  21909. addParams = false;
  21910. if (addDelegateParamsType)
  21911. {
  21912. BfMethodParam methodParam;
  21913. methodParam.mResolvedType = CreateModifiedTypeType(resolvedParamType, BfToken_Params);
  21914. methodParam.mParamDefIdx = paramDefIdx;
  21915. mCurMethodInstance->mParams.Add(methodParam);
  21916. //TODO: Why do we have this 'if'
  21917. if (!methodInstance->IsSpecializedGenericMethod())
  21918. AddDependency(methodParam.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  21919. }
  21920. }
  21921. }
  21922. else
  21923. {
  21924. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  21925. if ((paramTypeInst != NULL) &&
  21926. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mTupleTypeDef))))
  21927. {
  21928. // If we have a 'params T' and 'T' gets specialized with actually 'Tuple', 'Delegate' or 'Function' then just ignore it
  21929. isValid = true;
  21930. addParams = false;
  21931. }
  21932. }
  21933. if (!isValid)
  21934. {
  21935. Fail("Parameters with 'params' specifiers can only be used for array, span, tuple, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  21936. // Failure case, make it an Object[]
  21937. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  21938. }
  21939. if ((addParams) && (resolvedParamType != NULL))
  21940. {
  21941. BfMethodParam methodParam;
  21942. methodParam.mResolvedType = resolvedParamType;
  21943. methodParam.mParamDefIdx = paramDefIdx;
  21944. mCurMethodInstance->mParams.push_back(methodParam);
  21945. }
  21946. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  21947. {
  21948. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  21949. }
  21950. }
  21951. else
  21952. {
  21953. BfMethodParam methodParam;
  21954. methodParam.mResolvedType = resolvedParamType;
  21955. methodParam.mParamDefIdx = paramDefIdx;
  21956. mCurMethodInstance->mParams.Add(methodParam);
  21957. }
  21958. }
  21959. if (hadDelegateParams)
  21960. {
  21961. HashSet<String> usedNames;
  21962. Dictionary<int, int> usedParamDefIdx;
  21963. for (auto methodParam : methodDef->mParams)
  21964. {
  21965. usedNames.Add(methodParam->mName);
  21966. }
  21967. for (auto& methodParam : mCurMethodInstance->mParams)
  21968. {
  21969. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  21970. {
  21971. int* refCount = NULL;
  21972. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  21973. (*refCount)++;
  21974. }
  21975. }
  21976. for (auto& methodParam : mCurMethodInstance->mParams)
  21977. {
  21978. if (methodParam.mDelegateParamIdx != -1)
  21979. {
  21980. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  21981. methodParam.mDelegateParamNameCombine = true;
  21982. if (methodParam.mResolvedType->IsTuple())
  21983. {
  21984. auto tupleType = (BfTupleType*)methodParam.mResolvedType;
  21985. auto& fieldInstance = tupleType->mFieldInstances[methodParam.mDelegateParamIdx];
  21986. auto paramName = fieldInstance.GetFieldDef()->mName;
  21987. if ((!usedNames.Add(paramName)) || (::isdigit((uint8)paramName[0])))
  21988. methodParam.mDelegateParamNameCombine = true;
  21989. }
  21990. else
  21991. {
  21992. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  21993. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  21994. if (!usedNames.Add(paramName))
  21995. methodParam.mDelegateParamNameCombine = true;
  21996. }
  21997. }
  21998. }
  21999. }
  22000. int argIdx = 0;
  22001. resolveModule->PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  22002. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  22003. {
  22004. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  22005. auto thisType = methodInstance->GetOwner();
  22006. if (methodInstance->GetParamIsSplat(thisIdx))
  22007. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  22008. else if (!thisType->IsValuelessType())
  22009. {
  22010. BfTypeCode loweredTypeCode = BfTypeCode_None;
  22011. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  22012. if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (!methodInstance->ForcingThisPtr()))
  22013. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  22014. argIdx++;
  22015. if (loweredTypeCode2 != BfTypeCode_None)
  22016. argIdx++;
  22017. }
  22018. }
  22019. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  22020. argIdx++;
  22021. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  22022. {
  22023. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  22024. BfType* checkType = methodParam.mResolvedType;
  22025. int checkArgIdx = argIdx;
  22026. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  22027. {
  22028. checkArgIdx = 0;
  22029. checkType = methodInstance->GetThisType();
  22030. }
  22031. if (checkType->IsMethodRef())
  22032. {
  22033. methodParam.mIsSplat = true;
  22034. }
  22035. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  22036. {
  22037. resolveModule->PopulateType(checkType, BfPopulateType_Data);
  22038. if (checkType->IsSplattable())
  22039. {
  22040. bool isSplat = false;
  22041. auto checkTypeInstance = checkType->ToTypeInstance();
  22042. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  22043. isSplat = true;
  22044. int splatCount = checkType->GetSplatCount();
  22045. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  22046. isSplat = true;
  22047. if (isSplat)
  22048. {
  22049. methodParam.mIsSplat = true;
  22050. argIdx += splatCount;
  22051. continue;
  22052. }
  22053. }
  22054. else if (!checkType->IsValuelessType())
  22055. {
  22056. BfTypeCode loweredTypeCode = BfTypeCode_None;
  22057. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  22058. if (!mIsComptimeModule)
  22059. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  22060. argIdx++;
  22061. if (loweredTypeCode2 != BfTypeCode_None)
  22062. argIdx++;
  22063. continue;
  22064. }
  22065. }
  22066. argIdx++;
  22067. }
  22068. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  22069. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  22070. {
  22071. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  22072. }
  22073. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  22074. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  22075. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  22076. (!methodDef->mIsSkipCall))
  22077. {
  22078. if (methodDeclaration->mEndSemicolon == NULL)
  22079. {
  22080. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  22081. {
  22082. //
  22083. }
  22084. else
  22085. AssertParseErrorState();
  22086. }
  22087. else
  22088. {
  22089. bool isError = true;
  22090. if (typeInstance->IsTypedPrimitive())
  22091. {
  22092. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  22093. {
  22094. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  22095. {
  22096. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  22097. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  22098. {
  22099. isError = false;
  22100. }
  22101. else if (mCurTypeInstance->IsEnum())
  22102. {
  22103. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0)->IsInteger())) ||
  22104. ((methodInstance->mReturnType->IsInteger()) && (methodInstance->GetParamType(0) == typeInstance)))
  22105. {
  22106. isError = false;
  22107. }
  22108. }
  22109. }
  22110. }
  22111. }
  22112. if (isError)
  22113. {
  22114. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  22115. MethodToString(methodInstance).c_str()),
  22116. methodDef->GetRefNode());
  22117. }
  22118. }
  22119. }
  22120. if (methodDef->IsEmptyPartial())
  22121. hasExternSpecifier = true;
  22122. if (!methodInstance->IsAutocompleteMethod())
  22123. {
  22124. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  22125. int implicitParamCount = methodInstance->GetImplicitParamCount();
  22126. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  22127. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  22128. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  22129. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  22130. int paramIdx = 0;
  22131. int defaultParamIdx = 0;
  22132. while (true)
  22133. {
  22134. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  22135. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  22136. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  22137. {
  22138. paramIdx++;
  22139. continue;
  22140. }
  22141. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  22142. {
  22143. defaultParamIdx++;
  22144. continue;
  22145. }
  22146. if ((isDone) || (isDefaultDone))
  22147. {
  22148. // 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
  22149. // to cause us to throw an assertion in the declaration here
  22150. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  22151. BF_ASSERT((isDone) && (isDefaultDone));
  22152. break;
  22153. }
  22154. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  22155. if (paramType->IsRef())
  22156. paramType = paramType->GetUnderlyingType();
  22157. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  22158. paramIdx++;
  22159. defaultParamIdx++;
  22160. }
  22161. }
  22162. StringT<4096> mangledName;
  22163. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  22164. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  22165. {
  22166. auto paramType = methodInstance->GetParamType(paramIdx);
  22167. if (paramType->IsComposite())
  22168. resolveModule->PopulateType(paramType, BfPopulateType_Data);
  22169. if (!methodInstance->IsParamSkipped(paramIdx))
  22170. {
  22171. if (paramType->IsStruct())
  22172. {
  22173. //
  22174. }
  22175. else
  22176. {
  22177. PopulateType(paramType, BfPopulateType_Declaration);
  22178. }
  22179. }
  22180. }
  22181. // Only process method in default unspecialized mode, not in variations
  22182. if (methodInstance->mIsUnspecializedVariation)
  22183. return;
  22184. resolveModule->PopulateType(resolvedReturnType, BfPopulateType_Data);
  22185. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  22186. if (resolvedReturnType->IsValuelessType())
  22187. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  22188. if (!mBfIRBuilder->mIgnoreWrites)
  22189. {
  22190. bool isIntrinsic = false;
  22191. if (!methodInstance->mIRFunction)
  22192. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  22193. if (isIntrinsic)
  22194. {
  22195. addToWorkList = false;
  22196. }
  22197. }
  22198. else
  22199. {
  22200. GetMethodCustomAttributes(methodInstance);
  22201. }
  22202. auto func = methodInstance->mIRFunction;
  22203. // if (methodInstance->mIsReified)
  22204. // CheckHotMethod(methodInstance, mangledName);
  22205. for (auto& param : methodInstance->mParams)
  22206. {
  22207. BF_ASSERT(!param.mResolvedType->IsDeleting());
  22208. }
  22209. 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);
  22210. SizedArray<BfIRMDNode, 8> diParams;
  22211. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  22212. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  22213. {
  22214. //CS0708
  22215. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  22216. }
  22217. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  22218. {
  22219. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  22220. methodDef->mIsVirtual = false;
  22221. }
  22222. BfAstNode* mutSpecifier = NULL;
  22223. if (methodDeclaration != NULL)
  22224. mutSpecifier = methodDeclaration->mMutSpecifier;
  22225. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  22226. {
  22227. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  22228. if (mutSpecifier == NULL)
  22229. {
  22230. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22231. if (propertyDeclaration != NULL)
  22232. {
  22233. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  22234. mutSpecifier = propExprBody->mMutSpecifier;
  22235. }
  22236. }
  22237. }
  22238. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  22239. {
  22240. if (methodDef->mIsStatic)
  22241. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  22242. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  22243. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  22244. else if (methodDef->mMethodType == BfMethodType_Ctor)
  22245. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  22246. else if (methodDef->mMethodType == BfMethodType_Dtor)
  22247. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  22248. }
  22249. if (isTemporaryFunc)
  22250. {
  22251. // This handles temporary methods for autocomplete types
  22252. //BF_ASSERT(mIsScratchModule);
  22253. //BF_ASSERT(mCompiler->IsAutocomplete());
  22254. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  22255. return; // Bail out early for autocomplete pass
  22256. }
  22257. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  22258. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  22259. // autocompleter. Why did we have this check anyway?
  22260. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  22261. {
  22262. AddMethodReference(methodInstance);
  22263. mFuncReferences[methodInstance] = func;
  22264. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  22265. }*/
  22266. if (mParentModule != NULL)
  22267. {
  22268. // For extension modules we need to keep track of our own methods so we can know which methods
  22269. // we have defined ourselves and which are from the parent module or other extensions
  22270. if (!func.IsFake())
  22271. {
  22272. if (func)
  22273. mFuncReferences[methodInstance] = func;
  22274. }
  22275. }
  22276. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  22277. {
  22278. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  22279. auto owningModule = methodInstance->GetOwner()->mModule;
  22280. if (!owningModule->mIsScratchModule)
  22281. owningModule->mOnDemandMethodCount++;
  22282. VerifyOnDemandMethods();
  22283. }
  22284. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  22285. if (wasAwaitingDecl)
  22286. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  22287. if (addToWorkList)
  22288. {
  22289. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  22290. {
  22291. AddMethodToWorkList(methodInstance);
  22292. }
  22293. else
  22294. {
  22295. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  22296. methodInstance->mIgnoreBody = true;
  22297. if (typeInstance->IsUnspecializedType())
  22298. {
  22299. // Don't hold on to actual Function for unspecialized types
  22300. methodInstance->mIRFunction = BfIRFunction();
  22301. }
  22302. }
  22303. }
  22304. else
  22305. {
  22306. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  22307. }
  22308. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  22309. (!methodDef->mIsLocalMethod) &&
  22310. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  22311. (!methodDef->mReturnTypeRef->IsTemporary()))
  22312. {
  22313. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  22314. {
  22315. //TODO:
  22316. //CS0053
  22317. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  22318. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22319. methodDef->mReturnTypeRef, true);
  22320. }
  22321. else
  22322. {
  22323. //CS0050
  22324. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  22325. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  22326. methodDef->mReturnTypeRef, true);
  22327. }
  22328. }
  22329. if (typeInstance->IsInterface())
  22330. {
  22331. if (methodDef->mMethodType == BfMethodType_Ctor)
  22332. Fail("Interfaces cannot contain constructors", methodDeclaration);
  22333. if (methodDeclaration != NULL)
  22334. {
  22335. if (methodDef->mBody == NULL)
  22336. {
  22337. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  22338. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  22339. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  22340. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  22341. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  22342. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  22343. }
  22344. }
  22345. }
  22346. bool foundHiddenMethod = false;
  22347. BfTokenNode* virtualToken = NULL;
  22348. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22349. if (propertyDeclaration != NULL)
  22350. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22351. else if (methodDeclaration != NULL)
  22352. virtualToken = methodDeclaration->mVirtualSpecifier;
  22353. // Don't compare specialized generic methods against normal methods
  22354. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  22355. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  22356. {
  22357. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  22358. {
  22359. typeDef->PopulateMemberSets();
  22360. BfMethodDef* nextMethod = NULL;
  22361. BfMemberSetEntry* entry = NULL;
  22362. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22363. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22364. while (nextMethod != NULL)
  22365. {
  22366. auto checkMethod = nextMethod;
  22367. nextMethod = nextMethod->mNextWithSameName;
  22368. if (checkMethod == methodDef)
  22369. continue;
  22370. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22371. if (checkMethodInstance == NULL)
  22372. {
  22373. if (methodDef->mDeclaringType->IsExtension())
  22374. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  22375. if (checkMethodInstance == NULL)
  22376. continue;
  22377. }
  22378. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  22379. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22380. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  22381. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22382. {
  22383. bool canChain = false;
  22384. if ((methodDef->mParams.empty()) &&
  22385. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  22386. {
  22387. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  22388. canChain = true;
  22389. else if (methodDef->mMethodType == BfMethodType_Normal)
  22390. {
  22391. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  22392. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  22393. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  22394. canChain = true;
  22395. }
  22396. }
  22397. if (canChain)
  22398. {
  22399. bool isBetter;
  22400. bool isWorse;
  22401. CompareDeclTypes(typeInstance, checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  22402. if (isBetter && !isWorse)
  22403. {
  22404. methodInstance->mChainType = BfMethodChainType_ChainHead;
  22405. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  22406. }
  22407. else
  22408. {
  22409. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  22410. methodInstance->mChainType = BfMethodChainType_ChainMember;
  22411. }
  22412. }
  22413. else
  22414. {
  22415. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  22416. continue;
  22417. bool silentlyAllow = false;
  22418. bool extensionWarn = false;
  22419. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  22420. {
  22421. if (typeInstance->IsInterface())
  22422. {
  22423. if (methodDef->mIsOverride)
  22424. silentlyAllow = true;
  22425. }
  22426. else
  22427. {
  22428. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  22429. {
  22430. silentlyAllow = true;
  22431. methodInstance->mIsInnerOverride = true;
  22432. CheckOverridenMethod(methodInstance, checkMethodInstance);
  22433. }
  22434. else if (!checkMethod->mDeclaringType->IsExtension())
  22435. {
  22436. foundHiddenMethod = true;
  22437. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  22438. silentlyAllow = true;
  22439. else if (methodDef->mIsNew)
  22440. {
  22441. silentlyAllow = true;
  22442. }
  22443. else if (checkMethod->GetMethodDeclaration() == NULL)
  22444. silentlyAllow = true;
  22445. else if (methodDef->mIsOverride)
  22446. silentlyAllow = true;
  22447. else
  22448. extensionWarn = true;
  22449. }
  22450. else
  22451. silentlyAllow = true;
  22452. }
  22453. }
  22454. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  22455. silentlyAllow = true;
  22456. if (checkMethod->mMethodDeclaration == NULL)
  22457. {
  22458. // This can allow emission of a default ctor if we've already auto-added a default ctor
  22459. silentlyAllow = true;
  22460. }
  22461. if (checkMethod->mMethodType == BfMethodType_CtorCalcAppend)
  22462. {
  22463. // Only use the main ctor as the error method
  22464. silentlyAllow = true;
  22465. }
  22466. if (!silentlyAllow)
  22467. {
  22468. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  22469. {
  22470. auto refNode = methodDef->GetRefNode();
  22471. BfError* bfError;
  22472. if (extensionWarn)
  22473. {
  22474. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  22475. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22476. StrFormat("This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional. Note that this method is not callable from project '%s'.",
  22477. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  22478. else
  22479. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  22480. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  22481. }
  22482. else
  22483. {
  22484. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  22485. }
  22486. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  22487. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  22488. }
  22489. }
  22490. }
  22491. }
  22492. }
  22493. }
  22494. // Virtual methods give their error while slotting
  22495. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  22496. (!methodDef->mIsLocalMethod) &&
  22497. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  22498. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  22499. {
  22500. auto baseType = typeInstance->mBaseType;
  22501. while (baseType != NULL)
  22502. {
  22503. auto baseTypeDef = baseType->mTypeDef;
  22504. baseTypeDef->PopulateMemberSets();
  22505. BfMethodDef* checkMethod = NULL;
  22506. BfMemberSetEntry* entry = NULL;
  22507. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22508. checkMethod = (BfMethodDef*)entry->mMemberDef;
  22509. while (checkMethod != NULL)
  22510. {
  22511. if (checkMethod->mMethodDeclaration == NULL)
  22512. {
  22513. checkMethod = checkMethod->mNextWithSameName;
  22514. continue;
  22515. }
  22516. if (baseType->mMethodInstanceGroups.size() == 0)
  22517. {
  22518. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  22519. break;
  22520. }
  22521. if (checkMethod == methodDef)
  22522. {
  22523. checkMethod = checkMethod->mNextWithSameName;
  22524. continue;
  22525. }
  22526. if (checkMethod->mName != methodDef->mName)
  22527. {
  22528. checkMethod = checkMethod->mNextWithSameName;
  22529. continue;
  22530. }
  22531. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  22532. if (checkMethodInstance != NULL)
  22533. {
  22534. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  22535. (checkMethod->mProtection != BfProtection_Private) &&
  22536. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  22537. {
  22538. if ((!methodDef->mIsNew) && (!checkMethod->mDeclaringType->IsExtension()))
  22539. {
  22540. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  22541. if (refNode != NULL)
  22542. {
  22543. 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?
  22544. if (bfError != NULL)
  22545. {
  22546. bfError->mIsPersistent = true;
  22547. mCompiler->mPassInstance->MoreInfo("See inherited method", checkMethod->GetRefNode());
  22548. }
  22549. }
  22550. }
  22551. foundHiddenMethod = true;
  22552. break;
  22553. }
  22554. }
  22555. checkMethod = checkMethod->mNextWithSameName;
  22556. }
  22557. if (foundHiddenMethod)
  22558. break;
  22559. baseType = baseType->mBaseType;
  22560. }
  22561. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  22562. {
  22563. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22564. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  22565. methodDeclaration->mNewSpecifier;
  22566. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  22567. }
  22568. }
  22569. }
  22570. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  22571. {
  22572. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  22573. }
  22574. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  22575. {
  22576. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  22577. Fail("No suitable method found to override", virtualToken, true);
  22578. else
  22579. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  22580. }
  22581. else if (methodDef->mIsVirtual)
  22582. {
  22583. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  22584. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  22585. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  22586. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  22587. }
  22588. mCompiler->mStats.mMethodDeclarations++;
  22589. mCompiler->UpdateCompletion();
  22590. }
  22591. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  22592. {
  22593. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  22594. auto typeInstance = mCurTypeInstance;
  22595. auto methodDef = methodInstance->mMethodDef;
  22596. int virtualMethodMatchIdx = -1;
  22597. if (typeInstance->mHotTypeData != NULL)
  22598. {
  22599. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  22600. {
  22601. BF_ASSERT(mCompiler->IsHotCompile());
  22602. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  22603. // may slot this override anyway (?)
  22604. int vTableStart = 0;
  22605. auto implBaseType = typeInstance->GetImplBaseType();
  22606. if (implBaseType != NULL)
  22607. vTableStart = implBaseType->mVirtualMethodTableSize;
  22608. StringT<512> mangledName;
  22609. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  22610. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  22611. {
  22612. // O(1) checking when virtual methods haven't changed
  22613. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  22614. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  22615. if (mangledName == entry.mFuncName)
  22616. {
  22617. virtualMethodMatchIdx = vTableStart + checkIdx;
  22618. break;
  22619. }
  22620. }
  22621. if (virtualMethodMatchIdx != -1)
  22622. {
  22623. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22624. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  22625. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  22626. }
  22627. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  22628. }
  22629. }
  22630. if (virtualMethodMatchIdx == -1)
  22631. {
  22632. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  22633. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  22634. typeInstance->mVirtualMethodTable.push_back(entry);
  22635. }
  22636. }
  22637. void BfModule::CompareDeclTypes(BfTypeInstance* typeInst, BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  22638. {
  22639. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  22640. {
  22641. // When we provide an extension override in the same project a root type override
  22642. isBetter = true;
  22643. isWorse = false;
  22644. }
  22645. else
  22646. {
  22647. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22648. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22649. }
  22650. if ((isBetter == isWorse) && (typeInst != NULL) && (newDeclType->IsExtension()) && (prevDeclType->IsExtension()))
  22651. {
  22652. if ((typeInst->mGenericTypeInfo != NULL) && (typeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  22653. {
  22654. isBetter = false;
  22655. isWorse = false;
  22656. auto newConstraints = typeInst->GetGenericParamsVector(newDeclType);
  22657. auto prevConstraints = typeInst->GetGenericParamsVector(prevDeclType);
  22658. for (int genericIdx = 0; genericIdx < (int)newConstraints->size(); genericIdx++)
  22659. {
  22660. auto newConstraint = (*newConstraints)[genericIdx];
  22661. auto prevConstraint = (*prevConstraints)[genericIdx];
  22662. bool newIsSubset = AreConstraintsSubset(newConstraint, prevConstraint);
  22663. bool prevIsSubset = AreConstraintsSubset(prevConstraint, newConstraint);
  22664. if ((prevIsSubset) && (!newIsSubset))
  22665. isBetter = true;
  22666. if ((!prevIsSubset) && (newIsSubset))
  22667. isWorse = true;
  22668. }
  22669. }
  22670. }
  22671. }
  22672. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  22673. {
  22674. BP_ZONE("BfModule::SlotVirtualMethod");
  22675. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  22676. return false;
  22677. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  22678. {
  22679. if (!mCompiler->mOptions.mAllowHotSwapping)
  22680. return;
  22681. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  22682. return;
  22683. if (methodInstance->mHotMethod == NULL)
  22684. CheckHotMethod(methodInstance, "");
  22685. if (methodInstance->mHotMethod == NULL)
  22686. return;
  22687. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  22688. if (declMethodInstance->mHotMethod == NULL)
  22689. CheckHotMethod(declMethodInstance, "");
  22690. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  22691. virtualDecl->mRefCount++;
  22692. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  22693. };
  22694. auto typeInstance = mCurTypeInstance;
  22695. auto typeDef = typeInstance->mTypeDef;
  22696. auto methodDef = methodInstance->mMethodDef;
  22697. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22698. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  22699. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  22700. if (methodInstance->mIsInnerOverride)
  22701. return false;
  22702. BfAstNode* declaringNode = methodDeclaration;
  22703. if (propertyMethodDeclaration != NULL)
  22704. declaringNode = propertyMethodDeclaration->mNameNode;
  22705. BfMethodInstance* methodOverriden = NULL;
  22706. bool usedMethod = false;
  22707. BfTokenNode* virtualToken = NULL;
  22708. if (propertyDeclaration != NULL)
  22709. virtualToken = propertyDeclaration->mVirtualSpecifier;
  22710. else if (methodDeclaration != NULL)
  22711. virtualToken = methodDeclaration->mVirtualSpecifier;
  22712. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  22713. {
  22714. //Fail: Static members cannot be marked as override, virtual, or abstract
  22715. }
  22716. else if (methodDef->mIsVirtual)
  22717. {
  22718. if (IsHotCompile())
  22719. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  22720. BfTypeInstance* checkBase = typeInstance;
  22721. // If we are in an extension, look in ourselves first
  22722. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  22723. checkBase = checkBase->mBaseType;
  22724. if (typeInstance->IsValueType())
  22725. {
  22726. if (typeInstance->mBaseType == NULL)
  22727. return false; // It's actually ValueType
  22728. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  22729. if (!methodDef->mIsOverride)
  22730. {
  22731. Fail("Structs cannot have virtual methods", virtualToken, true);
  22732. return false;
  22733. }
  22734. checkBase = mContext->mBfObjectType;
  22735. if (checkBase->mVirtualMethodTableSize == 0)
  22736. PopulateType(checkBase, BfPopulateType_Full);
  22737. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  22738. return false; // System circular ref, don't do struct checking on those
  22739. }
  22740. int virtualMethodMatchIdx = -1;
  22741. bool hadHidingError = false;
  22742. BfMethodInstance* bestOverrideMethodInstance = NULL;
  22743. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  22744. int bestOverrideMethodIdx = -1;
  22745. int ambiguousOverrideMethodIdx = -1;
  22746. if (checkBase != NULL)
  22747. {
  22748. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22749. auto lookupType = checkBase;
  22750. while (lookupType != NULL)
  22751. {
  22752. lookupType->mTypeDef->PopulateMemberSets();
  22753. BfMethodDef* nextMethodDef = NULL;
  22754. BfMemberSetEntry* entry;
  22755. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  22756. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  22757. while (nextMethodDef != NULL)
  22758. {
  22759. auto checkMethodDef = nextMethodDef;
  22760. nextMethodDef = nextMethodDef->mNextWithSameName;
  22761. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  22762. continue;
  22763. BfMethodInstance* baseMethodInstance = NULL;
  22764. int checkMethodIdx = -1;
  22765. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  22766. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  22767. {
  22768. if (lookupType->IsUnspecializedTypeVariation())
  22769. {
  22770. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  22771. {
  22772. baseMethodInstance = lookupMethodInstance;
  22773. checkMethodIdx = -2;
  22774. }
  22775. }
  22776. if (baseMethodInstance == NULL)
  22777. continue;
  22778. }
  22779. if (baseMethodInstance == NULL)
  22780. {
  22781. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  22782. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  22783. {
  22784. Fail("SlotVirtualMethod out of bounds", checkMethodDef->GetRefNode());
  22785. continue;
  22786. }
  22787. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22788. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22789. {
  22790. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22791. continue;
  22792. }
  22793. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22794. if (baseMethodInstance == NULL)
  22795. {
  22796. AssertErrorState();
  22797. continue;
  22798. }
  22799. }
  22800. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22801. {
  22802. if (methodDef->mIsOverride)
  22803. {
  22804. BfMethodInstance* checkMethodInstance;
  22805. if (checkMethodIdx == -2)
  22806. checkMethodInstance = baseMethodInstance;
  22807. else if (typeInstance->IsValueType())
  22808. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22809. else
  22810. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22811. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22812. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22813. continue;
  22814. if (bestOverrideMethodInstance != NULL)
  22815. {
  22816. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22817. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22818. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22819. if (isBetter == isWorse)
  22820. {
  22821. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22822. }
  22823. else
  22824. {
  22825. if (isWorse)
  22826. continue;
  22827. ambiguousOverrideMethodInstance = NULL;
  22828. }
  22829. }
  22830. bestOverrideMethodInstance = checkMethodInstance;
  22831. bestOverrideMethodIdx = checkMethodIdx;
  22832. }
  22833. else
  22834. {
  22835. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22836. {
  22837. if (!hadHidingError)
  22838. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22839. hadHidingError = true;
  22840. }
  22841. }
  22842. }
  22843. }
  22844. lookupType = lookupType->mBaseType;
  22845. }
  22846. }
  22847. //TODO:
  22848. if ((checkBase != NULL)
  22849. && (false)
  22850. )
  22851. {
  22852. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22853. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  22854. {
  22855. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  22856. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  22857. {
  22858. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  22859. continue;
  22860. }
  22861. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22862. if (baseMethodInstance == NULL)
  22863. {
  22864. AssertErrorState();
  22865. continue;
  22866. }
  22867. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  22868. {
  22869. if (methodDef->mIsOverride)
  22870. {
  22871. BfMethodInstance* checkMethodInstance;
  22872. if (typeInstance->IsValueType())
  22873. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22874. else
  22875. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  22876. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  22877. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  22878. continue;
  22879. if (bestOverrideMethodInstance != NULL)
  22880. {
  22881. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  22882. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  22883. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  22884. if (isBetter == isWorse)
  22885. {
  22886. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  22887. }
  22888. else
  22889. {
  22890. if (isWorse)
  22891. continue;
  22892. ambiguousOverrideMethodInstance = NULL;
  22893. }
  22894. }
  22895. bestOverrideMethodInstance = checkMethodInstance;
  22896. bestOverrideMethodIdx = checkMethodIdx;
  22897. }
  22898. else
  22899. {
  22900. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  22901. {
  22902. if (!hadHidingError)
  22903. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  22904. hadHidingError = true;
  22905. }
  22906. }
  22907. }
  22908. }
  22909. }
  22910. if (bestOverrideMethodInstance != NULL)
  22911. {
  22912. if (ambiguousOverrideMethodInstance != NULL)
  22913. {
  22914. bool allow = false;
  22915. // 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.
  22916. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  22917. bool canSeeEachOther = false;
  22918. //
  22919. {
  22920. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  22921. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22922. canSeeEachOther = true;
  22923. }
  22924. //
  22925. {
  22926. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  22927. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  22928. canSeeEachOther = true;
  22929. }
  22930. if (!canSeeEachOther)
  22931. {
  22932. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  22933. }
  22934. else
  22935. {
  22936. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  22937. if (error != NULL)
  22938. {
  22939. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  22940. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  22941. }
  22942. }
  22943. }
  22944. }
  22945. if (bestOverrideMethodIdx == -2)
  22946. {
  22947. // Comes from an unspecialized variation
  22948. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22949. }
  22950. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  22951. {
  22952. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  22953. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  22954. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  22955. {
  22956. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  22957. {
  22958. BfTypeReference* returnTypeRef;
  22959. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22960. {
  22961. returnTypeRef = propertyDeclaration->mTypeRef;
  22962. Fail("Property differs from overridden property by type", returnTypeRef, true);
  22963. }
  22964. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22965. {
  22966. returnTypeRef = methodDeclaration->mReturnType;
  22967. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  22968. }
  22969. else
  22970. {
  22971. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  22972. }
  22973. return usedMethod;
  22974. }
  22975. }
  22976. if (methodDef->mIsOverride)
  22977. {
  22978. // We can have multiple matches when a virtual method is used to implement interface methods
  22979. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  22980. // vtable entries for this method signature
  22981. virtualMethodMatchIdx = bestOverrideMethodIdx;
  22982. if (!typeInstance->IsValueType())
  22983. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22984. if (typeInstance->IsValueType())
  22985. {
  22986. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22987. }
  22988. else
  22989. {
  22990. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  22991. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  22992. BfMethodInstance* setMethodInstance = methodInstance;
  22993. bool doOverride = false;
  22994. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  22995. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  22996. {
  22997. methodOverriden = overridenRef;
  22998. doOverride = true;
  22999. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  23000. {
  23001. bool isBetter = false;
  23002. bool isWorse = false;
  23003. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  23004. if (isBetter == isWorse)
  23005. {
  23006. // We have to resolve later per-project
  23007. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  23008. {
  23009. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23010. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  23011. }
  23012. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  23013. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  23014. doOverride = false;
  23015. }
  23016. else
  23017. {
  23018. if ((isBetter) && (ambiguityContext != NULL))
  23019. {
  23020. ambiguityContext->Remove(virtualMethodMatchIdx);
  23021. }
  23022. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  23023. {
  23024. if (preferRootDefinition)
  23025. {
  23026. // Leave the master GCMarkMember
  23027. isBetter = false;
  23028. isWorse = true;
  23029. }
  23030. }
  23031. doOverride = isBetter;
  23032. }
  23033. }
  23034. }
  23035. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  23036. {
  23037. methodOverriden = overridenRef;
  23038. doOverride = true;
  23039. }
  23040. if (doOverride)
  23041. {
  23042. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23043. _AddVirtualDecl(declMethodInstance);
  23044. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  23045. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  23046. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  23047. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  23048. {
  23049. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  23050. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  23051. {
  23052. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  23053. BfReifyMethodDependency dep;
  23054. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  23055. dep.mMethodIdx = implMethodRef.mMethodNum;
  23056. typeInstance->mReifyMethodDependencies.Add(dep);
  23057. }
  23058. if (!methodInstance->mMangleWithIdx)
  23059. {
  23060. // Keep mangled names from conflicting
  23061. methodInstance->mMangleWithIdx = true;
  23062. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  23063. {
  23064. StringT<4096> mangledName;
  23065. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  23066. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  23067. }
  23068. }
  23069. }
  23070. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  23071. }
  23072. }
  23073. if (methodOverriden != NULL)
  23074. {
  23075. CheckOverridenMethod(methodInstance, methodOverriden);
  23076. }
  23077. }
  23078. }
  23079. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  23080. {
  23081. if (methodDef->mIsOverride)
  23082. {
  23083. BfTokenNode* overrideToken = NULL;
  23084. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  23085. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  23086. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23087. overrideToken = methodDeclaration->mVirtualSpecifier;
  23088. if (overrideToken != NULL)
  23089. {
  23090. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  23091. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  23092. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  23093. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  23094. else
  23095. Fail("No suitable method found to override", overrideToken, true);
  23096. }
  23097. return usedMethod;
  23098. }
  23099. UniqueSlotVirtualMethod(methodInstance);
  23100. }
  23101. else
  23102. usedMethod = true;
  23103. if (typeInstance->IsValueType())
  23104. return usedMethod;
  23105. }
  23106. bool foundInterface = false;
  23107. bool hadAnyMatch = false;
  23108. // See if this method matches interfaces
  23109. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  23110. {
  23111. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  23112. if (ifaceInst->IsIncomplete())
  23113. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  23114. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  23115. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  23116. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  23117. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  23118. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  23119. continue;
  23120. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  23121. continue;
  23122. bool hadMatch = false;
  23123. BfMethodInstance* hadNameMatch = NULL;
  23124. BfType* expectedReturnType = NULL;
  23125. bool showedError = false;
  23126. // We go through our VTable looking for NULL entries within the interface sections
  23127. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  23128. // because a normal method declared in this type could have matched earlier
  23129. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  23130. ifaceInst->mTypeDef->PopulateMemberSets();
  23131. BfMethodDef* checkMethodDef = NULL;
  23132. BfMemberSetEntry* entry;
  23133. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  23134. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  23135. while (checkMethodDef != NULL)
  23136. {
  23137. int iMethodIdx = checkMethodDef->mIdx;
  23138. int iTableIdx = iMethodIdx + startIdx;
  23139. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  23140. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  23141. bool storeIFaceMethod = false;
  23142. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  23143. {
  23144. checkMethodDef = checkMethodDef->mNextWithSameName;
  23145. continue;
  23146. }
  23147. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  23148. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  23149. if (iMethodIdx >= ifaceInst->mMethodInstanceGroups.mSize)
  23150. {
  23151. InternalError("Interface slotting error", methodInstance->mMethodDef->GetMutNode());
  23152. break;
  23153. }
  23154. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  23155. auto iMethodInst = iMethodGroup.mDefault;
  23156. if (iMethodInst == NULL)
  23157. {
  23158. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  23159. AssertErrorState();
  23160. checkMethodDef = checkMethodDef->mNextWithSameName;
  23161. continue;
  23162. }
  23163. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  23164. hadNameMatch = iMethodInst;
  23165. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  23166. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  23167. {
  23168. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  23169. }
  23170. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  23171. {
  23172. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  23173. {
  23174. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  23175. {
  23176. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  23177. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  23178. if (error != NULL)
  23179. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  23180. showedError = true;
  23181. }
  23182. }
  23183. }
  23184. if (doesMethodSignatureMatch)
  23185. {
  23186. usedMethod = true;
  23187. hadMatch = true;
  23188. hadAnyMatch = true;
  23189. storeIFaceMethod = true;
  23190. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  23191. {
  23192. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  23193. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  23194. {
  23195. // When autocompletion regenerates a single method body but not the whole type then
  23196. // we will see ourselves in the vtable already
  23197. return usedMethod;
  23198. }
  23199. bool isBetter = false;
  23200. bool isWorse = false;
  23201. isBetter = methodInstance->mReturnType == iMethodInst->mReturnType;
  23202. isWorse = prevMethod->mReturnType == iMethodInst->mReturnType;
  23203. if (isBetter == isWorse)
  23204. {
  23205. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  23206. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  23207. if ((isBetter) && (isWorse))
  23208. {
  23209. isBetter = methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst;
  23210. isWorse = prevMethod->mMethodInfoEx->mExplicitInterface == ifaceInst;
  23211. }
  23212. }
  23213. if (isBetter == isWorse)
  23214. CompareDeclTypes(typeInstance, methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  23215. if (isBetter == isWorse)
  23216. {
  23217. if (ambiguityContext != NULL)
  23218. {
  23219. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  23220. }
  23221. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  23222. storeIFaceMethod = true;
  23223. }
  23224. else
  23225. {
  23226. if ((isBetter) && (ambiguityContext != NULL))
  23227. ambiguityContext->Remove(~iTableIdx);
  23228. storeIFaceMethod = isBetter;
  23229. }
  23230. }
  23231. }
  23232. if (storeIFaceMethod)
  23233. {
  23234. if (methodInstance->GetNumGenericParams() != 0)
  23235. _AddVirtualDecl(iMethodInst);
  23236. *iMethodPtr = methodInstance;
  23237. }
  23238. checkMethodDef = checkMethodDef->mNextWithSameName;
  23239. }
  23240. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  23241. {
  23242. if (expectedReturnType != NULL)
  23243. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  23244. else if (hadNameMatch != NULL)
  23245. {
  23246. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  23247. if (error != NULL)
  23248. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  23249. }
  23250. else
  23251. {
  23252. auto propertyDecl = methodDef->GetPropertyDeclaration();
  23253. if (propertyDecl != NULL)
  23254. {
  23255. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  23256. String name;
  23257. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  23258. name = "this[]";
  23259. else if (propertyDecl->mNameNode != NULL)
  23260. propertyDecl->mNameNode->ToString(name);
  23261. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  23262. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23263. }
  23264. else
  23265. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  23266. }
  23267. }
  23268. }
  23269. // Any overriden virtual methods that were used in interfaces also need to be replaced
  23270. if (methodOverriden != NULL)
  23271. {
  23272. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  23273. {
  23274. if (methodEntry.mMethodRef == methodOverriden)
  23275. methodEntry.mMethodRef = methodInstance;
  23276. }
  23277. }
  23278. return usedMethod;
  23279. }
  23280. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  23281. {
  23282. auto methodDef = methodInstance->mMethodDef;
  23283. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  23284. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  23285. {
  23286. const char* protectionNames[] = { "disabled", "hidden", "private", "internal", "protected", "protected internal", "public" };
  23287. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  23288. BfAstNode* protectionRefNode = NULL;
  23289. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  23290. {
  23291. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  23292. if (protectionRefNode == NULL)
  23293. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  23294. if (protectionRefNode == NULL)
  23295. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  23296. }
  23297. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23298. {
  23299. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  23300. if (protectionRefNode == NULL)
  23301. protectionRefNode = methodDeclaration->mNameNode;
  23302. }
  23303. if (protectionRefNode != NULL)
  23304. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  23305. }
  23306. }
  23307. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  23308. {
  23309. auto typeInstance = mCurTypeInstance;
  23310. auto methodDef = methodInstance->mMethodDef;
  23311. if (methodDef->mMethodType == BfMethodType_Ctor)
  23312. return true;
  23313. bool foundOverride = false;
  23314. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  23315. {
  23316. auto methodDeclaration = methodDef->GetMethodDeclaration();
  23317. BfAstNode* refNode = NULL;
  23318. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23319. refNode = propertyDeclaration->mProtectionSpecifier;
  23320. else if (methodDeclaration != NULL)
  23321. refNode = methodDeclaration->mProtectionSpecifier;
  23322. Fail("Private interface methods must provide a body", refNode);
  23323. }
  23324. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  23325. {
  23326. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  23327. }
  23328. BfAstNode* declaringNode = methodDef->GetRefNode();
  23329. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  23330. {
  23331. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  23332. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  23333. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  23334. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  23335. continue;
  23336. ifaceInst->mTypeDef->PopulateMemberSets();
  23337. BfMethodDef* nextMethod = NULL;
  23338. BfMemberSetEntry* entry = NULL;
  23339. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23340. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23341. while (nextMethod != NULL)
  23342. {
  23343. auto checkMethod = nextMethod;
  23344. nextMethod = nextMethod->mNextWithSameName;
  23345. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23346. if (ifaceMethod == NULL)
  23347. continue;
  23348. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23349. {
  23350. if (methodDef->mIsOverride)
  23351. {
  23352. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  23353. {
  23354. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  23355. if (error != NULL)
  23356. {
  23357. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  23358. }
  23359. }
  23360. foundOverride = true;
  23361. }
  23362. else if (!methodDef->mIsNew)
  23363. {
  23364. auto error = Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  23365. if (error != NULL)
  23366. {
  23367. mCompiler->mPassInstance->MoreInfo("See inherited method", ifaceMethod->mMethodDef->GetRefNode());
  23368. }
  23369. }
  23370. }
  23371. }
  23372. }
  23373. if ((methodDef->mIsOverride) && (!foundOverride))
  23374. {
  23375. // This allows us to declare a method in the base definition or in an extension and then provide
  23376. // an implementation in a more-specific extension
  23377. typeInstance->mTypeDef->PopulateMemberSets();
  23378. BfMethodDef* nextMethod = NULL;
  23379. BfMemberSetEntry* entry = NULL;
  23380. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  23381. nextMethod = (BfMethodDef*)entry->mMemberDef;
  23382. while (nextMethod != NULL)
  23383. {
  23384. auto checkMethod = nextMethod;
  23385. nextMethod = nextMethod->mNextWithSameName;
  23386. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  23387. if (ifaceMethod == NULL)
  23388. continue;
  23389. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23390. continue;
  23391. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23392. {
  23393. foundOverride = true;
  23394. }
  23395. }
  23396. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  23397. // {
  23398. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  23399. // if (ifaceMethod == NULL)
  23400. // continue;
  23401. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  23402. // continue;
  23403. //
  23404. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  23405. // {
  23406. // foundOverride = true;
  23407. // }
  23408. // }
  23409. }
  23410. if (methodDef->mIsOverride)
  23411. {
  23412. if (!foundOverride)
  23413. {
  23414. BfTokenNode* overrideToken = NULL;
  23415. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  23416. overrideToken = propertyDeclaration->mVirtualSpecifier;
  23417. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  23418. overrideToken = methodDeclaration->mVirtualSpecifier;
  23419. if (overrideToken != NULL)
  23420. {
  23421. Fail("No suitable method found to override", overrideToken, true);
  23422. }
  23423. else
  23424. {
  23425. // Possible cause - DTOR with params
  23426. AssertErrorState();
  23427. }
  23428. }
  23429. return true;
  23430. }
  23431. // Generic methods can't be called virtually
  23432. if (methodInstance->GetNumGenericParams() != 0)
  23433. return true;
  23434. // Only public methods can be called virtually
  23435. if (methodDef->mProtection != BfProtection_Public)
  23436. return true;
  23437. UniqueSlotVirtualMethod(methodInstance);
  23438. return true;
  23439. }
  23440. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  23441. {
  23442. if (methodInstance->mMethodInfoEx == NULL)
  23443. return;
  23444. int wantMinDepth = -1;
  23445. if (mCurTypeInstance != NULL)
  23446. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  23447. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  23448. {
  23449. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  23450. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  23451. wantMinDepth = wantTypeMinDepth;
  23452. }
  23453. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  23454. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  23455. }
  23456. void BfModule::DbgFinish()
  23457. {
  23458. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  23459. return;
  23460. if (mAwaitingInitFinish)
  23461. FinishInit();
  23462. if (mHasForceLinkMarker)
  23463. return;
  23464. String markerName;
  23465. BfIRValue linkMarker;
  23466. if (mBfIRBuilder->DbgHasInfo())
  23467. {
  23468. bool needForceLinking = false;
  23469. if (WantsDebugHelpers())
  23470. {
  23471. for (auto& ownedType : mOwnedTypeInstances)
  23472. {
  23473. bool hasConfirmedReference = false;
  23474. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  23475. {
  23476. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  23477. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  23478. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  23479. (methodInstGroup.mHasEmittedReference))
  23480. {
  23481. hasConfirmedReference = true;
  23482. }
  23483. }
  23484. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  23485. needForceLinking = true;
  23486. }
  23487. }
  23488. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  23489. {
  23490. BfMethodState methodState;
  23491. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  23492. methodState.mTempKind = BfMethodState::TempKind_Static;
  23493. mHasForceLinkMarker = true;
  23494. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  23495. SizedArray<BfIRType, 0> paramTypes;
  23496. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  23497. String linkName = "FORCELINKMOD_" + mModuleName;
  23498. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  23499. mBfIRBuilder->SetActiveFunction(func);
  23500. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  23501. mBfIRBuilder->SetInsertPoint(entryBlock);
  23502. auto firstType = mOwnedTypeInstances[0];
  23503. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  23504. SizedArray<BfIRMDNode, 1> diParamTypes;
  23505. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  23506. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  23507. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  23508. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  23509. methodState.mCurScope->mDIScope = diScope;
  23510. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  23511. SizedArray<BfIRValue, 8> args;
  23512. BfExprEvaluator exprEvaluator(this);
  23513. for (auto& ownedType : mOwnedTypeInstances)
  23514. {
  23515. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  23516. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  23517. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  23518. }
  23519. mBfIRBuilder->CreateRetVoid();
  23520. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  23521. }
  23522. }
  23523. }
  23524. bool BfModule::Finish()
  23525. {
  23526. BP_ZONE("BfModule::Finish");
  23527. BfLogSysM("BfModule finish: %p\n", this);
  23528. if (mHadBuildError)
  23529. {
  23530. // Don't AssertErrorState here, this current pass may not have failed but
  23531. // the module was still queued in mFinishedModuleWorkList
  23532. ClearModule();
  23533. return true;
  23534. }
  23535. if (mUsedSlotCount != -1)
  23536. {
  23537. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  23538. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  23539. }
  23540. if ((!mGeneratesCode) && (!mAddedToCount))
  23541. return true;
  23542. BF_ASSERT(mAddedToCount);
  23543. mAddedToCount = false;
  23544. mAwaitingFinish = false;
  23545. mCompiler->mStats.mModulesFinished++;
  23546. if (HasCompiledOutput())
  23547. {
  23548. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  23549. DbgFinish();
  23550. if (mAwaitingInitFinish)
  23551. FinishInit();
  23552. for (auto ownedTypeInst : mOwnedTypeInstances)
  23553. {
  23554. // Generate dbg info and add global variables if we haven't already
  23555. mBfIRBuilder->PopulateType(ownedTypeInst);
  23556. }
  23557. if (mBfIRBuilder->DbgHasInfo())
  23558. {
  23559. mBfIRBuilder->DbgFinalize();
  23560. }
  23561. String objOutputPath;
  23562. String irOutputPath;
  23563. mIsModuleMutable = false;
  23564. //mOutFileNames.Clear();
  23565. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  23566. bool writeModule = mBfIRBuilder->HasExports();
  23567. String outputPath;
  23568. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  23569. auto& compilerOpts = mCompiler->mOptions;
  23570. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  23571. auto moduleOptions = GetModuleOptions();
  23572. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  23573. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  23574. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  23575. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  23576. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  23577. codeGenOptions.mVirtualMethodOfs = mCompiler->GetVDataPrefixDataCount() + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  23578. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  23579. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  23580. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  23581. bool allowWriteToLib = true;
  23582. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  23583. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  23584. {
  23585. codeGenOptions.mWriteToLib = true;
  23586. mWroteToLib = true;
  23587. }
  23588. else
  23589. {
  23590. mWroteToLib = false;
  23591. }
  23592. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  23593. {
  23594. outputPath = mModuleName;
  23595. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  23596. BfModuleFileName moduleFileName;
  23597. if (mParentModule != NULL)
  23598. {
  23599. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  23600. {
  23601. if (checkPair.mValue == this)
  23602. moduleFileName.mProjects = checkPair.mKey;
  23603. }
  23604. }
  23605. moduleFileName.mProjects.Add(mProject);
  23606. if (fileIdx > 0)
  23607. outputPath += StrFormat("@%d", fileIdx + 1);
  23608. if (mCompiler->mOptions.mWriteIR)
  23609. irOutputPath = outputPath + ".ll";
  23610. if (mCompiler->mOptions.mGenerateObj)
  23611. {
  23612. objOutputPath = outputPath + BF_OBJ_EXT;
  23613. moduleFileName.mFileName = objOutputPath;
  23614. }
  23615. else if (mCompiler->mOptions.mWriteIR)
  23616. {
  23617. moduleFileName.mFileName = irOutputPath;
  23618. }
  23619. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  23620. {
  23621. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  23622. }
  23623. moduleFileName.mModuleWritten = writeModule;
  23624. moduleFileName.mWroteToLib = mWroteToLib;
  23625. if (!mOutFileNames.Contains(moduleFileName))
  23626. mOutFileNames.Add(moduleFileName);
  23627. }
  23628. if (mCompiler->IsHotCompile())
  23629. {
  23630. codeGenOptions.mIsHotCompile = true;
  23631. if (mParentModule != NULL)
  23632. mParentModule->mHadHotObjectWrites = true;
  23633. mHadHotObjectWrites = true;
  23634. }
  23635. //TODO: Testing VDATA
  23636. /*if (mModuleName == "vdata")
  23637. {
  23638. codeGenOptions.mOptLevel = 4;
  23639. }*/
  23640. codeGenOptions.GenerateHash();
  23641. BP_ZONE("BfModule::Finish.WriteObjectFile");
  23642. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  23643. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  23644. mLastModuleWrittenRevision = mCompiler->mRevision;
  23645. }
  23646. else
  23647. {
  23648. for (auto type : mOwnedTypeInstances)
  23649. {
  23650. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  23651. }
  23652. }
  23653. for (auto& specModulePair : mSpecializedMethodModules)
  23654. {
  23655. auto specModule = specModulePair.mValue;
  23656. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  23657. {
  23658. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  23659. }
  23660. }
  23661. CleanupFileInstances();
  23662. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  23663. return true;
  23664. }
  23665. void BfModule::ReportMemory(MemReporter* memReporter)
  23666. {
  23667. memReporter->Add(sizeof(BfModule));
  23668. if (mBfIRBuilder != NULL)
  23669. {
  23670. memReporter->BeginSection("IRBuilder_ConstData");
  23671. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  23672. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  23673. memReporter->EndSection();
  23674. memReporter->BeginSection("IRBuilder_BFIR");
  23675. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  23676. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  23677. memReporter->EndSection();
  23678. memReporter->Add(sizeof(BfIRBuilder));
  23679. }
  23680. memReporter->BeginSection("FileInstanceMap");
  23681. memReporter->AddMap(mFileInstanceMap);
  23682. memReporter->AddMap(mNamedFileInstanceMap);
  23683. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  23684. memReporter->EndSection();
  23685. memReporter->AddVec(mOwnedTypeInstances, false);
  23686. memReporter->AddVec(mSpecializedMethodModules, false);
  23687. memReporter->AddVec(mOutFileNames, false);
  23688. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  23689. memReporter->AddMap(mInterfaceSlotRefs, false);
  23690. memReporter->AddMap(mStaticFieldRefs, false);
  23691. memReporter->AddMap(mClassVDataRefs, false);
  23692. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  23693. memReporter->AddMap(mTypeDataRefs, false);
  23694. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  23695. memReporter->AddMap(mDeferredMethodCallData, false);
  23696. memReporter->AddHashSet(mDeferredMethodIds, false);
  23697. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  23698. }
  23699. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  23700. // be transient through the next compile
  23701. void BfModule::ClearModuleData(bool clearTransientData)
  23702. {
  23703. BfLogSysM("ClearModuleData %p\n", this);
  23704. if (mAddedToCount)
  23705. {
  23706. mCompiler->mStats.mModulesFinished++;
  23707. mAddedToCount = false;
  23708. }
  23709. mDICompileUnit = BfIRMDNode();
  23710. if (clearTransientData)
  23711. mIncompleteMethodCount = 0;
  23712. mHasGenericMethods = false;
  23713. // We don't want to clear these because we want it to persist through module extensions-
  23714. // otherwise we may think an extension succeeds even though the base module failed
  23715. //mHadBuildError = false;
  23716. //mHadBuildWarning = false;
  23717. mClassVDataRefs.Clear();
  23718. mClassVDataExtRefs.Clear();
  23719. for (auto& kv : mTypeDataRefs)
  23720. kv.mValue = BfIRValue();
  23721. mStringCharPtrPool.Clear();
  23722. mStringObjectPool.Clear();
  23723. mStaticFieldRefs.Clear();
  23724. BF_ASSERT(!mIgnoreErrors);
  23725. for (auto prevIRBuilder : mPrevIRBuilders)
  23726. delete prevIRBuilder;
  23727. mPrevIRBuilders.Clear();
  23728. for (auto& specPair : mSpecializedMethodModules)
  23729. {
  23730. auto specModule = specPair.mValue;
  23731. specModule->ClearModuleData();
  23732. }
  23733. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23734. mBuiltInFuncs[i] = BfIRFunction();
  23735. if (mNextAltModule != NULL)
  23736. mNextAltModule->ClearModuleData();
  23737. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  23738. mIsModuleMutable = false;
  23739. delete mBfIRBuilder;
  23740. mBfIRBuilder = NULL;
  23741. mWantsIRIgnoreWrites = false;
  23742. }
  23743. void BfModule::DisownMethods()
  23744. {
  23745. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  23746. mBuiltInFuncs[i] = BfIRFunction();
  23747. BfModule* methodModule = this;
  23748. if (mParentModule != NULL)
  23749. methodModule = mParentModule;
  23750. for (auto typeInst : methodModule->mOwnedTypeInstances)
  23751. {
  23752. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  23753. {
  23754. if (methodGroup.mDefault != NULL)
  23755. {
  23756. if (methodGroup.mDefault->mIRFunction)
  23757. {
  23758. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  23759. if (methodGroup.mDefault->mDeclModule == this)
  23760. {
  23761. methodGroup.mDefault->mIRFunction = BfIRFunction();
  23762. }
  23763. }
  23764. }
  23765. if (methodGroup.mMethodSpecializationMap != NULL)
  23766. {
  23767. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  23768. {
  23769. auto methodInstance = mapPair.mValue;
  23770. if (methodInstance->mDeclModule == this)
  23771. {
  23772. methodInstance->mIRFunction = BfIRFunction();
  23773. }
  23774. }
  23775. }
  23776. }
  23777. }
  23778. }
  23779. void BfModule::ClearModule()
  23780. {
  23781. ClearModuleData();
  23782. DisownMethods();
  23783. for (auto& specPair : mSpecializedMethodModules)
  23784. {
  23785. auto specModule = specPair.mValue;
  23786. specModule->ClearModule();
  23787. }
  23788. if (mNextAltModule != NULL)
  23789. mNextAltModule->ClearModule();
  23790. }