BfModule.cpp 811 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925
  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 <fcntl.h>
  26. #include <time.h>
  27. #pragma warning(pop)
  28. //////////////////////////////////////////////////////////////////////////
  29. static bool gDebugStuff = false;
  30. USING_NS_BF;
  31. //////////////////////////////////////////////////////////////////////////
  32. void BfLocalVariable::Init()
  33. {
  34. if (mResolvedType->IsValuelessType())
  35. {
  36. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  37. return;
  38. }
  39. if (mAssignedKind != BfLocalVarAssignKind_None)
  40. return;
  41. bool isStruct = mResolvedType->IsStruct();
  42. if (mResolvedType->IsRef())
  43. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  44. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  45. {
  46. auto resolvedTypeRef = mResolvedType;
  47. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  48. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  49. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  50. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  51. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  52. {
  53. // Base ctor is responsible for initializing its own fields
  54. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  55. }
  56. if (mUnassignedFieldFlags == 0)
  57. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  58. }
  59. else
  60. {
  61. mUnassignedFieldFlags = 1;
  62. }
  63. }
  64. BfLocalMethod::~BfLocalMethod()
  65. {
  66. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  67. if (mMethodDeclaration != NULL)
  68. {
  69. mSource->mRefCount--;
  70. BF_ASSERT(mSource->mRefCount >= 0);
  71. }
  72. delete mMethodInstanceGroup;
  73. delete mMethodDef;
  74. }
  75. void BfLocalMethod::Dispose()
  76. {
  77. if (mMethodInstanceGroup == NULL)
  78. return;
  79. if (mMethodInstanceGroup->mDefault != NULL)
  80. mMethodInstanceGroup->mDefault->Dispose();
  81. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  82. {
  83. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  84. kv.mValue->Dispose();
  85. }
  86. }
  87. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  88. {
  89. mIsChained = doChain;
  90. if (outerLocalAssignData == NULL)
  91. return;
  92. mChainedAssignData = outerLocalAssignData;
  93. if (!doChain)
  94. {
  95. outerLocalAssignData->BreakExtendChain();
  96. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  97. }
  98. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  99. }
  100. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  101. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  102. // if ((GetValue(out a)) && (GetValue(out b)) {}
  103. void BfDeferredLocalAssignData::BreakExtendChain()
  104. {
  105. if (!mIsChained)
  106. return;
  107. mIsChained = false;
  108. if (mChainedAssignData == NULL)
  109. return;
  110. mChainedAssignData->BreakExtendChain();
  111. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  112. }
  113. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  114. {
  115. BreakExtendChain();
  116. for (int i = 0; i < (int)mAssignedLocals.size(); )
  117. {
  118. auto& local = mAssignedLocals[i];
  119. bool wantRemove = true;
  120. bool foundOtherFields = false;
  121. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  122. {
  123. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  124. {
  125. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  126. {
  127. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  128. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  129. wantRemove = false;
  130. }
  131. else
  132. foundOtherFields = true;
  133. }
  134. }
  135. if ((wantRemove) && (foundOtherFields))
  136. {
  137. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  138. {
  139. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  140. {
  141. mAssignedLocals.Add(otherLocalAssignData);
  142. }
  143. }
  144. }
  145. if (wantRemove)
  146. {
  147. mAssignedLocals.RemoveAt(i);
  148. }
  149. else
  150. i++;
  151. }
  152. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  153. }
  154. void BfDeferredLocalAssignData::Validate() const
  155. {
  156. for (auto var : mAssignedLocals)
  157. {
  158. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  159. }
  160. }
  161. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  162. {
  163. BreakExtendChain();
  164. Validate();
  165. otherLocalAssignData.Validate();
  166. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  167. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  168. {
  169. if (!mAssignedLocals.Contains(*otherItr))
  170. mAssignedLocals.push_back(*otherItr);
  171. ++otherItr;
  172. }
  173. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  174. }
  175. BfMethodState::~BfMethodState()
  176. {
  177. BF_ASSERT(mPendingNullConditional == NULL);
  178. if (mPrevMethodState != NULL)
  179. {
  180. BF_ASSERT(mCurAccessId == 1);
  181. BF_ASSERT(mCurLocalVarId <= 0);
  182. }
  183. for (auto local : mLocals)
  184. delete local;
  185. for (auto& kv : mLambdaCache)
  186. delete kv.mValue;
  187. }
  188. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  189. {
  190. auto checkMethodState = this;
  191. while (checkMethodState != NULL)
  192. {
  193. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  194. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  195. return checkMethodState;
  196. checkMethodState = checkMethodState->mPrevMethodState;
  197. }
  198. BF_FATAL("Failed to find method state for localvar");
  199. return NULL;
  200. }
  201. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  202. {
  203. auto localVarMethodState = GetMethodStateForLocal(localVar);
  204. if (localVarMethodState != this)
  205. {
  206. return;
  207. }
  208. //BF_ASSERT(localVarMethodState == this);
  209. // if (assignKind == BfLocalVarAssignKind_None)
  210. // assignKind = ((localVarMethodState->mLeftBlockCond) && ((mDeferredLocalAssignData != NULL) || isFromDeferredAssignData)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  211. //
  212. // //assignKind = BfLocalVarAssignKind_Unconditional;
  213. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  214. {
  215. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  216. // 'a' is always defined, but 'b' isn't:
  217. // if (Check(out a) || Check(out b)) { } int z = a;
  218. auto deferredLocalAssignData = mDeferredLocalAssignData;
  219. if ((deferredLocalAssignData != NULL) &&
  220. (deferredLocalAssignData->mIsIfCondition) &&
  221. (!deferredLocalAssignData->mIfMayBeSkipped))
  222. {
  223. ifDeferredLocalAssignData = deferredLocalAssignData;
  224. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  225. }
  226. while ((deferredLocalAssignData != NULL) &&
  227. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  228. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  229. if (assignKind == BfLocalVarAssignKind_None)
  230. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  231. if (localVar->mAssignedKind >= assignKind)
  232. {
  233. // Leave it alone
  234. }
  235. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  236. {
  237. if (fieldIdx >= 0)
  238. {
  239. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  240. if (localVar->mUnassignedFieldFlags == 0)
  241. {
  242. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  243. localVar->mAssignedKind = assignKind;
  244. }
  245. }
  246. else
  247. {
  248. localVar->mAssignedKind = assignKind;
  249. }
  250. }
  251. else
  252. {
  253. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  254. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  255. if (!deferredLocalAssignData->Contains(defineVal))
  256. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  257. if (ifDeferredLocalAssignData != NULL)
  258. {
  259. if (!ifDeferredLocalAssignData->Contains(defineVal))
  260. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  261. }
  262. }
  263. }
  264. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  265. }
  266. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  267. {
  268. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  269. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  270. {
  271. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  272. }
  273. }
  274. void BfMethodState::Reset()
  275. {
  276. mHeadScope.mDeferredCallEntries.DeleteAll();
  277. }
  278. //////////////////////////////////////////////////////////////////////////
  279. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  280. {
  281. Entry* entry = NULL;
  282. if (mEntries.TryAdd(id, NULL, &entry))
  283. {
  284. entry->mInterfaceEntry = interfaceEntry;
  285. entry->mMethodIdx = methodIdx;
  286. }
  287. if (!entry->mCandidates.Contains(candidateA))
  288. entry->mCandidates.push_back(candidateA);
  289. if (!entry->mCandidates.Contains(candidateB))
  290. entry->mCandidates.push_back(candidateB);
  291. }
  292. void BfAmbiguityContext::Remove(int id)
  293. {
  294. mEntries.Remove(id);
  295. }
  296. void BfAmbiguityContext::Finish()
  297. {
  298. for (auto& entryPair : mEntries)
  299. {
  300. int id = entryPair.mKey;
  301. auto entry = &entryPair.mValue;
  302. if (id >= 0)
  303. {
  304. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  305. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  306. for (auto candidate : entry->mCandidates)
  307. {
  308. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  309. }
  310. }
  311. else
  312. {
  313. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  314. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  315. for (auto candidate : entry->mCandidates)
  316. {
  317. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  318. }
  319. }
  320. }
  321. }
  322. //////////////////////////////////////////////////////////////////////////
  323. class HasAppendAllocVisitor : BfElementVisitor
  324. {
  325. public:
  326. bool mHas;
  327. public:
  328. HasAppendAllocVisitor()
  329. {
  330. mHas = false;
  331. }
  332. void Visit(BfObjectCreateExpression* objCreateExpr)
  333. {
  334. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  335. {
  336. if (newToken->GetToken() == BfToken_Append)
  337. {
  338. mHas = true;
  339. }
  340. }
  341. }
  342. bool HasAppendAlloc(BfAstNode* node)
  343. {
  344. mHas = false;
  345. VisitChild(node);
  346. return mHas;
  347. }
  348. };
  349. class AppendAllocVisitor : public BfStructuralVisitor
  350. {
  351. public:
  352. BfModule* mModule;
  353. HasAppendAllocVisitor mHasAppendAllocVisitor;
  354. BfTypedValue mConstAccum;
  355. bool mFailed;
  356. bool mIsFirstConstPass;
  357. int mCurAppendAlign;
  358. public:
  359. AppendAllocVisitor()
  360. {
  361. mFailed = false;
  362. mIsFirstConstPass = false;
  363. mCurAppendAlign = 1;
  364. }
  365. void EmitAppendAlign(int align, int sizeMultiple = 0)
  366. {
  367. BF_ASSERT(align > 0);
  368. if (mIsFirstConstPass)
  369. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  370. if (sizeMultiple == 0)
  371. sizeMultiple = align;
  372. if (mCurAppendAlign == 0)
  373. mCurAppendAlign = sizeMultiple;
  374. else
  375. {
  376. if (sizeMultiple % align == 0)
  377. mCurAppendAlign = align;
  378. else
  379. mCurAppendAlign = sizeMultiple % align;
  380. }
  381. BF_ASSERT(mCurAppendAlign > 0);
  382. if (mConstAccum)
  383. {
  384. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  385. if (constant != NULL)
  386. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  387. else
  388. BF_ASSERT(mIsFirstConstPass);
  389. return;
  390. }
  391. mModule->EmitAppendAlign(align, sizeMultiple);
  392. }
  393. void Visit(BfAstNode* astNode) override
  394. {
  395. mModule->VisitChild(astNode);
  396. }
  397. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  398. {
  399. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  400. {
  401. if (newToken->GetToken() == BfToken_Append)
  402. {
  403. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  404. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  405. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  406. BfArrayType* arrayType = NULL;
  407. bool isArrayAlloc = false;
  408. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  409. SizedArray<BfIRValue, 2> dimLengthVals;
  410. BfType* origResolvedTypeRef = NULL;
  411. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  412. {
  413. if (variableDecl != NULL)
  414. {
  415. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  416. if (origResolvedTypeRef->IsObject())
  417. {
  418. if (origResolvedTypeRef->IsArray())
  419. {
  420. arrayType = (BfArrayType*)origResolvedTypeRef;
  421. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  422. isArrayAlloc = true;
  423. }
  424. }
  425. else if (origResolvedTypeRef->IsPointer())
  426. {
  427. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  428. }
  429. }
  430. }
  431. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  432. {
  433. isArrayAlloc = true;
  434. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  435. int dimensions = 1;
  436. if (arrayTypeRef->mParams.size() != 0)
  437. {
  438. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  439. for (auto arg : arrayTypeRef->mParams)
  440. {
  441. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  442. {
  443. if (tokenNode->GetToken() == BfToken_Comma)
  444. {
  445. if (isRawArrayAlloc)
  446. {
  447. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  448. continue;
  449. }
  450. dimensions++;
  451. continue;
  452. }
  453. }
  454. auto expr = BfNodeDynCast<BfExpression>(arg);
  455. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  456. {
  457. mModule->CreateValueFromExpression(expr, intType);
  458. continue;
  459. }
  460. BfTypedValue dimLength;
  461. if (expr == NULL)
  462. {
  463. // Not specified
  464. dimLengthVals.push_back(BfIRValue());
  465. continue;
  466. }
  467. if (arg != NULL)
  468. dimLength = mModule->CreateValueFromExpression(expr, intType);
  469. if (!dimLength)
  470. {
  471. dimLength = mModule->GetDefaultTypedValue(intType);
  472. }
  473. dimLengthVals.push_back(dimLength.mValue);
  474. }
  475. }
  476. if (!isRawArrayAlloc)
  477. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  478. }
  479. if (origResolvedTypeRef == NULL)
  480. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  481. if (origResolvedTypeRef == NULL)
  482. {
  483. mModule->AssertErrorState();
  484. return;
  485. }
  486. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  487. auto resolvedTypeRef = origResolvedTypeRef;
  488. auto resultType = resolvedTypeRef;
  489. BfIRValue sizeValue;
  490. int curAlign = 0;
  491. if (isArrayAlloc)
  492. {
  493. int dimensions = 1;
  494. if (arrayType != NULL)
  495. dimensions = arrayType->mDimensions;
  496. bool sizeFailed = false;
  497. //
  498. {
  499. BfAstNode* initNode = objCreateExpr;
  500. for (int dim = 0; dim < dimensions; dim++)
  501. {
  502. BfAstNode* nextInitNode = NULL;
  503. int dimSize = -1;
  504. if (initNode == objCreateExpr)
  505. {
  506. dimSize = objCreateExpr->mArguments.size();
  507. if (!objCreateExpr->mArguments.IsEmpty())
  508. nextInitNode = objCreateExpr->mArguments[0];
  509. }
  510. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  511. {
  512. dimSize = (int)tupleNode->mCommas.size() + 1;
  513. }
  514. if (dimSize >= 0)
  515. {
  516. if (dim >= dimLengthVals.size())
  517. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  518. }
  519. else
  520. {
  521. sizeFailed = true;
  522. }
  523. }
  524. }
  525. BfIRValue allocCount;
  526. if (!sizeFailed)
  527. {
  528. if (!dimLengthVals.IsEmpty())
  529. {
  530. allocCount = dimLengthVals[0];
  531. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  532. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  533. }
  534. }
  535. if (!allocCount)
  536. {
  537. mFailed = true;
  538. if (!mIsFirstConstPass)
  539. {
  540. if (!mConstAccum)
  541. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  542. return;
  543. }
  544. }
  545. mModule->PopulateType(resultType);
  546. if (isRawArrayAlloc)
  547. {
  548. curAlign = resultType->mAlign;
  549. EmitAppendAlign(resultType->mAlign);
  550. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  551. }
  552. else
  553. {
  554. if (arrayType == NULL)
  555. arrayType = mModule->CreateArrayType(resultType, 1);
  556. // Array is a special case where the total size isn't aligned with mAlign
  557. // since we add arbitrary elements to the end without padding the end to align
  558. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  559. curAlign = arrayType->mAlign;
  560. auto firstElementField = &arrayType->mFieldInstances.back();
  561. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  562. sizeValue = mModule->GetConstValue(arrayClassSize);
  563. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  564. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  565. }
  566. }
  567. else
  568. {
  569. auto typeInst = resultType->ToTypeInstance();
  570. if (typeInst != NULL)
  571. {
  572. curAlign = typeInst->mInstAlign;
  573. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  574. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  575. }
  576. else
  577. {
  578. curAlign = resultType->mAlign;
  579. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  580. sizeValue = mModule->GetConstValue(resultType->mSize);
  581. }
  582. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  583. BfExprEvaluator exprEvaluator(mModule);
  584. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  585. BfFunctionBindResult bindResult;
  586. bindResult.mWantsArgs = true;
  587. exprEvaluator.mFunctionBindResult = &bindResult;
  588. SizedArray<BfExpression*, 8> copiedArgs;
  589. for (BfExpression* arg : objCreateExpr->mArguments)
  590. copiedArgs.push_back(arg);
  591. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  592. BfResolvedArgs argValues(&sizedArgExprs);
  593. if (typeInst != NULL)
  594. {
  595. exprEvaluator.ResolveArgValues(argValues);
  596. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  597. }
  598. exprEvaluator.mFunctionBindResult = NULL;
  599. if (bindResult.mMethodInstance != NULL)
  600. {
  601. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  602. {
  603. auto calcAppendArgs = bindResult.mIRArgs;
  604. BF_ASSERT(calcAppendArgs[0].IsFake());
  605. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  606. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  607. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  608. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  609. {
  610. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  611. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  612. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  613. }
  614. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  615. if ((!subDependSize) && (!mConstAccum))
  616. {
  617. BF_ASSERT(calcAppendMethodModule.mFunc);
  618. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  619. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  620. }
  621. if (subDependSize)
  622. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  623. else
  624. mFailed = true;
  625. }
  626. }
  627. }
  628. if (sizeValue)
  629. {
  630. if (mConstAccum)
  631. {
  632. if (!sizeValue.IsConst())
  633. {
  634. mFailed = true;
  635. if (!mIsFirstConstPass)
  636. return;
  637. }
  638. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  639. }
  640. else
  641. {
  642. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  643. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  644. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  645. }
  646. }
  647. }
  648. }
  649. }
  650. void Visit(BfObjectCreateExpression* objCreateExpr) override
  651. {
  652. DoObjectCreate(objCreateExpr, NULL);
  653. }
  654. void Visit(BfVariableDeclaration* varDecl) override
  655. {
  656. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  657. {
  658. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  659. DoObjectCreate(objectCreateExpr, varDecl);
  660. else
  661. VisitChild(varDecl->mInitializer);
  662. if (varDecl->mNameNode != NULL)
  663. {
  664. BfLocalVariable* localDef = new BfLocalVariable();
  665. localDef->mName = varDecl->mNameNode->ToString();
  666. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  667. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  668. localDef->mIsReadOnly = true;
  669. localDef->mParamFailed = true;
  670. localDef->mReadFromId = 0;
  671. mModule->AddLocalVariableDef(localDef);
  672. }
  673. }
  674. else
  675. {
  676. mModule->Visit(varDecl);
  677. }
  678. }
  679. void Visit(BfExpressionStatement* exprStatement) override
  680. {
  681. VisitChild(exprStatement->mExpression);
  682. }
  683. // void Visit(BfIfStatement* ifStmt) override
  684. // {
  685. // mModule->DoIfStatement(ifStmt,
  686. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  687. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  688. // }
  689. void Visit(BfBlock* block) override
  690. {
  691. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  692. return;
  693. int appendAllocIdx = -1;
  694. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  695. {
  696. auto child = block->mChildArr.mVals[childIdx];
  697. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  698. {
  699. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  700. {
  701. auto emitChild = block->mChildArr.mVals[emitIdx];
  702. mModule->UpdateSrcPos(emitChild);
  703. VisitChild(emitChild);
  704. if ((mFailed) && (!mIsFirstConstPass))
  705. break;
  706. }
  707. break;
  708. }
  709. }
  710. }
  711. };
  712. //////////////////////////////////////////////////////////////////////////
  713. BfModule* gLastCreatedModule = NULL;
  714. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  715. {
  716. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  717. gLastCreatedModule = this;
  718. mContext = context;
  719. mModuleName = moduleName;
  720. if (!moduleName.empty())
  721. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  722. mAddedToCount = false;
  723. mParentModule = NULL;
  724. mNextAltModule = NULL;
  725. mBfIRBuilder = NULL;
  726. mWantsIRIgnoreWrites = false;
  727. mModuleOptions = NULL;
  728. mLastUsedRevision = -1;
  729. mUsedSlotCount = -1;
  730. mIsReified = true;
  731. mReifyQueued = false;
  732. mIsSpecialModule = false;
  733. mIsComptimeModule = false;
  734. mIsScratchModule = false;
  735. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  736. mHadBuildError = false;
  737. mHadBuildWarning = false;
  738. mIgnoreErrors = false;
  739. mHadIgnoredError = false;
  740. mIgnoreWarnings = false;
  741. mReportErrors = true;
  742. mIsInsideAutoComplete = false;
  743. mIsDeleting = false;
  744. mSkipInnerLookup = false;
  745. mIsHotModule = false;
  746. mSetIllegalSrcPosition = false;
  747. mNoResolveGenericParams = false;
  748. mWroteToLib = false;
  749. mContext = context;
  750. mCompiler = context->mCompiler;
  751. mSystem = mCompiler->mSystem;
  752. mProject = NULL;
  753. mCurMethodState = NULL;
  754. mAttributeState = NULL;
  755. mCurLocalMethodId = 0;
  756. mParentNodeEntry = NULL;
  757. mRevision = -1;
  758. mRebuildIdx = 0;
  759. mLastModuleWrittenRevision = 0;
  760. mIsModuleMutable = false;
  761. mExtensionCount = 0;
  762. mIncompleteMethodCount = 0;
  763. mOnDemandMethodCount = 0;
  764. mHasGenericMethods = false;
  765. mCurMethodInstance = NULL;
  766. mCurTypeInstance = NULL;
  767. mAwaitingInitFinish = false;
  768. mAwaitingFinish = false;
  769. mHasFullDebugInfo = false;
  770. mHadHotObjectWrites = false;
  771. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  772. mBuiltInFuncs[i] = BfIRFunction();
  773. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  774. }
  775. void BfReportMemory();
  776. BfModule::~BfModule()
  777. {
  778. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  779. if (!mIsDeleting)
  780. RemoveModuleData();
  781. }
  782. void BfModule::RemoveModuleData()
  783. {
  784. BF_ASSERT(!mIsDeleting);
  785. if (!mModuleName.empty())
  786. {
  787. // Note: module names not necessarily unique
  788. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  789. }
  790. CleanupFileInstances();
  791. delete mBfIRBuilder;
  792. mBfIRBuilder = NULL;
  793. //delete mCpu;
  794. for (auto prevModule : mPrevIRBuilders)
  795. delete prevModule;
  796. mPrevIRBuilders.Clear();
  797. for (auto& pairVal : mDeferredMethodCallData)
  798. delete pairVal.mValue;
  799. mDeferredMethodCallData.Clear();
  800. mDeferredMethodIds.Clear();
  801. for (auto& specModulePair : mSpecializedMethodModules)
  802. delete specModulePair.mValue;
  803. mSpecializedMethodModules.Clear();
  804. if (mNextAltModule != NULL)
  805. delete mNextAltModule;
  806. mNextAltModule = NULL;
  807. if (mModuleOptions != NULL)
  808. delete mModuleOptions;
  809. mModuleOptions = NULL;
  810. BfReportMemory();
  811. }
  812. void BfModule::Init(bool isFullRebuild)
  813. {
  814. mContext->mFinishedModuleWorkList.Remove(this);
  815. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  816. BF_ASSERT(mIsReified);
  817. if (!mIsScratchModule)
  818. {
  819. mCompiler->mStats.mModulesStarted++;
  820. if (mIsReified)
  821. mCompiler->mStats.mReifiedModuleCount++;
  822. mAddedToCount = true;
  823. }
  824. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  825. mFuncReferences.Clear();
  826. mClassVDataRefs.Clear();
  827. mClassVDataExtRefs.Clear();
  828. //mTypeDataRefs.Clear();
  829. mDbgRawAllocDataRefs.Clear();
  830. CleanupFileInstances();
  831. mStaticFieldRefs.Clear();
  832. //mInterfaceSlotRefs.Clear();
  833. // If we are just doing an extension then the ownede types aren't rebuilt.
  834. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  835. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  836. if (isFullRebuild)
  837. mRevision = mCompiler->mRevision;
  838. BF_ASSERT(mCurTypeInstance == NULL);
  839. mIsModuleMutable = true;
  840. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  841. #ifdef _DEBUG
  842. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  843. #else
  844. EnsureIRBuilder(false);
  845. #endif
  846. mCurMethodState = NULL;
  847. mAwaitingInitFinish = true;
  848. mOnDemandMethodCount = 0;
  849. mAwaitingFinish = false;
  850. mHasForceLinkMarker = false;
  851. mUsedSlotCount = -1;
  852. }
  853. bool BfModule::WantsFinishModule()
  854. {
  855. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  856. }
  857. void BfModule::FinishInit()
  858. {
  859. BF_ASSERT(mAwaitingInitFinish);
  860. auto moduleOptions = GetModuleOptions();
  861. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  862. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  863. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  864. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  865. {
  866. // Og+ requires debug info
  867. moduleOptions.mEmitDebugInfo = 1;
  868. }
  869. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  870. if (mIsComptimeModule)
  871. mHasFullDebugInfo = false;
  872. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  873. (mIsComptimeModule))
  874. {
  875. mBfIRBuilder->DbgInit();
  876. }
  877. else
  878. mHasFullDebugInfo = false;
  879. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  880. ((moduleOptions.mEmitDebugInfo != 0)))
  881. {
  882. if (mCompiler->mOptions.IsCodeView())
  883. {
  884. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  885. }
  886. else
  887. {
  888. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  889. }
  890. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  891. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  892. }
  893. mAwaitingInitFinish = false;
  894. }
  895. void BfModule::ReifyModule()
  896. {
  897. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  898. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  899. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  900. mIsReified = true;
  901. mReifyQueued = false;
  902. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  903. mCompiler->mStats.mModulesReified++;
  904. }
  905. void BfModule::UnreifyModule()
  906. {
  907. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  908. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  909. mIsReified = false;
  910. mReifyQueued = false;
  911. StartNewRevision(RebuildKind_None, true);
  912. mCompiler->mStats.mModulesUnreified++;
  913. }
  914. void BfModule::CleanupFileInstances()
  915. {
  916. for (auto& itr : mNamedFileInstanceMap)
  917. {
  918. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  919. delete itr.mValue;
  920. }
  921. mCurFilePosition.mFileInstance = NULL;//
  922. mFileInstanceMap.Clear();
  923. mNamedFileInstanceMap.Clear();
  924. }
  925. void BfModule::Cleanup()
  926. {
  927. CleanupFileInstances();
  928. }
  929. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  930. {
  931. if (HasCompiledOutput())
  932. {
  933. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  934. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  935. {
  936. StartExtension();
  937. }
  938. }
  939. else
  940. {
  941. EnsureIRBuilder();
  942. }
  943. }
  944. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  945. {
  946. BF_ASSERT(!mIsDeleting);
  947. if (mBfIRBuilder == NULL)
  948. {
  949. if ((!mIsScratchModule) && (!mAddedToCount))
  950. {
  951. mCompiler->mStats.mModulesStarted++;
  952. mAddedToCount = true;
  953. }
  954. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  955. /*if (mCompiler->mIsResolveOnly)
  956. BF_ASSERT(mIsResolveOnly);*/
  957. mBfIRBuilder = new BfIRBuilder(this);
  958. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  959. if (mIsScratchModule)
  960. {
  961. mBfIRBuilder->mIgnoreWrites = true;
  962. BF_ASSERT(!dbgVerifyCodeGen);
  963. }
  964. #ifdef _DEBUG
  965. if (mCompiler->mIsResolveOnly)
  966. {
  967. // For "deep" verification testing
  968. /*if (!mIsSpecialModule)
  969. dbgVerifyCodeGen = true;*/
  970. // We only want to turn this off on smaller builds for testing
  971. mBfIRBuilder->mIgnoreWrites = true;
  972. if (dbgVerifyCodeGen)
  973. mBfIRBuilder->mIgnoreWrites = false;
  974. if (!mBfIRBuilder->mIgnoreWrites)
  975. {
  976. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  977. mBfIRBuilder->mDbgVerifyCodeGen = true;
  978. }
  979. }
  980. else if (!mIsReified)
  981. {
  982. mBfIRBuilder->mIgnoreWrites = true;
  983. }
  984. else
  985. {
  986. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  987. // code as we walk the AST
  988. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  989. if (
  990. (mModuleName == "-")
  991. //|| (mModuleName == "BeefTest2_ClearColorValue")
  992. //|| (mModuleName == "Tests_FuncRefs")
  993. )
  994. mBfIRBuilder->mDbgVerifyCodeGen = true;
  995. // Just for testing!
  996. //mBfIRBuilder->mIgnoreWrites = true;
  997. }
  998. #else
  999. if (mCompiler->mIsResolveOnly)
  1000. {
  1001. // Always ignore writes in resolveOnly for release builds
  1002. mBfIRBuilder->mIgnoreWrites = true;
  1003. }
  1004. else
  1005. {
  1006. // Just for memory testing! This breaks everything.
  1007. //mBfIRBuilder->mIgnoreWrites = true;
  1008. // For "deep" verification testing
  1009. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1010. }
  1011. #endif
  1012. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1013. }
  1014. }
  1015. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1016. {
  1017. String name = "FORCELINKMOD_" + module->mModuleName;
  1018. if (outName != NULL)
  1019. *outName = name;
  1020. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1021. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1022. }
  1023. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1024. {
  1025. BP_ZONE("BfModule::StartNewRevision");
  1026. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1027. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1028. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1029. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1030. {
  1031. // Cleaning up local methods may cause some necessary NewRevisions
  1032. force = true;
  1033. }
  1034. // Already on new revision?
  1035. if ((mRevision == mCompiler->mRevision) && (!force))
  1036. return;
  1037. mHadBuildError = false;
  1038. mHadBuildWarning = false;
  1039. mExtensionCount = 0;
  1040. mRevision = mCompiler->mRevision;
  1041. mRebuildIdx++;
  1042. ClearModuleData(!force);
  1043. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1044. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1045. mStringPoolRefs.Clear();
  1046. mDllImportEntries.Clear();
  1047. mImportFileNames.Clear();
  1048. for (auto& pairVal : mDeferredMethodCallData)
  1049. delete pairVal.mValue;
  1050. mDeferredMethodCallData.Clear();
  1051. mDeferredMethodIds.Clear();
  1052. mModuleRefs.Clear();
  1053. mOutFileNames.Clear();
  1054. mTypeDataRefs.Clear();
  1055. mInterfaceSlotRefs.Clear();
  1056. if (rebuildKind == BfModule::RebuildKind_None)
  1057. {
  1058. for (auto& specPair : mSpecializedMethodModules)
  1059. {
  1060. auto specModule = specPair.mValue;
  1061. if (specModule->mIsReified != mIsReified)
  1062. {
  1063. if (mIsReified)
  1064. specModule->ReifyModule();
  1065. else
  1066. specModule->UnreifyModule();
  1067. }
  1068. }
  1069. }
  1070. else
  1071. {
  1072. for (auto& specPair : mSpecializedMethodModules)
  1073. {
  1074. auto specModule = specPair.mValue;
  1075. delete specModule;
  1076. }
  1077. }
  1078. mSpecializedMethodModules.Clear();
  1079. delete mNextAltModule;
  1080. mNextAltModule = NULL;
  1081. BF_ASSERT(mModuleOptions == NULL);
  1082. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1083. bool needsTypePopulated = false;
  1084. int oldOnDemandCount = 0;
  1085. // We don't have to rebuild types in the unspecialized module because there is no
  1086. // data that's needed -- their method instances are all NULL and the module
  1087. // doesn't get included in the build
  1088. if (this != mContext->mScratchModule)
  1089. {
  1090. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1091. {
  1092. auto typeInst = mOwnedTypeInstances[typeIdx];
  1093. if (!typeInst->IsDeleting())
  1094. {
  1095. typeInst->mIsReified = mIsReified;
  1096. if (rebuildKind != BfModule::RebuildKind_None)
  1097. {
  1098. if (typeInst->IsOnDemand())
  1099. {
  1100. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1101. if (rebuildKind == BfModule::RebuildKind_All)
  1102. mContext->DeleteType(typeInst);
  1103. else
  1104. {
  1105. RebuildMethods(typeInst);
  1106. }
  1107. }
  1108. else
  1109. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1110. mContext->RebuildType(typeInst, false, false, true);
  1111. //mContext->RebuildType(typeInst, false, false, false);
  1112. }
  1113. else
  1114. {
  1115. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1116. {
  1117. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1118. methodInstance->mDeclModule = this;
  1119. };
  1120. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1121. {
  1122. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1123. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1124. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1125. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1126. {
  1127. oldOnDemandCount++;
  1128. }
  1129. _HandleMethod(methodGroup.mDefault);
  1130. if (methodGroup.mMethodSpecializationMap != NULL)
  1131. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1132. _HandleMethod(kv.mValue);
  1133. }
  1134. }
  1135. if (typeInst->IsDeleting())
  1136. typeIdx--;
  1137. }
  1138. }
  1139. }
  1140. if (!mIsDeleting)
  1141. Init();
  1142. mOnDemandMethodCount += oldOnDemandCount;
  1143. VerifyOnDemandMethods();
  1144. }
  1145. void BfModule::StartExtension()
  1146. {
  1147. BF_ASSERT(!mIsModuleMutable);
  1148. BfLogSysM("Extension started of module %p\n", this);
  1149. mExtensionCount++;
  1150. if (mBfIRBuilder != NULL)
  1151. mPrevIRBuilders.push_back(mBfIRBuilder);
  1152. mBfIRBuilder = NULL;
  1153. mWantsIRIgnoreWrites = false;
  1154. mFuncReferences.Clear();
  1155. mClassVDataRefs.Clear();
  1156. mClassVDataExtRefs.Clear();
  1157. for (auto& kv : mTypeDataRefs)
  1158. kv.mValue = BfIRValue();
  1159. mDbgRawAllocDataRefs.Clear();
  1160. mStringCharPtrPool.Clear();
  1161. mStringObjectPool.Clear();
  1162. mStaticFieldRefs.Clear();
  1163. for (auto& kv : mInterfaceSlotRefs)
  1164. kv.mValue = BfIRValue();
  1165. for (auto& pairVal : mDeferredMethodCallData)
  1166. delete pairVal.mValue;
  1167. mDeferredMethodCallData.Clear();
  1168. mDeferredMethodIds.Clear();
  1169. DisownMethods();
  1170. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1171. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1172. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1173. Init(false);
  1174. if (!wasAwaitingInitFinish)
  1175. FinishInit();
  1176. mOnDemandMethodCount = prevOnDemandMethodCount;
  1177. }
  1178. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1179. {
  1180. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1181. BfIRValue vDataValue;
  1182. if (hasObjectDebugFlags)
  1183. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1184. else
  1185. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1186. typeValueParams.push_back(vDataValue);
  1187. if (hasObjectDebugFlags)
  1188. {
  1189. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1190. typeValueParams.push_back(GetDefaultValue(primType));
  1191. }
  1192. }
  1193. BfIRValue BfModule::GetConstValue(int64 val)
  1194. {
  1195. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1196. }
  1197. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1198. {
  1199. BfType* checkType = type;
  1200. if (type->IsTypedPrimitive())
  1201. {
  1202. checkType = type->GetUnderlyingType();
  1203. }
  1204. if (checkType->IsPrimitiveType())
  1205. {
  1206. auto primType = (BfPrimitiveType*)checkType;
  1207. if (checkType->IsFloat())
  1208. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1209. else
  1210. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1211. }
  1212. return BfIRValue();
  1213. }
  1214. BfIRValue BfModule::GetConstValue8(int val)
  1215. {
  1216. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1217. }
  1218. BfIRValue BfModule::GetConstValue32(int32 val)
  1219. {
  1220. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1221. }
  1222. BfIRValue BfModule::GetConstValue64(int64 val)
  1223. {
  1224. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1225. }
  1226. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1227. {
  1228. PopulateType(type, BfPopulateType_Data);
  1229. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1230. if (type->IsTypedPrimitive())
  1231. {
  1232. auto underlyingType = type->GetUnderlyingType();
  1233. if (underlyingType == NULL)
  1234. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1235. return GetDefaultValue(type->GetUnderlyingType());
  1236. }
  1237. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1238. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1239. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1240. if ((type->IsIntegral()) || (type->IsBoolean()))
  1241. {
  1242. auto primType = (BfPrimitiveType*)type;
  1243. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1244. }
  1245. if (type->IsFloat())
  1246. {
  1247. auto primType = (BfPrimitiveType*)type;
  1248. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1249. }
  1250. if (type->IsVoid())
  1251. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1252. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1253. }
  1254. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1255. {
  1256. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1257. if (type->mSize == 0)
  1258. return BfTypedValue(BfIRValue::sValueless, type);
  1259. else
  1260. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1261. }
  1262. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1263. {
  1264. if (type->IsVar())
  1265. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1266. PopulateType(type, BfPopulateType_Data);
  1267. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1268. if (defaultValueKind == BfDefaultValueKind_Undef)
  1269. {
  1270. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1271. }
  1272. BfTypedValue typedValue;
  1273. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1274. {
  1275. if (type->IsRef())
  1276. {
  1277. BfRefType* refType = (BfRefType*)type;
  1278. BfType* underlyingType = refType->GetUnderlyingType();
  1279. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1280. }
  1281. else
  1282. {
  1283. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1284. }
  1285. if (!mBfIRBuilder->mIgnoreWrites)
  1286. {
  1287. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1288. GetConstValue(type->mSize), type->mAlign);
  1289. }
  1290. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1291. typedValue = LoadValue(typedValue);
  1292. return typedValue;
  1293. }
  1294. if ((type->IsRef()) && (!allowRef))
  1295. {
  1296. BfRefType* refType = (BfRefType*)type;
  1297. BfType* underlyingType = refType->GetUnderlyingType();
  1298. if (underlyingType->IsValuelessType())
  1299. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1300. else
  1301. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1302. }
  1303. else
  1304. {
  1305. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1306. }
  1307. return typedValue;
  1308. }
  1309. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1310. {
  1311. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1312. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1313. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1314. BfIRValue strConstant;
  1315. if (define)
  1316. {
  1317. strConstant = mBfIRBuilder->CreateConstString(str);
  1318. }
  1319. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1320. true, BfIRLinkageType_External,
  1321. strConstant, stringDataName);
  1322. if (define)
  1323. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1324. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1325. }
  1326. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1327. {
  1328. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1329. mBfIRBuilder->PopulateType(stringTypeInst);
  1330. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1331. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1332. BfIRValue stringValData;
  1333. if (define)
  1334. {
  1335. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1336. mStringCharPtrPool[stringId] = stringCharsVal;
  1337. SizedArray<BfIRValue, 8> typeValueParams;
  1338. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1339. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1340. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1341. typeValueParams.clear();
  1342. typeValueParams.push_back(objData);
  1343. if (lenByteCount == 4)
  1344. {
  1345. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1346. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1347. }
  1348. else
  1349. {
  1350. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1351. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1352. }
  1353. typeValueParams.push_back(stringCharsVal); // mPtr
  1354. for (int fieldIdx = 0; fieldIdx < (int)stringTypeInst->mFieldInstances.size(); fieldIdx++)
  1355. {
  1356. auto fieldInstance = &stringTypeInst->mFieldInstances[fieldIdx];
  1357. if (fieldInstance->mDataIdx < 4)
  1358. continue;
  1359. while (fieldInstance->mDataIdx >= typeValueParams.size())
  1360. typeValueParams.Add(BfIRValue());
  1361. typeValueParams[fieldInstance->mDataIdx] = GetDefaultValue(fieldInstance->mResolvedType);
  1362. }
  1363. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1364. }
  1365. mBfIRBuilder->PopulateType(stringTypeInst);
  1366. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1367. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1368. true,
  1369. BfIRLinkageType_External,
  1370. define ? stringValData : BfIRValue(),
  1371. stringObjName);
  1372. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1373. return stringVal;
  1374. }
  1375. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1376. {
  1377. BF_ASSERT(constantStr.IsConst());
  1378. if (constHolder == NULL)
  1379. constHolder = mBfIRBuilder;
  1380. auto constant = constHolder->GetConstant(constantStr);
  1381. if (constant->mTypeCode == BfTypeCode_StringId)
  1382. {
  1383. return constant->mInt32;
  1384. }
  1385. while (constant->mConstType == BfConstType_BitCast)
  1386. {
  1387. auto constBitCast = (BfConstantBitCast*)constant;
  1388. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1389. }
  1390. if (constant->mConstType == BfConstType_GEP32_2)
  1391. {
  1392. auto constGEP = (BfConstantGEP32_2*)constant;
  1393. constant = constHolder->GetConstantById(constGEP->mTarget);
  1394. }
  1395. if (constant->mConstType == BfConstType_GlobalVar)
  1396. {
  1397. auto constGV = (BfGlobalVar*)constant;
  1398. const char* strDataPrefix = "__bfStrData";
  1399. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1400. return atoi(constGV->mName + strlen(strDataPrefix));
  1401. const char* strObjPrefix = "__bfStrObj";
  1402. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1403. return atoi(constGV->mName + strlen(strObjPrefix));
  1404. }
  1405. return -1;
  1406. }
  1407. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1408. {
  1409. int strId = GetStringPoolIdx(constantStr, constHolder);
  1410. if (strId != -1)
  1411. {
  1412. auto& entry = mContext->mStringObjectIdMap[strId];
  1413. return &entry.mString;
  1414. }
  1415. return NULL;
  1416. }
  1417. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1418. {
  1419. BfIRValue* irValue = NULL;
  1420. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1421. return *irValue;
  1422. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1423. if (!mStringObjectPool.ContainsKey(stringId))
  1424. mStringPoolRefs.Add(stringId);
  1425. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1426. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1427. *irValue = strCharPtrConst;
  1428. return strCharPtrConst;
  1429. }
  1430. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1431. {
  1432. if (strValue.IsConst())
  1433. {
  1434. int stringId = GetStringPoolIdx(strValue);
  1435. BF_ASSERT(stringId != -1);
  1436. return GetStringCharPtr(stringId);
  1437. }
  1438. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1439. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1440. return charPtr;
  1441. }
  1442. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1443. {
  1444. return GetStringCharPtr(GetStringObjectValue(str));
  1445. }
  1446. BfIRValue BfModule::GetStringObjectValue(int strId)
  1447. {
  1448. BfIRValue* objValue;
  1449. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1450. return *objValue;
  1451. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1452. return GetStringObjectValue(stringPoolEntry.mString, true);
  1453. }
  1454. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1455. {
  1456. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1457. mBfIRBuilder->PopulateType(stringType);
  1458. int strId = mContext->GetStringLiteralId(str);
  1459. BfIRValue* irValuePtr = NULL;
  1460. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1461. return *irValuePtr;
  1462. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1463. if (!mStringCharPtrPool.ContainsKey(strId))
  1464. mStringPoolRefs.Add(strId);
  1465. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1466. *irValuePtr = strObject;
  1467. mStringPoolRefs.Add(strId);
  1468. return strObject;
  1469. }
  1470. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1471. {
  1472. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1473. type,
  1474. true,
  1475. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1476. constant,
  1477. name.c_str());
  1478. return newConst;
  1479. }
  1480. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1481. {
  1482. auto curScope = mCurMethodState->mCurScope;
  1483. if (curScope->mLabelNode != NULL)
  1484. {
  1485. curScope->mLabelNode->ToString(curScope->mLabel);
  1486. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1487. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1488. auto autoComplete = mCompiler->GetAutoComplete();
  1489. if (autoComplete != NULL)
  1490. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1491. }
  1492. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1493. {
  1494. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1495. while (checkScope != NULL)
  1496. {
  1497. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1498. {
  1499. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1500. if (errorNode != NULL)
  1501. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1502. break;
  1503. }
  1504. checkScope = checkScope->mPrevScope;
  1505. }
  1506. }
  1507. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1508. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1509. {
  1510. if (prevScope->mHadScopeValueRetain)
  1511. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1512. else
  1513. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1514. }
  1515. mCurMethodState->mBlockNestLevel++;
  1516. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1517. {
  1518. // DIScope could be NULL if we're in an unspecialized method (for example)
  1519. if (mCurMethodState->mCurScope->mDIScope)
  1520. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1521. }
  1522. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1523. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1524. }
  1525. void BfModule::RestoreScoreState_LocalVariables()
  1526. {
  1527. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1528. {
  1529. auto localVar = mCurMethodState->mLocals.back();
  1530. LocalVariableDone(localVar, false);
  1531. mCurMethodState->mLocals.pop_back();
  1532. if (localVar->mShadowedLocal != NULL)
  1533. {
  1534. BfLocalVarEntry* localVarEntryPtr;
  1535. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1536. {
  1537. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1538. }
  1539. }
  1540. else
  1541. {
  1542. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1543. }
  1544. delete localVar;
  1545. }
  1546. }
  1547. void BfModule::RestoreScopeState()
  1548. {
  1549. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1550. mCurMethodState->mBlockNestLevel--;
  1551. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1552. {
  1553. BfIRBlock afterEndBlock;
  1554. if (!mCurMethodState->mLeftBlockUncond)
  1555. {
  1556. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1557. mBfIRBuilder->CreateBr(afterEndBlock);
  1558. mBfIRBuilder->ClearDebugLocation_Last();
  1559. }
  1560. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1561. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1562. if (afterEndBlock)
  1563. {
  1564. mBfIRBuilder->AddBlock(afterEndBlock);
  1565. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1566. }
  1567. }
  1568. if (!mCurMethodState->mLeftBlockUncond)
  1569. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1570. RestoreScoreState_LocalVariables();
  1571. if (mCurMethodState->mCurScope->mValueScopeStart)
  1572. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1573. mCurMethodState->mCurScope = prevScopeData;
  1574. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1575. }
  1576. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1577. {
  1578. if (mBfIRBuilder->mIgnoreWrites)
  1579. return mBfIRBuilder->GetFakeVal();
  1580. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1581. mBfIRBuilder->PopulateType(type);
  1582. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1583. if (!mBfIRBuilder->mIgnoreWrites)
  1584. BF_ASSERT(!prevInsertBlock.IsFake());
  1585. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1586. BfIRValue allocaInst;
  1587. if (arraySize)
  1588. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1589. else
  1590. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1591. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1592. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1593. if (name != NULL)
  1594. mBfIRBuilder->SetName(allocaInst, name);
  1595. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1596. if ((addLifetime) && (WantsLifetimes()))
  1597. {
  1598. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1599. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1600. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1601. }
  1602. return allocaInst;
  1603. }
  1604. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1605. {
  1606. if (mBfIRBuilder->mIgnoreWrites)
  1607. return mBfIRBuilder->GetFakeVal();
  1608. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1609. mBfIRBuilder->PopulateType(typeInst);
  1610. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1611. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1612. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1613. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1614. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1615. if (name != NULL)
  1616. mBfIRBuilder->SetName(allocaInst, name);
  1617. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1618. if ((addLifetime) && (WantsLifetimes()))
  1619. {
  1620. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1621. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1622. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1623. }
  1624. return allocaInst;
  1625. }
  1626. void BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1627. {
  1628. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1629. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1630. /*if (mCurMethodState->mInHeadScope)
  1631. isScopeAlloc = true;*/
  1632. if (scopeData == NULL)
  1633. return;
  1634. auto checkBaseType = val.mType->ToTypeInstance();
  1635. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1636. {
  1637. bool hadDtorCall = false;
  1638. while (checkBaseType != NULL)
  1639. {
  1640. checkBaseType->mTypeDef->PopulateMemberSets();
  1641. BfMemberSetEntry* entry = NULL;
  1642. BfMethodDef* dtorMethodDef = NULL;
  1643. checkBaseType->mTypeDef->mMethodSet.TryGetWith(String("~this"), &entry);
  1644. if (entry != NULL)
  1645. dtorMethodDef = (BfMethodDef*)entry->mMemberDef;
  1646. if (dtorMethodDef != NULL)
  1647. {
  1648. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1649. if (dtorMethodInstance)
  1650. {
  1651. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1652. BfIRValue useVal = val.mValue;
  1653. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1654. if (isDynAlloc)
  1655. {
  1656. //
  1657. }
  1658. else if (condAlloca)
  1659. {
  1660. BF_ASSERT(!IsTargetingBeefBackend());
  1661. BF_ASSERT(!isDynAlloc);
  1662. auto valPtr = CreateAlloca(checkBaseType);
  1663. mBfIRBuilder->CreateStore(useVal, valPtr);
  1664. useVal = valPtr;
  1665. }
  1666. SizedArray<BfIRValue, 1> llvmArgs;
  1667. llvmArgs.push_back(useVal);
  1668. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1669. if (deferredCall != NULL)
  1670. {
  1671. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1672. if (condAlloca)
  1673. deferredCall->mArgsNeedLoad = true;
  1674. }
  1675. hadDtorCall = true;
  1676. break;
  1677. }
  1678. }
  1679. checkBaseType = checkBaseType->mBaseType;
  1680. }
  1681. return;
  1682. }
  1683. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1684. if (mayEscape)
  1685. {
  1686. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1687. {
  1688. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1689. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1690. if (!isDyn)
  1691. {
  1692. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1693. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1694. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1695. if (!dtorMethodInstance.mMethodInstance)
  1696. {
  1697. Fail(StrFormat("Unable to find %s", methodName));
  1698. }
  1699. else
  1700. {
  1701. SizedArray<BfIRValue, 1> llvmArgs;
  1702. if (IsTargetingBeefBackend())
  1703. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1704. else
  1705. llvmArgs.push_back(val.mValue);
  1706. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1707. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1708. if (arraySize)
  1709. llvmArgs.push_back(arraySize);
  1710. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1711. }
  1712. }
  1713. else
  1714. {
  1715. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1716. {
  1717. BfIRValue clearSize = arraySize;
  1718. if (val.mType->GetStride() > 1)
  1719. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1720. const char* methodName = "SetDeletedX";
  1721. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1722. BF_ASSERT(dtorMethodInstance);
  1723. if (!dtorMethodInstance)
  1724. {
  1725. Fail(StrFormat("Unable to find %s", methodName));
  1726. }
  1727. else
  1728. {
  1729. SizedArray<BfIRValue, 1> llvmArgs;
  1730. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1731. llvmArgs.push_back(clearSize);
  1732. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1733. }
  1734. }
  1735. else
  1736. {
  1737. intptr clearSize = val.mType->mSize;
  1738. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1739. if (constant != NULL)
  1740. clearSize = (intptr)(clearSize * constant->mInt64);
  1741. const char* funcName = "SetDeleted1";
  1742. if (clearSize >= 16)
  1743. funcName = "SetDeleted16";
  1744. else if (clearSize >= 8)
  1745. funcName = "SetDeleted8";
  1746. else if (clearSize >= 4)
  1747. funcName = "SetDeleted4";
  1748. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1749. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1750. if (!dtorMethodInstance)
  1751. {
  1752. Fail(StrFormat("Unable to find %s", funcName));
  1753. }
  1754. else
  1755. {
  1756. SizedArray<BfIRValue, 1> llvmArgs;
  1757. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1758. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1759. }
  1760. }
  1761. }
  1762. }
  1763. }
  1764. }
  1765. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1766. {
  1767. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1768. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1769. return false;
  1770. auto checkTypeInstance = startTypeInstance;
  1771. while (checkTypeInstance != NULL)
  1772. {
  1773. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1774. {
  1775. if (fieldInstance.mMergedDataIdx != -1)
  1776. {
  1777. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1778. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1779. {
  1780. // For fields added in extensions, we automatically initialize those if necessary
  1781. auto fieldDef = fieldInstance.GetFieldDef();
  1782. if (!fieldDef->mDeclaringType->IsExtension())
  1783. return false;
  1784. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1785. {
  1786. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1787. mBfIRBuilder->SaveDebugLocation();
  1788. if (localVar->IsParam())
  1789. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1790. else
  1791. {
  1792. BF_ASSERT(localVar->mDeclBlock);
  1793. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1794. }
  1795. mBfIRBuilder->ClearDebugLocation();
  1796. BfIRValue curVal;
  1797. if (localVar->mIsThis)
  1798. curVal = mBfIRBuilder->GetArgument(0);
  1799. else
  1800. curVal = localVar->mAddr;
  1801. auto subTypeInstance = startTypeInstance;
  1802. while (subTypeInstance != checkTypeInstance)
  1803. {
  1804. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1805. subTypeInstance = subTypeInstance->mBaseType;
  1806. }
  1807. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1808. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1809. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1810. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1811. mBfIRBuilder->RestoreDebugLocation();
  1812. }
  1813. localVar->mUnassignedFieldFlags &= ~checkMask;
  1814. if (localVar->mUnassignedFieldFlags == 0)
  1815. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1816. }
  1817. }
  1818. }
  1819. checkTypeInstance = checkTypeInstance->mBaseType;
  1820. }
  1821. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1822. }
  1823. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1824. {
  1825. //if (localVar->mAddr == NULL)
  1826. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1827. {
  1828. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1829. {
  1830. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1831. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1832. }
  1833. }*/
  1834. BfAstNode* localNameNode = localVar->mNameNode;
  1835. if (localVar->mIsThis)
  1836. {
  1837. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1838. }
  1839. if (localNameNode != NULL)
  1840. {
  1841. bool isOut = false;
  1842. if (localVar->mResolvedType->IsRef())
  1843. {
  1844. auto refType = (BfRefType*)localVar->mResolvedType;
  1845. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1846. }
  1847. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1848. {
  1849. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1850. TryLocalVariableInit(localVar);
  1851. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1852. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1853. // We may have init blocks that we aren't processing here...
  1854. if ((mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  1855. deferFullAnalysis = true;
  1856. //bool deferFullAnalysis = true;
  1857. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1858. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1859. (!localVar->mIsImplicitParam))
  1860. {
  1861. if (deferUsageWarning)
  1862. {
  1863. // Ignore
  1864. }
  1865. else if (localVar->mIsThis)
  1866. {
  1867. bool foundFields = false;
  1868. auto checkTypeInstance = mCurTypeInstance;
  1869. while (checkTypeInstance != NULL)
  1870. {
  1871. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1872. {
  1873. if (fieldInstance.mMergedDataIdx != -1)
  1874. {
  1875. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1876. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1877. {
  1878. auto fieldDef = fieldInstance.GetFieldDef();
  1879. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1880. {
  1881. String propName;
  1882. if (propertyDeclaration->mNameNode != NULL)
  1883. propertyDeclaration->mNameNode->ToString(propName);
  1884. if (checkTypeInstance == mCurTypeInstance)
  1885. {
  1886. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1887. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1888. }
  1889. else
  1890. {
  1891. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  1892. TypeToString(checkTypeInstance).c_str(),
  1893. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1894. }
  1895. }
  1896. else
  1897. {
  1898. if (checkTypeInstance == mCurTypeInstance)
  1899. {
  1900. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1901. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1902. }
  1903. else
  1904. {
  1905. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1906. TypeToString(checkTypeInstance).c_str(),
  1907. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1908. }
  1909. }
  1910. foundFields = true;
  1911. }
  1912. }
  1913. }
  1914. checkTypeInstance = checkTypeInstance->mBaseType;
  1915. }
  1916. if (!foundFields)
  1917. {
  1918. if (mCurTypeInstance->mInstSize > 0)
  1919. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1920. }
  1921. }
  1922. else if (localVar->IsParam())
  1923. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1924. else if (!deferUsageWarning)
  1925. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1926. }
  1927. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1928. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1929. }
  1930. }
  1931. }
  1932. void BfModule::CreateRetValLocal()
  1933. {
  1934. if (mCurMethodState->mRetVal)
  1935. {
  1936. BfLocalVariable* localDef = new BfLocalVariable();
  1937. localDef->mName = "return";
  1938. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  1939. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  1940. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1941. AddLocalVariableDef(localDef);
  1942. }
  1943. else if (mCurMethodState->mRetValAddr)
  1944. {
  1945. BfLocalVariable* localDef = new BfLocalVariable();
  1946. localDef->mName = "return";
  1947. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  1948. localDef->mAddr = mCurMethodState->mRetValAddr;
  1949. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1950. AddLocalVariableDef(localDef);
  1951. }
  1952. }
  1953. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1954. {
  1955. auto checkScope = mCurMethodState->mCurScope;
  1956. while (true)
  1957. {
  1958. if (checkScope == scopeData)
  1959. break;
  1960. checkScope->mHadOuterDynStack = true;
  1961. checkScope = checkScope->mPrevScope;
  1962. }
  1963. }
  1964. void BfModule::SaveStackState(BfScopeData* scopeData)
  1965. {
  1966. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1967. // scopes within scopeData restore the stack
  1968. auto checkScope = mCurMethodState->mCurScope;
  1969. while (true)
  1970. {
  1971. if (checkScope == scopeData)
  1972. {
  1973. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1974. {
  1975. if (mBfIRBuilder->mHasDebugInfo)
  1976. mBfIRBuilder->SaveDebugLocation();
  1977. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1978. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1979. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1980. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1981. mBfIRBuilder->SetInsertPoint(prevPos);
  1982. if (mBfIRBuilder->mHasDebugInfo)
  1983. mBfIRBuilder->RestoreDebugLocation();
  1984. }
  1985. break;
  1986. }
  1987. if (checkScope->mSavedStack)
  1988. {
  1989. for (auto usage : checkScope->mSavedStackUses)
  1990. mBfIRBuilder->EraseInstFromParent(usage);
  1991. checkScope->mSavedStackUses.Clear();
  1992. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1993. checkScope->mSavedStack = BfIRValue();
  1994. }
  1995. checkScope = checkScope->mPrevScope;
  1996. }
  1997. }
  1998. BfIRValue BfModule::ValueScopeStart()
  1999. {
  2000. if (IsTargetingBeefBackend())
  2001. return mBfIRBuilder->CreateValueScopeStart();
  2002. return BfIRValue();
  2003. }
  2004. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2005. {
  2006. if (valueScopeStart)
  2007. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2008. }
  2009. BfProjectSet* BfModule::GetVisibleProjectSet()
  2010. {
  2011. if (mCurMethodState == NULL)
  2012. return NULL;
  2013. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2014. {
  2015. HashSet<BfType*> seenTypes;
  2016. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2017. {
  2018. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2019. {
  2020. for (auto dep : project->mDependencies)
  2021. _AddProject(dep);
  2022. }
  2023. };
  2024. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2025. {
  2026. auto typeInstance = type->ToTypeInstance();
  2027. if (typeInstance == NULL)
  2028. {
  2029. if (type->IsSizedArray())
  2030. _AddType(type->GetUnderlyingType());
  2031. return;
  2032. }
  2033. if (typeInstance->IsTuple())
  2034. {
  2035. for (auto& fieldInst : typeInstance->mFieldInstances)
  2036. {
  2037. if (fieldInst.mDataIdx != -1)
  2038. _AddType(fieldInst.mResolvedType);
  2039. }
  2040. }
  2041. _AddProject(typeInstance->mTypeDef->mProject);
  2042. if (typeInstance->mGenericTypeInfo == NULL)
  2043. return;
  2044. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2045. {
  2046. if (seenTypes.Add(type))
  2047. _AddType(type);
  2048. }
  2049. };
  2050. if (mCurTypeInstance != NULL)
  2051. _AddType(mCurTypeInstance);
  2052. auto methodState = mCurMethodState;
  2053. while (methodState != NULL)
  2054. {
  2055. if (methodState->mMethodInstance != NULL)
  2056. {
  2057. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2058. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2059. {
  2060. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2061. _AddType(type);
  2062. }
  2063. }
  2064. methodState = methodState->mPrevMethodState;
  2065. }
  2066. }
  2067. return &mCurMethodState->mVisibleProjectSet;
  2068. }
  2069. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2070. {
  2071. auto bfParser = astNode->GetSourceData()->ToParserData();
  2072. if (bfParser == NULL)
  2073. return NULL;
  2074. BfFileInstance** fileInstancePtr = NULL;
  2075. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2076. {
  2077. return *fileInstancePtr;
  2078. }
  2079. else
  2080. {
  2081. // It's possible two parsers have the same file name (ie: mNextRevision)
  2082. BfFileInstance** namedFileInstancePtr = NULL;
  2083. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2084. {
  2085. auto bfFileInstance = *namedFileInstancePtr;
  2086. *fileInstancePtr = bfFileInstance;
  2087. return bfFileInstance;
  2088. }
  2089. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2090. auto bfFileInstance = new BfFileInstance();
  2091. *fileInstancePtr = bfFileInstance;
  2092. *namedFileInstancePtr = bfFileInstance;
  2093. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2094. bfFileInstance->mParser = bfParser;
  2095. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2096. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2097. {
  2098. String fileName = bfParser->mFileName;
  2099. for (int i = 0; i < (int)fileName.length(); i++)
  2100. {
  2101. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2102. fileName[i] = DIR_SEP_CHAR;
  2103. }
  2104. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2105. }
  2106. return bfFileInstance;
  2107. }
  2108. }
  2109. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2110. {
  2111. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2112. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2113. return;
  2114. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2115. if (astNode == NULL)
  2116. return;
  2117. auto bfParser = astNode->GetSourceData()->ToParserData();
  2118. if (bfParser == NULL)
  2119. return;
  2120. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2121. {
  2122. if (mCurFilePosition.mFileInstance != NULL)
  2123. {
  2124. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2125. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2126. }
  2127. auto bfFileInstance = GetFileFromNode(astNode);
  2128. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2129. {
  2130. mCurFilePosition = bfFileInstance->mPrevPosition;
  2131. }
  2132. else
  2133. {
  2134. mCurFilePosition.mFileInstance = bfFileInstance;
  2135. mCurFilePosition.mCurLine = 0;
  2136. mCurFilePosition.mCurSrcPos = 0;
  2137. }
  2138. }
  2139. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2140. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2141. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2142. if (jumpEntry->mCharIdx > srcPos)
  2143. jumpEntry--;
  2144. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2145. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2146. mCurFilePosition.mCurColumn = 0;
  2147. while (mCurFilePosition.mCurSrcPos < srcPos)
  2148. {
  2149. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2150. {
  2151. mCurFilePosition.mCurLine++;
  2152. mCurFilePosition.mCurColumn = 0;
  2153. }
  2154. else
  2155. {
  2156. mCurFilePosition.mCurColumn++;
  2157. }
  2158. mCurFilePosition.mCurSrcPos++;
  2159. }
  2160. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2161. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2162. {
  2163. int column = mCurFilePosition.mCurColumn + 1;
  2164. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2165. {
  2166. // Set to illegal position
  2167. column = 0;
  2168. }
  2169. if (mSetIllegalSrcPosition)
  2170. column = 0;
  2171. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2172. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2173. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2174. {
  2175. // This is from a different scope...
  2176. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2177. {
  2178. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2179. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2180. }
  2181. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2182. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2183. }
  2184. else
  2185. {
  2186. if (mCurMethodState->mCurScope->mAltDIFile)
  2187. {
  2188. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2189. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2190. }
  2191. }
  2192. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2193. if (mCurMethodState->mCrossingMixin)
  2194. inlineAt = BfIRMDNode();
  2195. if ((!useDIScope) && (mIsComptimeModule))
  2196. useDIScope = wantDIFile;
  2197. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2198. if ((flags & BfSrcPosFlag_Expression) == 0)
  2199. mBfIRBuilder->CreateStatementStart();
  2200. }
  2201. }
  2202. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2203. {
  2204. // We've turned off expr src pos (for now?)
  2205. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2206. }
  2207. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2208. {
  2209. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2210. SetIllegalSrcPos();
  2211. }
  2212. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2213. {
  2214. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2215. {
  2216. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2217. {
  2218. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2219. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2220. }
  2221. else
  2222. {
  2223. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2224. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2225. }
  2226. if ((flags & BfSrcPosFlag_Expression) == 0)
  2227. mBfIRBuilder->CreateStatementStart();
  2228. }
  2229. }
  2230. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2231. {
  2232. // We've turned off expr src pos (for now?)
  2233. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2234. }
  2235. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2236. {
  2237. if ((protection == BfProtection_Public) ||
  2238. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2239. ((protection == BfProtection_Private) && (allowPrivate)))
  2240. return true;
  2241. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2242. {
  2243. mAttributeState->mUsed = true;
  2244. return true;
  2245. }
  2246. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2247. {
  2248. if (CheckInternalProtection(checkType))
  2249. return true;
  2250. }
  2251. return false;
  2252. }
  2253. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2254. {
  2255. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2256. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2257. {
  2258. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2259. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2260. }
  2261. allowProtected = allowPrivate;
  2262. }
  2263. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2264. {
  2265. if (memberProtection == BfProtection_Hidden)
  2266. return false;
  2267. if (memberProtection == BfProtection_Public)
  2268. return true;
  2269. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2270. {
  2271. BfTypeInstance* curCheckType = mCurTypeInstance;
  2272. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2273. {
  2274. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2275. curCheckType = mixinOwner;
  2276. }
  2277. bool allowPrivate = (curCheckType != NULL) && (memberOwner->mTypeDef == curCheckType->mTypeDef);
  2278. if (curCheckType != NULL)
  2279. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2280. if (allowPrivate)
  2281. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2282. else
  2283. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2284. }
  2285. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2286. return true;
  2287. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2288. {
  2289. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2290. {
  2291. bool allowProtected = false;
  2292. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2293. auto curCheckType = mCurTypeInstance;
  2294. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2295. {
  2296. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2297. curCheckType = mixinOwner;
  2298. }
  2299. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2300. {
  2301. auto lookupCheckType = lookupStartType;
  2302. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2303. {
  2304. if (lookupCheckType == curCheckType)
  2305. {
  2306. allowProtected = true;
  2307. break;
  2308. }
  2309. if (lookupCheckType == memberOwner)
  2310. break;
  2311. lookupCheckType = lookupCheckType->mBaseType;
  2312. if (lookupCheckType == NULL)
  2313. break;
  2314. }
  2315. }
  2316. else
  2317. {
  2318. auto lookupCheckType = curCheckType;
  2319. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2320. {
  2321. if (lookupCheckType == memberOwner)
  2322. {
  2323. allowProtected = true;
  2324. break;
  2325. }
  2326. lookupCheckType = lookupCheckType->mBaseType;
  2327. if (lookupCheckType == NULL)
  2328. break;
  2329. }
  2330. }
  2331. if (!allowProtected)
  2332. {
  2333. // It's possible our outer type is derived from 'memberOwner'
  2334. while (curCheckType->mTypeDef->mNestDepth > 0)
  2335. {
  2336. curCheckType = GetOuterType(curCheckType);
  2337. if (curCheckType == NULL)
  2338. break;
  2339. auto lookupCheckType = lookupStartType;
  2340. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2341. {
  2342. if (lookupCheckType == curCheckType)
  2343. {
  2344. allowProtected = true;
  2345. break;
  2346. }
  2347. if (lookupCheckType == memberOwner)
  2348. break;
  2349. lookupCheckType = lookupCheckType->mBaseType;
  2350. if (lookupCheckType == NULL)
  2351. break;
  2352. }
  2353. }
  2354. }
  2355. if (allowProtected)
  2356. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2357. else
  2358. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2359. }
  2360. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2361. return true;
  2362. }
  2363. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2364. {
  2365. mAttributeState->mUsed = true;
  2366. return true;
  2367. }
  2368. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2369. {
  2370. if (CheckInternalProtection(memberOwner->mTypeDef))
  2371. return true;
  2372. }
  2373. return false;
  2374. }
  2375. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2376. {
  2377. if ((mCompiler->mResolvePassData != NULL) &&
  2378. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2379. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2380. {
  2381. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2382. }
  2383. }
  2384. bool BfModule::PreFail()
  2385. {
  2386. if (!mIgnoreErrors)
  2387. return true;
  2388. SetFail();
  2389. return false;
  2390. }
  2391. void BfModule::SetFail()
  2392. {
  2393. if (mIgnoreErrors)
  2394. {
  2395. if (mAttributeState != NULL)
  2396. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2397. }
  2398. }
  2399. void BfModule::VerifyOnDemandMethods()
  2400. {
  2401. #ifdef _DEBUG
  2402. // if (mParentModule != NULL)
  2403. // {
  2404. // BF_ASSERT(mOnDemandMethodCount == 0);
  2405. // mParentModule->VerifyOnDemandMethods();
  2406. // return;
  2407. // }
  2408. //
  2409. // int onDemandCount = 0;
  2410. // for (auto type : mOwnedTypeInstances)
  2411. // {
  2412. // auto typeInst = type->ToTypeInstance();
  2413. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2414. // {
  2415. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2416. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2417. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2418. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2419. // onDemandCount++;
  2420. // }
  2421. // }
  2422. //
  2423. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2424. #endif
  2425. }
  2426. bool BfModule::IsSkippingExtraResolveChecks()
  2427. {
  2428. if (mIsComptimeModule)
  2429. return false;
  2430. return mCompiler->IsSkippingExtraResolveChecks();
  2431. }
  2432. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2433. {
  2434. BP_ZONE("BfModule::Fail");
  2435. if (mIgnoreErrors)
  2436. {
  2437. mHadIgnoredError = true;
  2438. if (mAttributeState != NULL)
  2439. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2440. return NULL;
  2441. }
  2442. if (!mReportErrors)
  2443. {
  2444. mCompiler->mPassInstance->SilentFail();
  2445. return NULL;
  2446. }
  2447. if (refNode != NULL)
  2448. refNode = BfNodeToNonTemporary(refNode);
  2449. //BF_ASSERT(refNode != NULL);
  2450. if (mIsComptimeModule)
  2451. {
  2452. if ((mCompiler->mCEMachine->mCurContext != NULL) && (mCompiler->mCEMachine->mCurContext->mCurTargetSrc != NULL))
  2453. {
  2454. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors", mCompiler->mCEMachine->mCurContext->mCurTargetSrc);
  2455. if (bfError != NULL)
  2456. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2457. return bfError;
  2458. }
  2459. mHadBuildError = true;
  2460. return NULL;
  2461. }
  2462. if (mCurMethodInstance != NULL)
  2463. mCurMethodInstance->mHasFailed = true;
  2464. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2465. return NULL;
  2466. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2467. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2468. if (!mHadBuildError)
  2469. mHadBuildError = true;
  2470. if (mParentModule != NULL)
  2471. mParentModule->mHadBuildError = true;
  2472. if (mCurTypeInstance != NULL)
  2473. AddFailType(mCurTypeInstance);
  2474. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2475. String errorString = error;
  2476. bool isWhileSpecializing = false;
  2477. bool isWhileSpecializingMethod = false;
  2478. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2479. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2480. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2481. errorString += StrFormat("\n while generating append size calculating method");
  2482. else if (refNode == NULL)
  2483. {
  2484. if (mCurTypeInstance != NULL)
  2485. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2486. else if (mProject != NULL)
  2487. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2488. }
  2489. if (mCurTypeInstance != NULL)
  2490. {
  2491. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2492. {
  2493. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2494. methodInstance->mHasFailed = true;
  2495. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2496. if (isSpecializedMethod)
  2497. {
  2498. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2499. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2500. if (unspecializedMethod == methodInstance)
  2501. {
  2502. // This is a local method inside a generic method
  2503. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2504. }
  2505. else
  2506. {
  2507. if (unspecializedMethod->mHasFailed)
  2508. return false; // At least SOME error has already been reported
  2509. }
  2510. }
  2511. if (isSpecializedMethod)
  2512. {
  2513. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2514. isWhileSpecializing = true;
  2515. isWhileSpecializingMethod = true;
  2516. }
  2517. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2518. {
  2519. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2520. isWhileSpecializing = true;
  2521. isWhileSpecializingMethod = true;
  2522. }
  2523. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2524. {
  2525. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2526. isWhileSpecializing = true;
  2527. }
  2528. return true;
  2529. };
  2530. bool hadMethodInstance = false;
  2531. if (mCurMethodState != NULL)
  2532. {
  2533. auto checkMethodState = mCurMethodState;
  2534. while (checkMethodState != NULL)
  2535. {
  2536. auto methodInstance = checkMethodState->mMethodInstance;
  2537. if (methodInstance == NULL)
  2538. {
  2539. checkMethodState = checkMethodState->mPrevMethodState;
  2540. continue;
  2541. }
  2542. hadMethodInstance = true;
  2543. if (!_CheckMethodInstance(methodInstance))
  2544. return NULL;
  2545. checkMethodState = checkMethodState->mPrevMethodState;
  2546. }
  2547. }
  2548. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2549. {
  2550. if (!_CheckMethodInstance(mCurMethodInstance))
  2551. return NULL;
  2552. }
  2553. }
  2554. // Keep in mind that all method specializations with generic type instances as its method generic params
  2555. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2556. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2557. // those method specializations if that occurs
  2558. if ((isWhileSpecializing) || (deferError))
  2559. {
  2560. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2561. if (bfError != NULL)
  2562. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2563. return bfError;
  2564. }
  2565. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2566. {
  2567. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2568. isWhileSpecializing = true;
  2569. }
  2570. if (!mHadBuildError)
  2571. mHadBuildError = true;
  2572. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2573. {
  2574. BfError* bfError = mCompiler->mPassInstance->Fail("Emitted code had errors", mCurMethodState->mEmitRefNode);
  2575. if (bfError != NULL)
  2576. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2577. return bfError;
  2578. }
  2579. // Check mixins
  2580. {
  2581. auto checkMethodInstance = mCurMethodState;
  2582. while (checkMethodInstance != NULL)
  2583. {
  2584. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2585. if (rootMixinState != NULL)
  2586. {
  2587. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2588. if (bfError != NULL)
  2589. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2590. auto mixinState = checkMethodInstance->mMixinState;
  2591. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2592. {
  2593. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2594. mixinState = mixinState->mPrevMixinState;
  2595. }
  2596. return bfError;
  2597. }
  2598. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2599. }
  2600. }
  2601. BfError* bfError = NULL;
  2602. if (refNode == NULL)
  2603. bfError = mCompiler->mPassInstance->Fail(errorString);
  2604. else
  2605. {
  2606. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2607. }
  2608. if (bfError != NULL)
  2609. {
  2610. bfError->mProject = mProject;
  2611. bfError->mIsPersistent = isPersistent;
  2612. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2613. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2614. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2615. }
  2616. return bfError;
  2617. }
  2618. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2619. {
  2620. if (mHadBuildError)
  2621. return NULL;
  2622. return Fail(error, refNode);
  2623. }
  2624. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2625. {
  2626. if (mIgnoreErrors)
  2627. return NULL;
  2628. if (refNode != NULL)
  2629. refNode = BfNodeToNonTemporary(refNode);
  2630. mHadBuildError = true;
  2631. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2632. if (bfError != NULL)
  2633. bfError->mProject = mProject;
  2634. return bfError;
  2635. }
  2636. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2637. {
  2638. if (mIgnoreErrors || mIgnoreWarnings)
  2639. return NULL;
  2640. if (!mReportErrors)
  2641. {
  2642. mCompiler->mPassInstance->SilentFail();
  2643. return NULL;
  2644. }
  2645. BfAstNode* unwarnNode = refNode;
  2646. //
  2647. {
  2648. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2649. while (parentNodeEntry != NULL)
  2650. {
  2651. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2652. break;
  2653. unwarnNode = parentNodeEntry->mNode;
  2654. parentNodeEntry = parentNodeEntry->mPrev;
  2655. }
  2656. }
  2657. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2658. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2659. {
  2660. return NULL;
  2661. }
  2662. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2663. if (mCurMethodInstance != NULL)
  2664. {
  2665. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2666. return NULL;
  2667. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2668. return NULL; // No ctorCalcAppend warnings
  2669. }
  2670. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2671. return NULL;
  2672. if (refNode != NULL)
  2673. refNode = BfNodeToNonTemporary(refNode);
  2674. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2675. {
  2676. // We used to bubble up warnings into the mixin injection site, BUT
  2677. // we are now assuming any relevant warnings will be given at the declaration site
  2678. return NULL;
  2679. }
  2680. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2681. {
  2682. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2683. if (bfError != NULL)
  2684. mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2685. return bfError;
  2686. }
  2687. BfError* bfError;
  2688. if (refNode != NULL)
  2689. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2690. else
  2691. bfError = mCompiler->mPassInstance->Warn(warningNum, warning);
  2692. if (bfError != NULL)
  2693. {
  2694. bfError->mProject = mProject;
  2695. AddFailType(mCurTypeInstance);
  2696. mHadBuildWarning = true;
  2697. bfError->mIsPersistent = isPersistent;
  2698. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2699. {
  2700. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2701. if (parser != NULL)
  2702. {
  2703. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2704. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2705. if (warningNum != 0)
  2706. {
  2707. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2708. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2709. }
  2710. }
  2711. }
  2712. }
  2713. return bfError;
  2714. }
  2715. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2716. {
  2717. auto _AddDeclarationMoreInfo = [&]()
  2718. {
  2719. if (methodInstance != NULL)
  2720. {
  2721. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2722. mCompiler->mPassInstance->MoreInfo(
  2723. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2724. methodInstance->mMethodDef->GetRefNode());
  2725. }
  2726. else
  2727. {
  2728. mCompiler->mPassInstance->MoreInfo(
  2729. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2730. typeInstance->mTypeDef->GetRefNode());
  2731. }
  2732. };
  2733. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2734. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2735. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2736. {
  2737. String err;
  2738. if (methodInstance != NULL)
  2739. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2740. else
  2741. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2742. bool isError = false;
  2743. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2744. if (constant->mTypeCode == BfTypeCode_Boolean)
  2745. {
  2746. isError = constant->mBool;
  2747. }
  2748. else if (customAttribute->mCtorArgs.size() >= 2)
  2749. {
  2750. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2751. if (str != NULL)
  2752. {
  2753. err += ":\n '";
  2754. err += *str;
  2755. err += "'";
  2756. }
  2757. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2758. isError = constant->mBool;
  2759. }
  2760. BfError* error = NULL;
  2761. if (isError)
  2762. error = Fail(err, targetSrc);
  2763. else
  2764. error = Warn(0, err, targetSrc);
  2765. if (error != NULL)
  2766. _AddDeclarationMoreInfo();
  2767. }
  2768. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2769. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2770. {
  2771. String err;
  2772. if (methodInstance != NULL)
  2773. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2774. else
  2775. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2776. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2777. if (str != NULL)
  2778. err += *str;
  2779. err += "'";
  2780. if (Fail(err, targetSrc) != NULL)
  2781. _AddDeclarationMoreInfo();
  2782. }
  2783. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2784. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2785. {
  2786. String err;
  2787. if (methodInstance != NULL)
  2788. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2789. else
  2790. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2791. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2792. if (str != NULL)
  2793. err += *str;
  2794. err += "'";
  2795. if (Warn(0, err, targetSrc) != NULL)
  2796. _AddDeclarationMoreInfo();
  2797. }
  2798. }
  2799. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2800. {
  2801. if (mBfIRBuilder->mOpFailed)
  2802. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2803. }
  2804. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2805. {
  2806. static bool sHadFatalError = false;
  2807. static bool sHadReentrancy = false;
  2808. if (sHadFatalError)
  2809. {
  2810. return;
  2811. sHadReentrancy = true;
  2812. }
  2813. sHadFatalError = true;
  2814. String fullError = error;
  2815. if (file != NULL)
  2816. fullError += StrFormat(" at %s:%d", file, line);
  2817. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2818. if (mCurTypeInstance != NULL)
  2819. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2820. if (mCurMethodInstance != NULL)
  2821. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2822. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2823. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2824. if (sHadReentrancy)
  2825. fullError += "\nError had reentrancy";
  2826. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2827. }
  2828. void BfModule::NotImpl(BfAstNode* astNode)
  2829. {
  2830. Fail("INTERNAL ERROR: Not implemented", astNode);
  2831. }
  2832. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  2833. {
  2834. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2835. if (!allowPrivate)
  2836. allowPrivate |= memberType->IsInterface();
  2837. bool allowProtected = allowPrivate;
  2838. //TODO: We had this commented out, but this makes accessing protected properties fail
  2839. if (mCurTypeInstance != NULL)
  2840. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2841. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  2842. {
  2843. return false;
  2844. }
  2845. return true;
  2846. }
  2847. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2848. {
  2849. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2850. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2851. auto memberTypeInstance = memberType->ToTypeInstance();
  2852. if (memberTypeInstance == NULL)
  2853. {
  2854. auto underlyingType = memberType->GetUnderlyingType();
  2855. if (underlyingType != NULL)
  2856. return CheckDefineMemberProtection(protection, underlyingType);
  2857. return true;
  2858. }
  2859. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2860. return false;
  2861. if (memberTypeInstance->IsGenericTypeInstance())
  2862. {
  2863. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2864. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  2865. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2866. {
  2867. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2868. return false;
  2869. }
  2870. }
  2871. return true;
  2872. }
  2873. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags)
  2874. {
  2875. if (usedType == userType)
  2876. return;
  2877. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2878. {
  2879. if (userType->IsMethodRef())
  2880. {
  2881. // We cannot short-circuit dependencies because of method group ref counting
  2882. }
  2883. else
  2884. return;
  2885. }
  2886. if (usedType->IsSpecializedByAutoCompleteMethod())
  2887. return;
  2888. // if (usedType->IsBoxed())
  2889. // {
  2890. // NOP;
  2891. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  2892. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  2893. // {
  2894. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  2895. // }
  2896. // }
  2897. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  2898. // BfType* origUsedType = usedType;
  2899. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  2900. // if (isDataAccess)
  2901. // {
  2902. // while (true)
  2903. // {
  2904. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  2905. // usedType = usedType->GetUnderlyingType();
  2906. // else if (usedType->IsArray())
  2907. // {
  2908. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  2909. // }
  2910. // else
  2911. // break;
  2912. // }
  2913. // }
  2914. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  2915. {
  2916. bool addType = true;
  2917. auto checkType = usedType;
  2918. PopulateType(checkType, BfPopulateType_Data);
  2919. if (checkType->IsValuelessType())
  2920. addType = false;
  2921. else if (checkType->IsPrimitiveType())
  2922. addType = false;
  2923. else
  2924. {
  2925. auto checkTypeInst = checkType->ToTypeInstance();
  2926. if (checkTypeInst == NULL)
  2927. {
  2928. addType = false;
  2929. }
  2930. else
  2931. {
  2932. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2933. addType = false;
  2934. }
  2935. }
  2936. if (addType)
  2937. {
  2938. auto checkTypeInst = checkType->ToTypeInstance();
  2939. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2940. BF_ASSERT(hotTypeVersion != NULL);
  2941. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2942. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2943. (checkType->IsComposite()))
  2944. isAllocation = true;
  2945. if (isAllocation)
  2946. {
  2947. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2948. }
  2949. else
  2950. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2951. }
  2952. }
  2953. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2954. {
  2955. auto usingModule = userType->GetModule();
  2956. BfModule* usedModule;
  2957. if (usedType->IsFunction())
  2958. {
  2959. auto typeInst = usedType->ToTypeInstance();
  2960. if (typeInst->mBaseType == NULL)
  2961. PopulateType(typeInst);
  2962. usedModule = typeInst->mBaseType->GetModule();
  2963. }
  2964. else
  2965. usedModule = usedType->GetModule();
  2966. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2967. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2968. {
  2969. usingModule->mModuleRefs.Add(usedModule);
  2970. }
  2971. }
  2972. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2973. {
  2974. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2975. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2976. if (genericArg == usedType)
  2977. return;
  2978. }
  2979. auto depFlag = flags;
  2980. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  2981. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef; // Will cause a rebuild but not an outright deletion of the type
  2982. auto underlyingType = usedType->GetUnderlyingType();
  2983. if (underlyingType != NULL)
  2984. AddDependency(underlyingType, userType, depFlag);
  2985. BfDependedType* checkDType = usedType->ToDependedType();
  2986. if (checkDType == NULL)
  2987. return;
  2988. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2989. mContext->MarkAsReferenced(checkDType);
  2990. #ifdef _DEBUG
  2991. // If a MethodRef depends ON US, that means it's a local method that we own
  2992. if (userType->IsMethodRef())
  2993. {
  2994. auto methodRefType = (BfMethodRefType*)userType;
  2995. BF_ASSERT(methodRefType->mOwner == checkDType);
  2996. }
  2997. #endif
  2998. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  2999. return;
  3000. if (checkDType->IsGenericTypeInstance())
  3001. {
  3002. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3003. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3004. {
  3005. AddDependency(genericArg, userType, depFlag);
  3006. }
  3007. }
  3008. if (checkDType->IsTuple())
  3009. {
  3010. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3011. {
  3012. if (field.mDataIdx != -1)
  3013. AddDependency(field.mResolvedType, userType, depFlag);
  3014. }
  3015. }
  3016. }
  3017. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3018. {
  3019. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3020. {
  3021. if (methodInstance->mHotMethod == NULL)
  3022. CheckHotMethod(methodInstance, "");
  3023. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3024. if (devirtualized)
  3025. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3026. else
  3027. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3028. }
  3029. }
  3030. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3031. {
  3032. auto checkTypeInst = typeInst;
  3033. while (checkTypeInst != NULL)
  3034. {
  3035. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  3036. return true;
  3037. checkTypeInst = checkTypeInst->mBaseType;
  3038. }
  3039. return false;
  3040. }
  3041. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3042. {
  3043. if (mContext->mCurTypeState == NULL)
  3044. return;
  3045. BP_ZONE("PopulateGlobalContainersList");
  3046. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3047. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3048. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3049. if (userTypeDef == NULL)
  3050. userTypeDef = mCurTypeInstance->mTypeDef;
  3051. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3052. {
  3053. mContext->mCurTypeState->mGlobalContainers.Clear();
  3054. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3055. {
  3056. BfAtomComposite findStr;
  3057. if (namespaceIdx != -1)
  3058. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3059. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3060. while (typeDefItr)
  3061. {
  3062. auto typeDef = *typeDefItr;
  3063. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3064. {
  3065. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3066. {
  3067. BfGlobalContainerEntry globalEntry;
  3068. globalEntry.mTypeDef = typeDef;
  3069. globalEntry.mTypeInst = NULL;
  3070. typeDef->PopulateMemberSets();
  3071. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3072. }
  3073. }
  3074. else if (!typeDef->mIsPartial)
  3075. {
  3076. //break;
  3077. }
  3078. typeDefItr.MoveToNextHashMatch();
  3079. }
  3080. }
  3081. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3082. }
  3083. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3084. // reifing types
  3085. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3086. {
  3087. if (globalEntry.mTypeInst == NULL)
  3088. {
  3089. bool include = false;
  3090. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3091. include = true;
  3092. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3093. {
  3094. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3095. include = true;
  3096. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3097. include = true;
  3098. }
  3099. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3100. {
  3101. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3102. include = true;
  3103. }
  3104. if (include)
  3105. {
  3106. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3107. if (type != NULL)
  3108. globalEntry.mTypeInst = type->ToTypeInstance();
  3109. }
  3110. }
  3111. }
  3112. }
  3113. BfStaticSearch* BfModule::GetStaticSearch()
  3114. {
  3115. auto activeTypeDef = GetActiveTypeDef();
  3116. BfStaticSearch* staticSearch = NULL;
  3117. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3118. return staticSearch;
  3119. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3120. return staticSearch;
  3121. return NULL;
  3122. }
  3123. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3124. {
  3125. auto activeTypeDef = GetActiveTypeDef();
  3126. BfInternalAccessSet* internalAccessSet = NULL;
  3127. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3128. return internalAccessSet;
  3129. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3130. return internalAccessSet;
  3131. return NULL;
  3132. }
  3133. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3134. {
  3135. auto internalAccessSet = GetInternalAccessSet();
  3136. if (internalAccessSet == NULL)
  3137. return false;
  3138. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3139. {
  3140. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3141. return true;
  3142. }
  3143. for (auto internalType : internalAccessSet->mTypes)
  3144. {
  3145. auto checkTypeDef = usingTypeDef;
  3146. while (checkTypeDef != NULL)
  3147. {
  3148. if (checkTypeDef == internalType->mTypeDef)
  3149. return true;
  3150. checkTypeDef = checkTypeDef->mOuterType;
  3151. }
  3152. }
  3153. return false;
  3154. }
  3155. void PrintUsers(llvm::MDNode* md);
  3156. BfModuleOptions BfModule::GetModuleOptions()
  3157. {
  3158. if (mIsScratchModule)
  3159. return BfModuleOptions();
  3160. if (mModuleOptions != NULL)
  3161. return *mModuleOptions;
  3162. BfModuleOptions moduleOptions;
  3163. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3164. if (mProject != NULL)
  3165. {
  3166. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3167. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3168. }
  3169. auto headModule = this;
  3170. while (headModule->mParentModule != NULL)
  3171. headModule = headModule->mParentModule;
  3172. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3173. if (headModule->mOwnedTypeInstances.size() > 0)
  3174. {
  3175. auto typeInst = headModule->mOwnedTypeInstances[0];
  3176. if (typeInst->mTypeOptionsIdx == -2)
  3177. PopulateType(typeInst);
  3178. if (typeInst->mTypeOptionsIdx != -1)
  3179. {
  3180. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3181. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3182. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3183. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3184. }
  3185. }
  3186. return moduleOptions;
  3187. }
  3188. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3189. {
  3190. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3191. return BfCheckedKind_Unchecked;
  3192. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3193. auto typeOptions = GetTypeOptions();
  3194. if (typeOptions != NULL)
  3195. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3196. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3197. }
  3198. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3199. {
  3200. BF_ASSERT(typeInstance != NULL);
  3201. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3202. return;
  3203. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3204. mContext->mFailTypes.Add(typeInstance);
  3205. }
  3206. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3207. {
  3208. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3209. return;
  3210. mCompiler->mHasQueuedTypeRebuilds = true;
  3211. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3212. AddFailType(typeInstance);
  3213. }
  3214. void BfModule::CheckAddFailType()
  3215. {
  3216. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3217. // but we still need to add the owning type to the FailTypes list
  3218. //.. OLD:
  3219. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3220. /*if (mCurTypeInstance->mModule != this)
  3221. return;*/
  3222. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3223. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3224. // being recompiled. This forces types with warnings to be recompiled.
  3225. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3226. // constantly warning-aware
  3227. if ((mHadBuildError) ||
  3228. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3229. {
  3230. //mContext->mFailTypes.Add(mCurTypeInstance);
  3231. }
  3232. }
  3233. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3234. {
  3235. if (!mCompiler->IsHotCompile())
  3236. return;
  3237. typeInst->mDirty = true;
  3238. for (auto& dep : typeInst->mDependencyMap)
  3239. {
  3240. auto depType = dep.mKey;
  3241. auto depFlags = dep.mValue.mFlags;
  3242. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3243. {
  3244. MarkDerivedDirty(depType->ToTypeInstance());
  3245. }
  3246. }
  3247. }
  3248. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3249. {
  3250. auto fieldType = fieldInstance->GetResolvedType();
  3251. auto field = fieldInstance->GetFieldDef();
  3252. if (fieldType->IsVar())
  3253. return;
  3254. BfIRValue initValue;
  3255. if (field->mIsConst)
  3256. {
  3257. if (fieldType->IsPointer())
  3258. fieldType = fieldType->GetUnderlyingType();
  3259. }
  3260. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3261. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3262. storageKind = BfIRStorageKind_Export;
  3263. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3264. storageKind = BfIRStorageKind_Import;
  3265. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3266. initValue = GetDefaultValue(fieldType);
  3267. if (fieldInstance->mOwner->IsUnspecializedType())
  3268. {
  3269. // Placeholder
  3270. auto ptrVal = CreatePointerType(fieldType);
  3271. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3272. }
  3273. else
  3274. {
  3275. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3276. StringT<128> staticVarName;
  3277. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3278. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3279. {
  3280. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3281. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  3282. false,
  3283. BfIRLinkageType_External,
  3284. initValue,
  3285. staticVarName,
  3286. isThreadLocal);
  3287. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3288. if (storageKind != BfIRStorageKind_Normal)
  3289. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3290. BF_ASSERT(globalVar);
  3291. mStaticFieldRefs[fieldInstance] = globalVar;
  3292. }
  3293. }
  3294. }
  3295. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3296. {
  3297. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3298. BfType* fieldType = NULL;
  3299. if (fieldInstance != NULL)
  3300. {
  3301. fieldType = fieldInstance->GetResolvedType();
  3302. if (fieldType == NULL)
  3303. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3304. }
  3305. else
  3306. {
  3307. BF_ASSERT(mCompiler->IsAutocomplete());
  3308. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3309. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3310. {
  3311. fieldType = typeInstance;
  3312. }
  3313. else
  3314. {
  3315. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3316. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3317. if (isLet || isVar)
  3318. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3319. else
  3320. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3321. if (fieldType == NULL)
  3322. fieldType = mContext->mBfObjectType;
  3323. }
  3324. }
  3325. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3326. return;
  3327. if (mContext->mFieldResolveReentrys.size() > 1)
  3328. {
  3329. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3330. {
  3331. String failStr = "Circular data reference detected between the following fields:";
  3332. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3333. {
  3334. if (i > 1)
  3335. failStr += ",";
  3336. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3337. }
  3338. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3339. if (err)
  3340. err->mIsPersistent = true;
  3341. return;
  3342. }
  3343. }
  3344. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3345. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3346. if (fieldInstance == NULL)
  3347. popTypeResolveReentry.Pop();
  3348. auto typeDef = typeInstance->mTypeDef;
  3349. BfIRValue constValue;
  3350. if (fieldDef->mIsExtern)
  3351. {
  3352. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3353. {
  3354. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3355. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3356. }
  3357. if (fieldDef->mInitializer != NULL)
  3358. {
  3359. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3360. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3361. }
  3362. }
  3363. else if (fieldDef->mInitializer == NULL)
  3364. {
  3365. if (fieldDef->IsEnumCaseEntry())
  3366. {
  3367. if (typeInstance->IsTypedPrimitive())
  3368. {
  3369. BfFieldInstance* prevFieldInstance = NULL;
  3370. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3371. {
  3372. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3373. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3374. {
  3375. prevFieldInstance = checkFieldInst;
  3376. break;
  3377. }
  3378. }
  3379. if (prevFieldInstance == NULL)
  3380. constValue = GetConstValue(0, typeInstance);
  3381. else
  3382. {
  3383. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3384. if (prevFieldInstance->mConstIdx == -1)
  3385. {
  3386. if (!mCompiler->IsAutocomplete())
  3387. AssertErrorState();
  3388. constValue = GetConstValue(0, typeInstance);
  3389. }
  3390. else
  3391. {
  3392. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3393. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3394. }
  3395. }
  3396. }
  3397. }
  3398. else
  3399. {
  3400. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3401. }
  3402. }
  3403. else if (mBfIRBuilder != NULL)
  3404. {
  3405. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3406. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3407. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3408. BfMethodState methodState;
  3409. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3410. methodState.mTempKind = BfMethodState::TempKind_Static;
  3411. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3412. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3413. {
  3414. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3415. if (!initValue)
  3416. {
  3417. AssertErrorState();
  3418. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3419. }
  3420. if (fieldInstance != NULL)
  3421. {
  3422. if (fieldType->IsUndefSizedArray())
  3423. {
  3424. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3425. {
  3426. fieldInstance->mResolvedType = initValue.mType;
  3427. }
  3428. }
  3429. else
  3430. fieldInstance->mResolvedType = initValue.mType;
  3431. }
  3432. constValue = initValue.mValue;
  3433. }
  3434. else
  3435. {
  3436. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3437. constValue = uncastedInitValue.mValue;
  3438. }
  3439. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3440. {
  3441. // Illegal
  3442. constValue = BfIRValue();
  3443. }
  3444. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3445. }
  3446. if (fieldInstance != NULL)
  3447. {
  3448. fieldType = fieldInstance->GetResolvedType();
  3449. if ((fieldType == NULL) || (fieldType->IsVar()))
  3450. {
  3451. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3452. AssertErrorState();
  3453. // Default const type is 'int'
  3454. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3455. if (fieldInstance != NULL)
  3456. {
  3457. fieldInstance->mResolvedType = initValue.mType;
  3458. }
  3459. constValue = initValue.mValue;
  3460. }
  3461. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3462. {
  3463. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3464. CurrentAddToConstHolder(constValue);
  3465. fieldInstance->mConstIdx = constValue.mId;
  3466. }
  3467. }
  3468. }
  3469. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3470. {
  3471. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3472. auto fieldType = fieldInstance->GetResolvedType();
  3473. if ((field->mIsConst) && (!isDeclType))
  3474. {
  3475. ResolveConstField(typeInstance, fieldInstance, field);
  3476. return fieldInstance->GetResolvedType();
  3477. }
  3478. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3479. if (!fieldInstance->mIsInferredType)
  3480. return fieldType;
  3481. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3482. return fieldType;
  3483. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3484. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3485. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  3486. auto typeDef = typeInstance->mTypeDef;
  3487. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3488. {
  3489. AssertErrorState();
  3490. return fieldType;
  3491. }
  3492. bool hadInferenceCycle = false;
  3493. if (mContext->mFieldResolveReentrys.size() > 1)
  3494. {
  3495. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3496. {
  3497. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3498. {
  3499. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3500. auto fieldDef = fieldInst->GetFieldDef();
  3501. auto fieldOwner = fieldInst->mOwner;
  3502. auto fieldModule = fieldOwner->mModule;
  3503. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3504. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3505. }
  3506. return fieldType;
  3507. }
  3508. }
  3509. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3510. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3511. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3512. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3513. if ((field->mInitializer == NULL) && (!isDeclType))
  3514. {
  3515. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3516. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3517. return fieldType;
  3518. }
  3519. BfType* resolvedType = NULL;
  3520. if (!hadInferenceCycle)
  3521. {
  3522. BfTypeState typeState;
  3523. typeState.mPrevState = mContext->mCurTypeState;
  3524. typeState.mTypeInstance = typeInstance;
  3525. typeState.mCurFieldDef = field;
  3526. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3527. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3528. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3529. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3530. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3531. BfMethodState methodState;
  3532. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3533. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3534. if (!staticOnly)
  3535. {
  3536. //BfLocalVariable localVar;
  3537. //methodState.mLocals.push_back(localVar);
  3538. }
  3539. if (isDeclType)
  3540. {
  3541. auto fieldDef = fieldInstance->GetFieldDef();
  3542. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3543. }
  3544. else
  3545. {
  3546. BfTypedValue valueFromExpr;
  3547. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3548. FixIntUnknown(valueFromExpr);
  3549. if (fieldType->IsUndefSizedArray())
  3550. {
  3551. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3552. resolvedType = valueFromExpr.mType;
  3553. }
  3554. else
  3555. resolvedType = valueFromExpr.mType;
  3556. }
  3557. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3558. }
  3559. if (resolvedType == NULL)
  3560. return fieldType;
  3561. fieldInstance->SetResolvedType(resolvedType);
  3562. if (field->mIsStatic)
  3563. {
  3564. }
  3565. else if (fieldInstance->mDataIdx >= 0)
  3566. {
  3567. }
  3568. else
  3569. {
  3570. BF_ASSERT(typeInstance->IsIncomplete());
  3571. }
  3572. return resolvedType;
  3573. }
  3574. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3575. {
  3576. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3577. auto fieldType = fieldInstance->GetResolvedType();
  3578. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3579. {
  3580. int fieldIdx = 0;
  3581. int fieldCount = 0;
  3582. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3583. fieldIdx--;
  3584. int count = fieldCount;
  3585. if (fieldIdx == -1)
  3586. count = 1;
  3587. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3588. auto thisVariable = GetThisVariable();
  3589. if (thisVariable != NULL)
  3590. {
  3591. for (int i = 0; i < count; i++)
  3592. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3593. }
  3594. }
  3595. }
  3596. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3597. {
  3598. if (fieldInstance->mCustomAttributes == NULL)
  3599. return false;
  3600. auto fieldDef = fieldInstance->GetFieldDef();
  3601. if (!fieldDef->mIsStatic)
  3602. return false;
  3603. bool isThreadLocal = false;
  3604. if (fieldInstance->mCustomAttributes != NULL)
  3605. {
  3606. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3607. {
  3608. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3609. return true;
  3610. }
  3611. }
  3612. return false;
  3613. }
  3614. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3615. {
  3616. if (fieldDef == NULL)
  3617. fieldDef = fieldInstance->GetFieldDef();
  3618. if (fieldType == NULL)
  3619. fieldType = fieldInstance->GetResolvedType();
  3620. if (initializer == NULL)
  3621. {
  3622. if (fieldDef == NULL)
  3623. return BfTypedValue();
  3624. initializer = fieldDef->mInitializer;
  3625. }
  3626. BfTypedValue staticVarRef;
  3627. BfTypedValue result;
  3628. if (initializer == NULL)
  3629. {
  3630. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3631. }
  3632. else
  3633. {
  3634. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3635. {
  3636. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3637. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3638. }
  3639. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3640. {
  3641. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3642. BfConstResolver constResolver(this);
  3643. constResolver.Resolve(initializer);
  3644. return GetDefaultTypedValue(fieldType);
  3645. }
  3646. else if (fieldDef->mIsConst)
  3647. {
  3648. int ceExecuteId = -1;
  3649. if (mCompiler->mCEMachine != NULL)
  3650. ceExecuteId = mCompiler->mCEMachine->mExecuteId;
  3651. BfTypeState typeState;
  3652. typeState.mTypeInstance = mCurTypeInstance;
  3653. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3654. typeState.mCurFieldDef = fieldDef;
  3655. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3656. BfConstResolver constResolver(this);
  3657. if (fieldType->IsVar())
  3658. return constResolver.Resolve(initializer);
  3659. else
  3660. {
  3661. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3662. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3663. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3664. {
  3665. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3666. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3667. resolveFlags = BfConstResolveFlag_NoCast;
  3668. }
  3669. UpdateSrcPos(initializer);
  3670. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  3671. if ((mCompiler->mCEMachine != NULL) && (fieldInstance != NULL))
  3672. {
  3673. if (mCompiler->mCEMachine->mExecuteId != ceExecuteId)
  3674. fieldInstance->mHadConstEval = true;
  3675. }
  3676. return result;
  3677. }
  3678. }
  3679. BfExprEvaluator exprEvaluator(this);
  3680. if (doStore)
  3681. {
  3682. staticVarRef = ReferenceStaticField(fieldInstance);
  3683. exprEvaluator.mReceivingValue = &staticVarRef;
  3684. }
  3685. if (fieldType->IsVar())
  3686. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3687. else
  3688. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3689. if (doStore)
  3690. {
  3691. if (exprEvaluator.mReceivingValue == NULL)
  3692. doStore = false; // Already stored
  3693. }
  3694. }
  3695. if (fieldInstance != NULL)
  3696. MarkFieldInitialized(fieldInstance);
  3697. if ((doStore) && (result))
  3698. {
  3699. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  3700. {
  3701. AssertErrorState();
  3702. }
  3703. else
  3704. {
  3705. result = LoadValue(result);
  3706. if (!result.mType->IsValuelessType())
  3707. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3708. }
  3709. }
  3710. return result;
  3711. }
  3712. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3713. {
  3714. }
  3715. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3716. {
  3717. PopulateType(classType);
  3718. if (isInterfacePass)
  3719. {
  3720. for (auto ifaceInst : classType->mInterfaces)
  3721. {
  3722. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3723. continue;
  3724. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3725. continue;
  3726. if (ifaceInst.mDeclaringType->IsExtension())
  3727. {
  3728. bool needsExCheck = false;
  3729. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3730. {
  3731. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  3732. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  3733. {
  3734. exChecks->push_back(ifaceInst.mInterfaceType);
  3735. continue;
  3736. }
  3737. else
  3738. {
  3739. // We can only do an 'exCheck' if we're actually going to slot this interface
  3740. }
  3741. }
  3742. }
  3743. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3744. }
  3745. }
  3746. else
  3747. {
  3748. outVals->push_back(classType->mTypeId);
  3749. }
  3750. if (classType->mBaseType != NULL)
  3751. {
  3752. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3753. }
  3754. }
  3755. void BfModule::CreateDynamicCastMethod()
  3756. {
  3757. auto objType = mContext->mBfObjectType;
  3758. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3759. {
  3760. // The main reason to punt on this method for ResolveOnly is because types can be created
  3761. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3762. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3763. // remove this punt when we recycle typeId's
  3764. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3765. mCurMethodState->mHadReturn = true;
  3766. return;
  3767. }
  3768. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3769. auto func = mCurMethodState->mIRFunction;
  3770. auto thisValue = mBfIRBuilder->GetArgument(0);
  3771. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3772. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3773. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3774. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3775. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3776. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3777. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3778. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3779. SizedArray<int, 8> typeMatches;
  3780. SizedArray<BfTypeInstance*, 8> exChecks;
  3781. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3782. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3783. {
  3784. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3785. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3786. BfTypeVector genericArgs;
  3787. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3788. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3789. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3790. typeMatches.push_back(unboundType->mTypeId);
  3791. }
  3792. if (mCurTypeInstance->IsBoxed())
  3793. {
  3794. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3795. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  3796. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3797. if (innerType->IsTypedPrimitive())
  3798. {
  3799. auto underlyingType = innerType->GetUnderlyingType();
  3800. typeMatches.push_back(underlyingType->mTypeId);
  3801. }
  3802. auto innerTypeInst = innerType->ToTypeInstance();
  3803. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3804. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3805. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3806. {
  3807. PopulateType(innerTypeInst);
  3808. //TODO: What case was this supposed to handle?
  3809. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3810. }
  3811. }
  3812. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3813. BfIRValue vDataPtr;
  3814. if (!exChecks.empty())
  3815. {
  3816. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3817. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3818. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3819. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3820. }
  3821. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3822. for (auto typeMatch : typeMatches)
  3823. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3824. Array<BfIRValue> incomingFalses;
  3825. for (auto ifaceTypeInst : exChecks)
  3826. {
  3827. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3828. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3829. mBfIRBuilder->SetInsertPoint(nextBB);
  3830. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3831. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3832. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3833. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3834. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3835. incomingFalses.push_back(nextBB);
  3836. }
  3837. mBfIRBuilder->AddBlock(trueBB);
  3838. mBfIRBuilder->SetInsertPoint(trueBB);
  3839. mBfIRBuilder->CreateBr(exitBB);
  3840. mBfIRBuilder->AddBlock(exitBB);
  3841. mBfIRBuilder->SetInsertPoint(exitBB);
  3842. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3843. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3844. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3845. for (auto incomingFalseBlock : incomingFalses)
  3846. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3847. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3848. mBfIRBuilder->CreateRet(phi);
  3849. mCurMethodState->mHadReturn = true;
  3850. }
  3851. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  3852. {
  3853. BfExprEvaluator exprEvaluator(this);
  3854. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3855. auto typeInst = rightValue.mType->ToTypeInstance();
  3856. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  3857. BfTypedValue result = exprEvaluator.GetResult();
  3858. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  3859. {
  3860. // Fail?
  3861. }
  3862. if ((result) && (!result.mType->IsVar()))
  3863. {
  3864. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3865. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3866. mBfIRBuilder->AddBlock(nextBB);
  3867. mBfIRBuilder->SetInsertPoint(nextBB);
  3868. }
  3869. }
  3870. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3871. {
  3872. if (mCurMethodInstance->mHasFailed)
  3873. return;
  3874. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  3875. return;
  3876. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3877. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3878. SizedArray<BfIRType, 4> paramTypes;
  3879. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3880. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3881. mBfIRBuilder->SetActiveFunction(func);
  3882. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3883. mBfIRBuilder->SetInsertPoint(entryBlock);
  3884. BfMethodState methodState;
  3885. methodState.mIRHeadBlock = entryBlock;
  3886. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3887. SizedArray<BfIRValue, 8> args;
  3888. BfExprEvaluator exprEvaluator(this);
  3889. if (mCurMethodInstance->GetStructRetIdx() == 0)
  3890. {
  3891. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3892. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3893. }
  3894. if (mCurMethodInstance->HasThis())
  3895. {
  3896. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  3897. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3898. }
  3899. if (mCurMethodInstance->GetStructRetIdx() == 1)
  3900. {
  3901. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3902. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3903. }
  3904. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3905. {
  3906. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3907. if (paramType->IsValuelessType())
  3908. continue;
  3909. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  3910. }
  3911. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3912. mBfIRBuilder->CreateRetVoid();
  3913. }
  3914. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  3915. {
  3916. if (mCurMethodInstance->mIsUnspecialized)
  3917. return;
  3918. if (mBfIRBuilder->mIgnoreWrites)
  3919. return;
  3920. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3921. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3922. bool isValid = true;
  3923. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3924. if (compareType->IsValuelessType())
  3925. {
  3926. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3927. return;
  3928. }
  3929. if (compareType->IsTypedPrimitive())
  3930. {
  3931. BfExprEvaluator exprEvaluator(this);
  3932. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  3933. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  3934. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  3935. mBfIRBuilder->CreateRet(cmpResult);
  3936. return;
  3937. }
  3938. auto compareDType = compareType->ToDependedType();
  3939. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3940. if (compareTypeInst != NULL)
  3941. {
  3942. if (compareType->IsPrimitiveType())
  3943. compareTypeInst = GetWrappedStructType(compareType);
  3944. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3945. {
  3946. isValid = false;
  3947. }
  3948. mBfIRBuilder->PopulateType(compareTypeInst);
  3949. }
  3950. if (!isValid)
  3951. {
  3952. ClearLifetimeEnds();
  3953. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3954. return;
  3955. }
  3956. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3957. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3958. if (refNode == NULL)
  3959. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3960. UpdateSrcPos(refNode);
  3961. SetIllegalSrcPos();
  3962. auto resultVal = CreateAlloca(boolType);
  3963. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3964. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3965. if (compareType->IsValuelessType())
  3966. {
  3967. // Always equal, nothing to do
  3968. }
  3969. else if (compareType->IsSizedArray())
  3970. {
  3971. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3972. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  3973. {
  3974. BfTypedValue result;
  3975. // if (sizedArrayType->mElementType->IsSizeAligned())
  3976. // {
  3977. // auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  3978. // auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  3979. // auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  3980. // result = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3981. // }
  3982. // else
  3983. // {
  3984. // auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  3985. // result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3986. // }
  3987. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  3988. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3989. if (!result.mType->IsValueType())
  3990. result = LoadValue(result);
  3991. return result;
  3992. };
  3993. if (sizedArrayType->mElementCount > 6)
  3994. {
  3995. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3996. auto itr = CreateAlloca(intPtrType);
  3997. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3998. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3999. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4000. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4001. mBfIRBuilder->CreateBr(loopBB);
  4002. mBfIRBuilder->SetInsertPoint(loopBB);
  4003. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4004. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4005. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4006. mBfIRBuilder->SetInsertPoint(bodyBB);
  4007. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4008. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4009. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4010. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4011. mBfIRBuilder->CreateStore(incValue, itr);
  4012. mBfIRBuilder->CreateBr(loopBB);
  4013. mBfIRBuilder->SetInsertPoint(doneBB);
  4014. }
  4015. else
  4016. {
  4017. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4018. {
  4019. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4020. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4021. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4022. }
  4023. }
  4024. }
  4025. else if (compareType->IsMethodRef())
  4026. {
  4027. auto methodRefType = (BfMethodRefType*)compareType;
  4028. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4029. BfExprEvaluator exprEvaluator(this);
  4030. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4031. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4032. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4033. // values for the same method reference -- they will always refer back to the same local variables.
  4034. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4035. if (dataIdx != -1)
  4036. {
  4037. bool failed = false;
  4038. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4039. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4040. BF_ASSERT(!failed);
  4041. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4042. }
  4043. }
  4044. else if (compareTypeInst->IsEnum())
  4045. {
  4046. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4047. BfExprEvaluator exprEvaluator(this);
  4048. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4049. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4050. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4051. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4052. leftValue = LoadValue(leftValue);
  4053. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4054. rightValue = LoadValue(rightValue);
  4055. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4056. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4057. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4058. int enumCount = 0;
  4059. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4060. {
  4061. BfFieldInstance* fieldInstance = &fieldRef;
  4062. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4063. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4064. {
  4065. enumCount = -fieldInstance->mDataIdx;
  4066. }
  4067. }
  4068. if (enumCount > 0)
  4069. {
  4070. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4071. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4072. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4073. {
  4074. BfFieldInstance* fieldInstance = &fieldRef;
  4075. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4076. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4077. {
  4078. int enumIdx = -fieldInstance->mDataIdx - 1;
  4079. if (fieldInstance->mResolvedType->mSize == 0)
  4080. {
  4081. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4082. }
  4083. else
  4084. {
  4085. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4086. mBfIRBuilder->SetInsertPoint(caseBlock);
  4087. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4088. BfTypedValue leftTuple;
  4089. BfTypedValue rightTuple;
  4090. if (leftPayload.IsAddr())
  4091. {
  4092. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4093. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4094. }
  4095. else
  4096. {
  4097. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4098. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4099. }
  4100. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4101. mBfIRBuilder->CreateBr(matchedBlock);
  4102. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4103. }
  4104. }
  4105. }
  4106. mBfIRBuilder->AddBlock(matchedBlock);
  4107. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4108. }
  4109. }
  4110. else if (compareTypeInst->IsUnion())
  4111. {
  4112. auto innerType = compareTypeInst->GetUnionInnerType();
  4113. if (!innerType->IsValuelessType())
  4114. {
  4115. BfExprEvaluator exprEvaluator(this);
  4116. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4117. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4118. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4119. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4120. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4121. }
  4122. }
  4123. else
  4124. {
  4125. BfExprEvaluator exprEvaluator(this);
  4126. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4127. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4128. bool hadComparison = false;
  4129. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4130. {
  4131. BfFieldInstance* fieldInstance = &fieldRef;
  4132. if (fieldInstance->mDataOffset == -1)
  4133. continue;
  4134. if (fieldInstance->mResolvedType->IsValuelessType())
  4135. continue;
  4136. if (fieldInstance->mResolvedType->IsVar())
  4137. continue;
  4138. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4139. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4140. if (!fieldInstance->mResolvedType->IsComposite())
  4141. {
  4142. leftValue = LoadValue(leftValue);
  4143. rightValue = LoadValue(rightValue);
  4144. }
  4145. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4146. }
  4147. auto baseTypeInst = compareTypeInst->mBaseType;
  4148. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4149. {
  4150. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4151. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4152. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4153. }
  4154. }
  4155. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4156. mBfIRBuilder->CreateBr(exitBB);
  4157. mBfIRBuilder->AddBlock(exitBB);
  4158. mBfIRBuilder->SetInsertPoint(exitBB);
  4159. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4160. ClearLifetimeEnds();
  4161. mBfIRBuilder->CreateRet(loadedResult);
  4162. mCurMethodState->mHadReturn = true;
  4163. }
  4164. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4165. {
  4166. if (mBfIRBuilder->mIgnoreWrites)
  4167. return mBfIRBuilder->GetFakeVal();
  4168. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4169. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4170. if (mIsComptimeModule)
  4171. {
  4172. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4173. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4174. }
  4175. BfIRValue* globalVariablePtr = NULL;
  4176. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4177. int numElements = 1;
  4178. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4179. {
  4180. numElements += mCompiler->mMaxInterfaceSlots;
  4181. auto maxIFaceVirtIdx = 0;
  4182. if (!typeInstance->IsInterface())
  4183. {
  4184. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4185. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4186. numElements += typeInstance->GetOrigVTableSize();
  4187. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4188. if (typeInstance->mHotTypeData != NULL)
  4189. {
  4190. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4191. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4192. }
  4193. numElements += ifaceMethodLen;
  4194. }
  4195. if (outNumElements != NULL)
  4196. *outNumElements = numElements;
  4197. }
  4198. StringT<128> classVDataName;
  4199. String memberName = "sBfClassVData";
  4200. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4201. {
  4202. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4203. memberName += "_";
  4204. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4205. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4206. }
  4207. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4208. if (outMangledName != NULL)
  4209. *outMangledName = classVDataName;
  4210. /*if (itr != mClassVDataRefs.end())
  4211. {
  4212. globalVariable = itr->second;
  4213. }*/
  4214. BfIRValue globalVariable;
  4215. if (globalVariablePtr != NULL)
  4216. {
  4217. globalVariable = *globalVariablePtr;
  4218. }
  4219. else
  4220. {
  4221. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4222. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4223. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4224. arrayType,
  4225. true,
  4226. BfIRLinkageType_External,
  4227. BfIRValue(),
  4228. classVDataName);
  4229. mClassVDataRefs[typeInstance] = globalVariable;
  4230. }
  4231. return globalVariable;
  4232. }
  4233. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4234. {
  4235. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4236. if (mIsComptimeModule)
  4237. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4238. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4239. }
  4240. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4241. {
  4242. if (mBfIRBuilder->mIgnoreWrites)
  4243. return mBfIRBuilder->GetFakeVal();
  4244. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4245. BF_ASSERT(numElements >= 0);
  4246. if (numElements <= 0)
  4247. return BfIRValue();
  4248. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4249. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4250. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4251. BF_ASSERT(declTypeInst == implTypeInst);
  4252. else
  4253. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4254. if (declTypeInst != implTypeInst)
  4255. {
  4256. BfTypeInstance* highestImpl = declTypeInst;
  4257. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4258. {
  4259. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4260. break; // Start of an ext entry for another type
  4261. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4262. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4263. highestImpl = checkImplTypeInst;
  4264. }
  4265. if (highestImpl != implTypeInst)
  4266. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4267. }
  4268. BfVDataExtEntry mapEntry;
  4269. mapEntry.mDeclTypeInst = declTypeInst;
  4270. mapEntry.mImplTypeInst = implTypeInst;
  4271. BfIRValue* irValuePtr = NULL;
  4272. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4273. return *irValuePtr;
  4274. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4275. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4276. StringT<128> classVDataName;
  4277. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4278. if (declTypeInst != implTypeInst)
  4279. {
  4280. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4281. }
  4282. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4283. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4284. SizedArray<BfIRValue, 32> vData;
  4285. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4286. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4287. {
  4288. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4289. break; // Start of an ext entry for another type
  4290. BfIRValue vValue;
  4291. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4292. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4293. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4294. {
  4295. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4296. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4297. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4298. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4299. {
  4300. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4301. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4302. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4303. vValue = funcPtr;
  4304. }
  4305. }
  4306. if (!vValue)
  4307. vValue = voidPtrNull;
  4308. vData.Add(vValue);
  4309. }
  4310. BF_ASSERT((int)vData.size() == numElements);
  4311. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4312. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4313. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4314. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4315. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4316. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4317. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4318. mClassVDataExtRefs[mapEntry] = globalVariable;
  4319. return globalVariable;
  4320. }
  4321. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4322. {
  4323. if (mBfIRBuilder->mIgnoreWrites)
  4324. {
  4325. return mBfIRBuilder->CreateTypeOf(type);
  4326. }
  4327. if (mIsComptimeModule)
  4328. {
  4329. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4330. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4331. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4332. }
  4333. PopulateType(type);
  4334. BfIRValue globalVariable;
  4335. BfIRValue* globalVariablePtr = NULL;
  4336. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4337. {
  4338. if (*globalVariablePtr)
  4339. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4340. }
  4341. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4342. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4343. auto typeInstance = type->ToTypeInstance();
  4344. StringT<128> typeDataName;
  4345. if (typeInstance != NULL)
  4346. {
  4347. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4348. }
  4349. else
  4350. {
  4351. typeDataName += "sBfTypeData.";
  4352. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4353. }
  4354. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4355. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4356. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4357. mTypeDataRefs[type] = globalVariable;
  4358. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4359. }
  4360. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4361. {
  4362. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  4363. return BfIRValue();
  4364. BfIRValue* irValuePtr = NULL;
  4365. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4366. {
  4367. return *irValuePtr;
  4368. }
  4369. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4370. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4371. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4372. if (typeInstanceType == NULL)
  4373. {
  4374. AssertErrorState();
  4375. return BfIRValue();
  4376. }
  4377. if (mContext->mBfTypeType == NULL)
  4378. {
  4379. }
  4380. BfIRValue typeTypeData;
  4381. int typeFlags = 0;
  4382. if (needsTypeData)
  4383. {
  4384. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4385. BfTypeInstance* typeDataSource = NULL;
  4386. if (typeInstance != NULL)
  4387. {
  4388. if (typeInstance->IsUnspecializedType())
  4389. {
  4390. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4391. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4392. }
  4393. else if (typeInstance->IsArray())
  4394. {
  4395. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4396. typeFlags |= BfTypeFlags_Array;
  4397. }
  4398. else if (typeInstance->IsGenericTypeInstance())
  4399. {
  4400. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4401. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4402. }
  4403. else
  4404. typeDataSource = typeInstanceTypeInstance;
  4405. }
  4406. else if (type->IsPointer())
  4407. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4408. else if (type->IsRef())
  4409. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4410. else if (type->IsSizedArray())
  4411. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4412. else
  4413. typeDataSource = mContext->mBfTypeType;
  4414. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  4415. {
  4416. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  4417. }
  4418. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  4419. }
  4420. else
  4421. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  4422. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  4423. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4424. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4425. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4426. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4427. BfType* typeIdType = intType;
  4428. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4429. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4430. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4431. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4432. SizedArray<BfIRValue, 4> typeValueParams;
  4433. GetConstClassValueParam(typeTypeData, typeValueParams);
  4434. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4435. StringT<128> typeDataName;
  4436. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4437. {
  4438. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4439. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4440. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4441. }
  4442. else
  4443. {
  4444. typeDataName += "sBfTypeData.";
  4445. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4446. }
  4447. int typeCode = BfTypeCode_None;
  4448. if (typeInstance != NULL)
  4449. {
  4450. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  4451. typeCode = typeInstance->mTypeDef->mTypeCode;
  4452. }
  4453. else if (type->IsPrimitiveType())
  4454. {
  4455. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4456. typeCode = primType->mTypeDef->mTypeCode;
  4457. }
  4458. else if (type->IsPointer())
  4459. {
  4460. typeCode = BfTypeCode_Pointer;
  4461. typeFlags |= BfTypeFlags_Pointer;
  4462. }
  4463. else if (type->IsRef())
  4464. {
  4465. typeCode = BfTypeCode_Pointer;
  4466. typeFlags |= BfTypeFlags_Pointer;
  4467. }
  4468. if (type->IsObject())
  4469. {
  4470. typeFlags |= BfTypeFlags_Object;
  4471. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  4472. {
  4473. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4474. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4475. typeFlags |= BfTypeFlags_HasDestructor;
  4476. }
  4477. }
  4478. if (type->IsStruct())
  4479. typeFlags |= BfTypeFlags_Struct;
  4480. if (type->IsInterface())
  4481. typeFlags |= BfTypeFlags_Interface;
  4482. if (type->IsBoxed())
  4483. {
  4484. typeFlags |= BfTypeFlags_Boxed;
  4485. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4486. typeFlags |= BfTypeFlags_Pointer;
  4487. }
  4488. if (type->IsPrimitiveType())
  4489. typeFlags |= BfTypeFlags_Primitive;
  4490. if (type->IsTypedPrimitive())
  4491. typeFlags |= BfTypeFlags_TypedPrimitive;
  4492. if (type->IsTuple())
  4493. typeFlags |= BfTypeFlags_Tuple;
  4494. if (type->IsNullable())
  4495. typeFlags |= BfTypeFlags_Nullable;
  4496. if (type->IsSizedArray())
  4497. typeFlags |= BfTypeFlags_SizedArray;
  4498. if (type->IsSplattable())
  4499. typeFlags |= BfTypeFlags_Splattable;
  4500. if (type->IsUnion())
  4501. typeFlags |= BfTypeFlags_Union;
  4502. if (type->IsDelegate())
  4503. typeFlags |= BfTypeFlags_Delegate;
  4504. if (type->IsFunction())
  4505. typeFlags |= BfTypeFlags_Function;
  4506. if (type->WantsGCMarking())
  4507. typeFlags |= BfTypeFlags_WantsMarking;
  4508. int virtSlotIdx = -1;
  4509. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  4510. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  4511. int memberDataOffset = 0;
  4512. if (type->IsInterface())
  4513. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  4514. else if (typeInstance != NULL)
  4515. {
  4516. for (auto& fieldInstance : typeInstance->mFieldInstances)
  4517. {
  4518. if (fieldInstance.mDataOffset != -1)
  4519. {
  4520. memberDataOffset = fieldInstance.mDataOffset;
  4521. break;
  4522. }
  4523. }
  4524. }
  4525. int boxedTypeId = 0;
  4526. if ((type->IsValueType()) || (type->IsWrappableType()))
  4527. {
  4528. auto boxedType = CreateBoxedType(type, false);
  4529. if ((boxedType != NULL) && (boxedType->mIsReified))
  4530. boxedTypeId = boxedType->mTypeId;
  4531. }
  4532. SizedArray<BfIRValue, 8> typeDataParams =
  4533. {
  4534. objectData,
  4535. GetConstValue(type->mSize, intType), // mSize
  4536. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  4537. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  4538. GetConstValue(typeFlags, intType), // mTypeFlags
  4539. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  4540. GetConstValue(typeCode, byteType), // mTypeCode
  4541. GetConstValue(type->mAlign, byteType),
  4542. };
  4543. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  4544. if (typeInstance == NULL)
  4545. {
  4546. BfIRValue typeDataVar;
  4547. if (needsTypeData)
  4548. {
  4549. if (type->IsPointer())
  4550. {
  4551. auto pointerType = (BfPointerType*)type;
  4552. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  4553. {
  4554. typeData,
  4555. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  4556. };
  4557. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4558. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  4559. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  4560. BfIRLinkageType_External, pointerTypeData, typeDataName);
  4561. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4562. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4563. }
  4564. else if (type->IsRef())
  4565. {
  4566. auto refType = (BfRefType*)type;
  4567. SizedArray<BfIRValue, 3> refTypeDataParms =
  4568. {
  4569. typeData,
  4570. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  4571. GetConstValue((int8)refType->mRefKind, byteType),
  4572. };
  4573. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4574. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  4575. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  4576. BfIRLinkageType_External, refTypeData, typeDataName);
  4577. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4578. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4579. }
  4580. else if (type->IsSizedArray())
  4581. {
  4582. auto sizedArrayType = (BfSizedArrayType*)type;
  4583. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  4584. {
  4585. typeData,
  4586. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  4587. GetConstValue(sizedArrayType->mElementCount, intType)
  4588. };
  4589. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4590. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  4591. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  4592. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  4593. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4594. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4595. }
  4596. else
  4597. {
  4598. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  4599. BfIRLinkageType_External, typeData, typeDataName);
  4600. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4601. }
  4602. }
  4603. else
  4604. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  4605. mTypeDataRefs[type] = typeDataVar;
  4606. return typeDataVar;
  4607. }
  4608. // Reserve position
  4609. mTypeDataRefs[typeInstance] = BfIRValue();
  4610. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  4611. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4612. BfTypeDef* typeDef = typeInstance->mTypeDef;
  4613. StringT<128> mangledName;
  4614. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  4615. if (!mIsComptimeModule)
  4616. {
  4617. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4618. {
  4619. auto methodDef = typeDef->mMethods[methodIdx];
  4620. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  4621. if (methodInstance == NULL)
  4622. continue;
  4623. if (typeInstance->IsUnspecializedType())
  4624. continue;
  4625. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4626. {
  4627. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4628. {
  4629. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  4630. // We need to create an empty thunk for this chained method
  4631. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4632. mBfIRBuilder->SetActiveFunction(func);
  4633. auto block = mBfIRBuilder->CreateBlock("entry", true);
  4634. mBfIRBuilder->SetInsertPoint(block);
  4635. mBfIRBuilder->CreateRetVoid();
  4636. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  4637. }
  4638. }
  4639. }
  4640. }
  4641. SizedArray<BfIRValue, 32> vData;
  4642. BfIRValue classVDataVar;
  4643. String classVDataName;
  4644. if (typeInstance->mSlotNum >= 0)
  4645. {
  4646. // For interfaces we ONLY emit the slot num
  4647. StringT<128> slotVarName;
  4648. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  4649. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4650. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  4651. GetConstValue32(virtSlotIdx), slotVarName);
  4652. }
  4653. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  4654. {
  4655. int dynCastDataElems = 0;
  4656. int numElements = 1;
  4657. int vDataOfs = 1; // The number of intptrs before the iface slot map
  4658. numElements += mCompiler->mMaxInterfaceSlots;
  4659. if (!typeInstance->IsInterface())
  4660. {
  4661. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4662. numElements += mCompiler->GetDynCastVDataCount();
  4663. numElements += typeInstance->mVirtualMethodTableSize;
  4664. }
  4665. int expectNumElements = 0;
  4666. if (!typeDef->mIsStatic)
  4667. {
  4668. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  4669. }
  4670. vData.push_back(BfIRValue()); // Type*
  4671. SizedArray<BfIRValue, 1> extVTableData;
  4672. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  4673. if (!typeInstance->IsInterface())
  4674. {
  4675. Array<int32> dynCastData;
  4676. if (typeInstance->IsBoxed())
  4677. {
  4678. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  4679. dynCastData.Add(underlyingType->mInheritanceId);
  4680. }
  4681. else
  4682. dynCastData.Add(typeInstance->mInheritanceId);
  4683. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  4684. dynCastData.Add(0);
  4685. dynCastData.Add(0);
  4686. auto checkTypeInst = typeInstance;
  4687. while (checkTypeInst != NULL)
  4688. {
  4689. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4690. {
  4691. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  4692. {
  4693. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  4694. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  4695. }
  4696. }
  4697. checkTypeInst = checkTypeInst->GetImplBaseType();
  4698. }
  4699. if (mSystem->mPtrSize == 8)
  4700. {
  4701. int intPtrCount = (dynCastDataElems + 1) / 2;
  4702. vDataOfs += intPtrCount;
  4703. uint64* intPtrData = (uint64*)&dynCastData[0];
  4704. for (int i = 0; i < intPtrCount; i++)
  4705. {
  4706. uint64 val = intPtrData[i];
  4707. if (val == 0)
  4708. {
  4709. vData.push_back(voidPtrNull);
  4710. }
  4711. else
  4712. {
  4713. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4714. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4715. }
  4716. }
  4717. }
  4718. else
  4719. {
  4720. int intPtrCount = dynCastDataElems;
  4721. vDataOfs += intPtrCount;
  4722. uint32* intPtrData = (uint32*)&dynCastData[0];
  4723. for (int i = 0; i < intPtrCount; i++)
  4724. {
  4725. uint32 val = intPtrData[i];
  4726. if (val == 0)
  4727. {
  4728. vData.push_back(voidPtrNull);
  4729. }
  4730. else
  4731. {
  4732. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  4733. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4734. }
  4735. }
  4736. }
  4737. }
  4738. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  4739. vData.push_back(voidPtrNull);
  4740. struct _InterfaceMatchEntry
  4741. {
  4742. BfTypeInterfaceEntry* mEntry;
  4743. BfTypeInstance* mEntrySource;
  4744. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  4745. };
  4746. int highestIFaceVirtIdx = 0;
  4747. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  4748. auto checkTypeInst = typeInstance;
  4749. bool forceInterfaceSet = false;
  4750. while (checkTypeInst != NULL)
  4751. {
  4752. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4753. {
  4754. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  4755. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  4756. continue;
  4757. _InterfaceMatchEntry* matchEntry = NULL;
  4758. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  4759. {
  4760. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  4761. if (compareCheckTypeInst->IsBoxed())
  4762. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  4763. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  4764. if (compareEntrySource->IsBoxed())
  4765. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  4766. auto prevEntry = matchEntry->mEntry;
  4767. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  4768. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  4769. if ((!isBetter) && (!isWorse))
  4770. {
  4771. // Unboxed comparison to Object fix
  4772. if (compareCheckTypeInst == mContext->mBfObjectType)
  4773. isWorse = true;
  4774. else if (compareEntrySource == mContext->mBfObjectType)
  4775. isBetter = true;
  4776. }
  4777. if (forceInterfaceSet)
  4778. {
  4779. isBetter = true;
  4780. isWorse = false;
  4781. }
  4782. if (isBetter == isWorse)
  4783. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4784. if (isBetter == isWorse)
  4785. {
  4786. if (matchEntry->mAmbiguousEntries.empty())
  4787. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4788. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4789. continue;
  4790. }
  4791. else if (isBetter)
  4792. {
  4793. matchEntry->mEntry = &interfaceEntry;
  4794. matchEntry->mEntrySource = checkTypeInst;
  4795. matchEntry->mAmbiguousEntries.Clear();
  4796. }
  4797. else
  4798. continue;
  4799. }
  4800. else
  4801. {
  4802. _InterfaceMatchEntry matchEntry;
  4803. matchEntry.mEntry = &interfaceEntry;
  4804. matchEntry.mEntrySource = checkTypeInst;
  4805. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4806. }
  4807. }
  4808. checkTypeInst = checkTypeInst->GetImplBaseType();
  4809. }
  4810. for (auto interfacePair : interfaceMap)
  4811. {
  4812. auto& interfaceMatchEntry = interfacePair.mValue;
  4813. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4814. {
  4815. 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());
  4816. if (error != NULL)
  4817. {
  4818. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4819. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4820. }
  4821. }
  4822. }
  4823. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4824. {
  4825. int startTabIdx = (int)vData.size();
  4826. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4827. BfTypeInstance* checkTypeInst = typeInstance;
  4828. while (checkTypeInst != NULL)
  4829. {
  4830. origVirtTypeStack.push_back(checkTypeInst);
  4831. checkTypeInst = checkTypeInst->GetImplBaseType();
  4832. }
  4833. Array<BfVirtualMethodEntry> origVTable;
  4834. int origVirtIdx = 0;
  4835. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4836. {
  4837. HashSet<String> reslotNames;
  4838. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4839. {
  4840. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4841. if (entry.mDeclaringMethod.mMethodNum == -1)
  4842. continue;
  4843. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4844. if ((methodInstance == NULL) ||
  4845. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  4846. {
  4847. if (origVTable.empty())
  4848. origVTable = typeInstance->mVirtualMethodTable;
  4849. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4850. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  4851. {
  4852. // Prepare to reslot...
  4853. entry.mImplementingMethod = entry.mDeclaringMethod;
  4854. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4855. }
  4856. else
  4857. {
  4858. // Decl isn't accessible, null out entry
  4859. entry.mImplementingMethod = BfMethodRef();
  4860. }
  4861. }
  4862. }
  4863. if (!reslotNames.IsEmpty())
  4864. {
  4865. BfAmbiguityContext ambiguityContext;
  4866. ambiguityContext.mTypeInstance = typeInstance;
  4867. ambiguityContext.mModule = this;
  4868. ambiguityContext.mIsProjectSpecific = true;
  4869. ambiguityContext.mIsReslotting = true;
  4870. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4871. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4872. {
  4873. auto methodInstance = methodGroup.mDefault;
  4874. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4875. continue;
  4876. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4877. continue;
  4878. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4879. continue;
  4880. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4881. continue;
  4882. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4883. }
  4884. ambiguityContext.Finish();
  4885. }
  4886. }
  4887. bool isInExts = false;
  4888. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4889. {
  4890. BfIRValue vValue = voidPtrNull;
  4891. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4892. BfModuleMethodInstance moduleMethodInst;
  4893. if (entry.mDeclaringMethod.mMethodNum == -1)
  4894. {
  4895. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4896. isInExts = true;
  4897. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4898. if (vExt)
  4899. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4900. }
  4901. else
  4902. {
  4903. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4904. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4905. {
  4906. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4907. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4908. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4909. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4910. {
  4911. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4912. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4913. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4914. vValue = funcPtr;
  4915. }
  4916. }
  4917. }
  4918. while (origVirtTypeStack.size() != 0)
  4919. {
  4920. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4921. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4922. {
  4923. // Moved past current base vtable size
  4924. origVirtTypeStack.pop_back();
  4925. continue;
  4926. }
  4927. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4928. {
  4929. // We are within the original vtable size
  4930. int idx = startTabIdx + origVirtIdx;
  4931. origVirtIdx++;
  4932. vData.push_back(vValue);
  4933. }
  4934. else
  4935. {
  4936. // This is a new entry, it only gets added to the ext
  4937. BF_ASSERT(isInExts);
  4938. }
  4939. break;
  4940. }
  4941. }
  4942. if (!origVTable.empty())
  4943. typeInstance->mVirtualMethodTable = origVTable;
  4944. }
  4945. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4946. if (typeInstance->mHotTypeData != NULL)
  4947. {
  4948. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4949. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4950. }
  4951. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4952. int iFaceMethodStartIdx = (int)vData.size();
  4953. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4954. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4955. vData[i] = voidPtrNull;
  4956. if (expectNumElements != 0)
  4957. BF_ASSERT(expectNumElements == vData.size());
  4958. //BF_ASSERT(vData.size() == expectNumElements);
  4959. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4960. // ifaceMethodExtData.Add(voidPtrNull);
  4961. int ifaceEntryIdx = iFaceMethodStartIdx;
  4962. for (auto& interfacePair : interfaceMap)
  4963. {
  4964. auto interfaceEntry = interfacePair.mValue.mEntry;
  4965. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  4966. {
  4967. BF_ASSERT(mIsComptimeModule);
  4968. break;
  4969. }
  4970. bool makeEmpty = false;
  4971. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  4972. makeEmpty = true;
  4973. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4974. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4975. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4976. {
  4977. BfIRValue pushValue;
  4978. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4979. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4980. continue;
  4981. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4982. continue;
  4983. if (makeEmpty)
  4984. {
  4985. pushValue = voidPtrNull;
  4986. }
  4987. else
  4988. {
  4989. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4990. auto methodInstance = (BfMethodInstance*)methodRef;
  4991. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4992. {
  4993. BF_ASSERT(methodInstance->mIsReified);
  4994. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4995. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4996. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4997. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4998. pushValue = funcPtr;
  4999. }
  5000. else
  5001. {
  5002. pushValue = voidPtrNull;
  5003. }
  5004. }
  5005. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5006. if (idx < ifaceMethodExtStart)
  5007. {
  5008. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5009. vData[iFaceMethodStartIdx + idx] = pushValue;
  5010. }
  5011. else
  5012. {
  5013. BF_ASSERT(useExt);
  5014. int extIdx = idx - ifaceMethodExtStart;
  5015. while (extIdx >= ifaceMethodExtData.size())
  5016. ifaceMethodExtData.Add(voidPtrNull);
  5017. ifaceMethodExtData[extIdx] = pushValue;
  5018. }
  5019. }
  5020. }
  5021. if (typeInstance->IsBoxed())
  5022. {
  5023. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5024. if (boxedType->IsBoxedStructPtr())
  5025. {
  5026. // Force override of GetHashCode so we use the pointer address as the hash code
  5027. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5028. // Force override of GetHashCode so we use the pointer address as the hash code
  5029. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5030. {
  5031. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5032. {
  5033. BfIRValue pushValue;
  5034. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5035. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5036. continue;
  5037. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5038. continue;
  5039. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5040. auto methodInstance = (BfMethodInstance*)methodRef;
  5041. BF_ASSERT(methodInstance->mIsReified);
  5042. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5043. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5044. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5045. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5046. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5047. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5048. }
  5049. }
  5050. }
  5051. }
  5052. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5053. {
  5054. BfIRValue ifaceMethodExtVar;
  5055. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5056. {
  5057. StringT<128> classVDataName;
  5058. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5059. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5060. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5061. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5062. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5063. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5064. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5065. }
  5066. for (auto& ifaceInstPair : interfaceMap)
  5067. {
  5068. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5069. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5070. if (slotNum >= 0)
  5071. {
  5072. BfIRValue vtablePtr;
  5073. int idx = interfaceEntry->mStartVirtualIdx;
  5074. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5075. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5076. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5077. else
  5078. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5079. int slotVirtIdx = slotNum + vDataOfs;
  5080. if (vData[slotVirtIdx] == voidPtrNull)
  5081. {
  5082. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5083. }
  5084. else
  5085. {
  5086. if (mCompiler->IsHotCompile())
  5087. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5088. else
  5089. Fail("Interface slot collision error", typeDef->GetRefNode());
  5090. }
  5091. }
  5092. }
  5093. }
  5094. }
  5095. BfIRValue typeNameConst;
  5096. BfIRValue namespaceConst;
  5097. if (needsTypeNames)
  5098. {
  5099. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  5100. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  5101. }
  5102. else
  5103. {
  5104. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5105. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5106. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5107. }
  5108. int baseTypeId = 0;
  5109. if (typeInstance->mBaseType != NULL)
  5110. {
  5111. baseTypeId = typeInstance->mBaseType->mTypeId;
  5112. }
  5113. BfTypeOptions* typeOptions = NULL;
  5114. if (typeInstance->mTypeOptionsIdx >= 0)
  5115. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5116. SizedArray<BfIRValue, 16> customAttrs;
  5117. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5118. BfIRValue castedClassVData;
  5119. if (classVDataVar)
  5120. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5121. else
  5122. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5123. bool freflectIncludeTypeData = false;
  5124. bool reflectIncludeAllFields = false;
  5125. bool reflectIncludeAllMethods = false;
  5126. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5127. {
  5128. reflectIncludeAllFields = true;
  5129. reflectIncludeAllMethods = true;
  5130. }
  5131. BfReflectKind reflectKind = BfReflectKind_Type;
  5132. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5133. {
  5134. BfReflectKind reflectKind = BfReflectKind_None;
  5135. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5136. if (customAttrs != NULL)
  5137. {
  5138. for (auto& attr : customAttrs->mAttributes)
  5139. {
  5140. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5141. }
  5142. }
  5143. return reflectKind;
  5144. };
  5145. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5146. // Fields
  5147. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5148. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5149. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5150. {
  5151. if (customAttributes == NULL)
  5152. return -1;
  5153. Array<BfCustomAttribute*> reflectAttributes;
  5154. for (auto& attr : customAttributes->mAttributes)
  5155. {
  5156. bool wantAttribute = false;
  5157. if (attr.mType->mCustomAttributes != NULL)
  5158. {
  5159. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5160. if (usageAttribute != NULL)
  5161. {
  5162. // Check for Flags arg
  5163. if (usageAttribute->mCtorArgs.size() < 2)
  5164. continue;
  5165. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  5166. if (constant == NULL)
  5167. continue;
  5168. if (constant->mTypeCode == BfTypeCode_Boolean)
  5169. continue;
  5170. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  5171. wantAttribute = true;
  5172. }
  5173. }
  5174. if ((wantAttribute) && (attr.mType->mIsReified))
  5175. {
  5176. reflectAttributes.Add(&attr);
  5177. }
  5178. }
  5179. if (reflectAttributes.size() == 0)
  5180. return -1;
  5181. #define PUSH_INT8(val) data.push_back((uint8)val)
  5182. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5183. #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); }
  5184. #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); \
  5185. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  5186. SizedArray<uint8, 16> data;
  5187. int customAttrIdx = (int)customAttrs.size();
  5188. data.push_back((uint8)reflectAttributes.size());
  5189. for (auto attr : reflectAttributes)
  5190. {
  5191. // Size prefix
  5192. int sizeIdx = (int)data.size();
  5193. PUSH_INT16(0); // mSize
  5194. PUSH_INT32(attr->mType->mTypeId); // mType
  5195. PUSH_INT16(attr->mCtor->mIdx);
  5196. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  5197. int argIdx = 0;
  5198. for (auto arg : attr->mCtorArgs)
  5199. {
  5200. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  5201. bool handled = false;
  5202. if (constant != NULL)
  5203. {
  5204. auto argType = ctorMethodInstance->GetParamType(argIdx);
  5205. if (argType->IsObject())
  5206. {
  5207. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  5208. int stringId = constant->mInt32;
  5209. int* orderedIdPtr;
  5210. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5211. {
  5212. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5213. }
  5214. GetStringObjectValue(stringId);
  5215. PUSH_INT8(0xFF); // String
  5216. PUSH_INT32(*orderedIdPtr);
  5217. argIdx++;
  5218. continue;
  5219. }
  5220. if (argType->IsPointer())
  5221. {
  5222. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  5223. {
  5224. if (constant->mTypeCode == BfTypeCode_StringId)
  5225. {
  5226. int stringId = constant->mInt32;
  5227. int* orderedIdPtr;
  5228. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  5229. {
  5230. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  5231. }
  5232. GetStringObjectValue(stringId);
  5233. PUSH_INT8(0xFF); // String
  5234. PUSH_INT32(*orderedIdPtr);
  5235. argIdx++;
  5236. continue;
  5237. }
  5238. }
  5239. }
  5240. PUSH_INT8(constant->mTypeCode);
  5241. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  5242. (constant->mTypeCode == BfTypeCode_UInt64) ||
  5243. (constant->mTypeCode == BfTypeCode_Double))
  5244. {
  5245. PUSH_INT64(constant->mInt64);
  5246. }
  5247. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5248. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5249. (constant->mTypeCode == BfTypeCode_Char32))
  5250. {
  5251. PUSH_INT32(constant->mInt32);
  5252. }
  5253. else if (constant->mTypeCode == BfTypeCode_Float)
  5254. {
  5255. float val = (float)constant->mDouble;
  5256. PUSH_INT32(*(int*)&val);
  5257. }
  5258. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5259. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5260. (constant->mTypeCode == BfTypeCode_Char16))
  5261. {
  5262. PUSH_INT16(constant->mInt16);
  5263. }
  5264. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5265. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5266. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5267. (constant->mTypeCode == BfTypeCode_Char8))
  5268. {
  5269. PUSH_INT8(constant->mInt8);
  5270. }
  5271. else
  5272. {
  5273. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(type).c_str()));
  5274. }
  5275. }
  5276. else if (!handled)
  5277. {
  5278. BFMODULE_FATAL(this, "Unhandled");
  5279. }
  5280. argIdx++;
  5281. }
  5282. int size = (int)data.size() - sizeIdx;
  5283. *((uint16*)&data[sizeIdx]) = size;
  5284. }
  5285. #undef PUSH_INT8
  5286. #undef PUSH_INT16
  5287. #undef PUSH_INT32
  5288. SizedArray<BfIRValue, 16> dataValues;
  5289. for (uint8 val : data)
  5290. dataValues.push_back(GetConstValue8(val));
  5291. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5292. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  5293. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5294. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5295. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5296. customAttrs.push_back(customAttrArrayPtr);
  5297. return customAttrIdx;
  5298. };
  5299. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5300. SizedArray<int, 16> reflectFieldIndices;
  5301. for (int pass = 0; pass < 2; pass++)
  5302. {
  5303. bool skippedField = false;
  5304. reflectFieldIndices.clear();
  5305. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5306. {
  5307. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5308. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5309. if (fieldDef == NULL)
  5310. continue;
  5311. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5312. bool includeField = reflectIncludeAllFields;
  5313. if (fieldInstance->mCustomAttributes != NULL)
  5314. {
  5315. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5316. {
  5317. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5318. {
  5319. includeField = true;
  5320. }
  5321. else
  5322. {
  5323. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5324. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5325. }
  5326. }
  5327. }
  5328. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5329. includeField = true;
  5330. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5331. includeField = true;
  5332. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5333. includeField = true;
  5334. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5335. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5336. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5337. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5338. includeField |= forceReflectFields;
  5339. if (!includeField)
  5340. {
  5341. skippedField = true;
  5342. continue;
  5343. }
  5344. reflectFieldIndices.Add(fieldIdx);
  5345. }
  5346. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5347. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5348. // possible because we write out a SplatData structure containing just TypeIds in that case
  5349. if (pass == 0)
  5350. {
  5351. if (!typeInstance->IsSplattable())
  5352. break;
  5353. if (!skippedField)
  5354. break;
  5355. if (reflectFieldIndices.size() == 0)
  5356. break;
  5357. }
  5358. }
  5359. SizedArray<BfIRValue, 16> fieldTypes;
  5360. enum FieldFlags
  5361. {
  5362. FieldFlags_Protected = 3,
  5363. FieldFlags_Public = 6,
  5364. FieldFlags_Static = 0x10,
  5365. FieldFlags_Const = 0x40,
  5366. FieldFlags_SpecialName = 0x80,
  5367. FieldFlags_EnumPayload = 0x100,
  5368. FieldFlags_EnumDiscriminator = 0x200
  5369. };
  5370. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5371. {
  5372. BfType* payloadType = typeInstance->GetUnionInnerType();
  5373. if (!payloadType->IsValuelessType())
  5374. {
  5375. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  5376. SizedArray<BfIRValue, 8> payloadFieldVals =
  5377. {
  5378. emptyValueType,
  5379. payloadNameConst, // mName
  5380. GetConstValue(0, intPtrType), // mData
  5381. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5382. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  5383. GetConstValue(-1, intType), // mCustomAttributesIdx
  5384. };
  5385. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5386. fieldTypes.push_back(payloadFieldData);
  5387. }
  5388. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5389. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  5390. SizedArray<BfIRValue, 8> dscrFieldVals =
  5391. {
  5392. emptyValueType,
  5393. dscrNameConst, // mName
  5394. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5395. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5396. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  5397. GetConstValue(-1, intType), // mCustomAttributesIdx
  5398. };
  5399. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  5400. fieldTypes.push_back(dscrFieldData);
  5401. }
  5402. for (auto fieldIdx : reflectFieldIndices)
  5403. {
  5404. if (!needsTypeData)
  5405. break;
  5406. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5407. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5408. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  5409. int typeId = 0;
  5410. auto fieldType = fieldInstance->GetResolvedType();
  5411. if (fieldType->IsGenericParam())
  5412. {
  5413. //TODO:
  5414. }
  5415. else
  5416. typeId = fieldType->mTypeId;
  5417. FieldFlags fieldFlags = (FieldFlags)0;
  5418. if (fieldDef->mProtection == BfProtection_Protected)
  5419. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  5420. if (fieldDef->mProtection == BfProtection_Public)
  5421. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  5422. if (fieldDef->mIsStatic)
  5423. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  5424. if (fieldDef->mIsConst)
  5425. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  5426. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  5427. BfIRValue constValue;
  5428. if (fieldInstance->GetFieldDef()->mIsConst)
  5429. {
  5430. if (fieldInstance->mConstIdx != -1)
  5431. {
  5432. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5433. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, constant->mUInt64);
  5434. }
  5435. }
  5436. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5437. {
  5438. auto refVal = ReferenceStaticField(fieldInstance);
  5439. if (refVal.mValue.IsConst())
  5440. {
  5441. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5442. if (constant->mConstType == BfConstType_GlobalVar)
  5443. {
  5444. auto globalVar = (BfGlobalVar*)constant;
  5445. if (globalVar->mName[0] == '#')
  5446. refVal = BfTypedValue();
  5447. }
  5448. }
  5449. if (refVal.IsAddr())
  5450. {
  5451. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5452. }
  5453. }
  5454. if (!constValue)
  5455. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5456. SizedArray<BfIRValue, 8> fieldVals =
  5457. {
  5458. emptyValueType,
  5459. fieldNameConst, // mName
  5460. constValue, // mConstValue
  5461. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5462. GetConstValue(fieldFlags, shortType), // mFlags
  5463. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  5464. };
  5465. auto fieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  5466. fieldTypes.push_back(fieldData);
  5467. }
  5468. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5469. BfIRValue fieldDataPtr;
  5470. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5471. if (fieldTypes.size() == 0)
  5472. {
  5473. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5474. {
  5475. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5476. SizedArray<BfIRValue, 3> splatTypes;
  5477. SizedArray<BfIRValue, 3> splatOffsets;
  5478. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5479. {
  5480. auto checkTypeInstance = checkType->ToTypeInstance();
  5481. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5482. PopulateType(checkTypeInstance);
  5483. if (checkType->IsStruct())
  5484. {
  5485. int dataEnd = offset;
  5486. if (checkTypeInstance->mBaseType != NULL)
  5487. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5488. if (checkTypeInstance->mIsUnion)
  5489. {
  5490. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5491. _CheckSplat(unionInnerType, offset);
  5492. }
  5493. else
  5494. {
  5495. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5496. {
  5497. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5498. if (fieldInstance->mDataIdx >= 0)
  5499. {
  5500. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5501. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5502. }
  5503. }
  5504. }
  5505. if (checkTypeInstance->IsEnum())
  5506. {
  5507. // Add discriminator
  5508. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5509. if (!checkTypeInstance->mIsPacked)
  5510. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5511. _CheckSplat(dscrType, dataEnd);
  5512. }
  5513. }
  5514. else if (checkType->IsMethodRef())
  5515. {
  5516. // auto methodRefType = (BfMethodRefType*)checkType;
  5517. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5518. // {
  5519. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5520. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5521. // else
  5522. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5523. // }
  5524. }
  5525. else if (!checkType->IsValuelessType())
  5526. {
  5527. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5528. splatOffsets.Add(GetConstValue(offset, intType));
  5529. }
  5530. };
  5531. _CheckSplat(type, 0);
  5532. while (splatTypes.size() < 3)
  5533. {
  5534. splatTypes.Add(GetConstValue(0, typeIdType));
  5535. splatOffsets.Add(GetConstValue(0, intType));
  5536. }
  5537. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5538. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  5539. SizedArray<BfIRValue, 8> splatVals =
  5540. {
  5541. emptyValueType,
  5542. splatTypesConst,
  5543. splatOffsetsConst
  5544. };
  5545. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  5546. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  5547. fieldSplatData, typeDataName + ".splats");
  5548. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5549. }
  5550. else
  5551. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  5552. }
  5553. else
  5554. {
  5555. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  5556. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  5557. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  5558. fieldDataConst, "fields." + typeDataName);
  5559. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5560. }
  5561. /// Methods
  5562. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  5563. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  5564. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  5565. SizedArray<BfIRValue, 16> methodTypes;
  5566. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5567. {
  5568. if (!needsTypeData)
  5569. break;
  5570. // Disable const method reflection info for now
  5571. if (mIsComptimeModule)
  5572. break;
  5573. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  5574. if (!methodInstanceGroup->IsImplemented())
  5575. continue;
  5576. auto methodDef = typeDef->mMethods[methodIdx];
  5577. if (methodDef->mIsNoReflect)
  5578. continue;
  5579. if (methodDef->mHasComptime)
  5580. continue;
  5581. auto defaultMethod = methodInstanceGroup->mDefault;
  5582. if (defaultMethod == NULL)
  5583. continue;
  5584. if (defaultMethod->mIsUnspecialized)
  5585. continue;
  5586. if (!defaultMethod->mIsReified)
  5587. continue;
  5588. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  5589. continue;
  5590. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  5591. continue;
  5592. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5593. bool includeMethod = reflectIncludeAllMethods;
  5594. BfCustomAttributes* methodCustomAttributes = NULL;
  5595. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  5596. {
  5597. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  5598. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  5599. {
  5600. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5601. {
  5602. includeMethod = true;
  5603. }
  5604. else
  5605. {
  5606. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5607. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  5608. }
  5609. }
  5610. }
  5611. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  5612. continue;
  5613. //
  5614. {
  5615. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5616. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  5617. {
  5618. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  5619. {
  5620. if (paramDecl->mAttributes != NULL)
  5621. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  5622. }
  5623. }
  5624. }
  5625. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  5626. includeMethod = true;
  5627. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  5628. includeMethod = true;
  5629. if ((!includeMethod) && (typeOptions != NULL))
  5630. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  5631. if (!includeMethod)
  5632. continue;
  5633. BfModuleMethodInstance moduleMethodInstance;
  5634. BfIRValue funcVal = voidPtrNull;
  5635. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  5636. (!typeInstance->IsUnspecializedType()) &&
  5637. (methodDef->mMethodType != BfMethodType_Ignore) &&
  5638. (methodDef->mMethodType != BfMethodType_Mixin) &&
  5639. (!methodDef->mIsAbstract) &&
  5640. (methodDef->mGenericParams.size() == 0))
  5641. {
  5642. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5643. if (moduleMethodInstance.mFunc)
  5644. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5645. }
  5646. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  5647. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  5648. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  5649. enum ParamFlags
  5650. {
  5651. ParamFlag_None = 0,
  5652. ParamFlag_Splat = 1,
  5653. ParamFlag_Implicit = 2,
  5654. };
  5655. SizedArray<BfIRValue, 8> paramVals;
  5656. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  5657. {
  5658. String paramName = defaultMethod->GetParamName(paramIdx);
  5659. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  5660. ParamFlags paramFlags = ParamFlag_None;
  5661. if (defaultMethod->GetParamIsSplat(paramIdx))
  5662. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  5663. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  5664. SizedArray<BfIRValue, 8> paramDataVals =
  5665. {
  5666. emptyValueType,
  5667. paramNameConst,
  5668. GetConstValue(paramType->mTypeId, typeIdType),
  5669. GetConstValue((int32)paramFlags, shortType),
  5670. GetConstValue(customAttrIdx, intType) // defaultIdx
  5671. };
  5672. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  5673. paramVals.Add(paramData);
  5674. }
  5675. BfIRValue paramsVal;
  5676. if (paramVals.size() > 0)
  5677. {
  5678. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  5679. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  5680. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  5681. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  5682. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  5683. }
  5684. else
  5685. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  5686. int vDataVal = -1;
  5687. if (defaultMethod->mVirtualTableIdx != -1)
  5688. {
  5689. int vDataIdx = -1;
  5690. if (type->IsInterface())
  5691. {
  5692. vDataIdx = defaultMethod->mVirtualTableIdx;
  5693. }
  5694. else
  5695. {
  5696. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  5697. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  5698. {
  5699. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  5700. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  5701. if (extMethodIdx >= 0)
  5702. {
  5703. // Extension?
  5704. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  5705. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  5706. }
  5707. else
  5708. {
  5709. // Map this new virtual index back to the original index
  5710. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  5711. }
  5712. }
  5713. else
  5714. {
  5715. vDataIdx += defaultMethod->mVirtualTableIdx;
  5716. }
  5717. }
  5718. if (vDataVal == -1)
  5719. vDataVal = vDataIdx * mSystem->mPtrSize;
  5720. }
  5721. SizedArray<BfIRValue, 8> methodDataVals =
  5722. {
  5723. emptyValueType,
  5724. methodNameConst, // mName
  5725. funcVal, // mFuncPtr
  5726. paramsVal,
  5727. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  5728. GetConstValue((int)paramVals.size(), shortType),
  5729. GetConstValue(methodFlags, shortType),
  5730. GetConstValue(methodIdx, intType),
  5731. GetConstValue(vDataVal, intType),
  5732. GetConstValue(customAttrIdx, intType),
  5733. };
  5734. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  5735. methodTypes.push_back(methodData);
  5736. }
  5737. BfIRValue methodDataPtr;
  5738. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  5739. if (methodTypes.size() == 0)
  5740. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5741. else
  5742. {
  5743. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5744. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  5745. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5746. methodDataConst, "methods." + typeDataName);
  5747. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5748. }
  5749. /////
  5750. int interfaceCount = 0;
  5751. BfIRValue interfaceDataPtr;
  5752. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  5753. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  5754. Array<bool> wantsIfaceMethod;
  5755. bool wantsIfaceMethods = false;
  5756. if (typeInstance->mInterfaces.IsEmpty())
  5757. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  5758. else
  5759. {
  5760. SizedArray<BfIRValue, 16> interfaces;
  5761. for (auto& interface : typeInstance->mInterfaces)
  5762. {
  5763. SizedArray<BfIRValue, 8> interfaceDataVals =
  5764. {
  5765. emptyValueType,
  5766. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  5767. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  5768. GetConstValue(interface.mStartVirtualIdx, intType),
  5769. };
  5770. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  5771. interfaces.push_back(interfaceData);
  5772. if (!mIsComptimeModule)
  5773. {
  5774. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5775. {
  5776. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  5777. if (ifaceMethodGroup->mExplicitlyReflected)
  5778. {
  5779. wantsIfaceMethods = true;
  5780. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  5781. while (tableIdx >= wantsIfaceMethod.size())
  5782. wantsIfaceMethod.Add(false);
  5783. wantsIfaceMethod[tableIdx] = true;
  5784. }
  5785. }
  5786. }
  5787. }
  5788. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  5789. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  5790. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  5791. interfaceDataConst, "interfaces." + typeDataName);
  5792. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  5793. interfaceCount = (int)interfaces.size();
  5794. }
  5795. BfIRValue interfaceMethodTable;
  5796. int ifaceMethodTableSize = 0;
  5797. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  5798. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  5799. {
  5800. SizedArray<BfIRValue, 16> methods;
  5801. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  5802. {
  5803. BfIRValue funcVal = voidPtrNull;
  5804. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  5805. {
  5806. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  5807. if (!methodEntry.mMethodRef.IsNull())
  5808. {
  5809. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  5810. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  5811. (!methodInstance->mMethodDef->mIsAbstract))
  5812. {
  5813. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  5814. if (moduleMethodInstance.mFunc)
  5815. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5816. }
  5817. }
  5818. }
  5819. methods.Add(funcVal);
  5820. }
  5821. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  5822. methods.pop_back();
  5823. if (!methods.IsEmpty())
  5824. {
  5825. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  5826. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  5827. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5828. methodDataConst, "imethods." + typeDataName);
  5829. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  5830. ifaceMethodTableSize = (int)methods.size();
  5831. }
  5832. }
  5833. if (!interfaceMethodTable)
  5834. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5835. /////
  5836. int underlyingType = 0;
  5837. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5838. {
  5839. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5840. }
  5841. int outerTypeId = 0;
  5842. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  5843. if (outerType != NULL)
  5844. {
  5845. outerTypeId = outerType->mTypeId;
  5846. }
  5847. //
  5848. BfIRValue customAttrDataPtr;
  5849. if (customAttrs.size() > 0)
  5850. {
  5851. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5852. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  5853. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5854. customAttrsConst, "customAttrs." + typeDataName);
  5855. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5856. }
  5857. else
  5858. {
  5859. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5860. }
  5861. SizedArray<BfIRValue, 32> typeDataVals =
  5862. {
  5863. typeData,
  5864. castedClassVData, // mTypeClassVData
  5865. typeNameConst, // mName
  5866. namespaceConst, // mNamespace
  5867. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5868. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5869. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5870. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5871. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5872. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5873. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5874. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5875. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5876. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  5877. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  5878. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5879. GetConstValue(0, shortType), // mPropertyDataCount
  5880. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5881. interfaceDataPtr, // mInterfaceDataPtr
  5882. interfaceMethodTable, // mInterfaceMethodTable
  5883. methodDataPtr, // mMethodDataPtr
  5884. voidPtrNull, // mPropertyDataPtr
  5885. fieldDataPtr, // mFieldDataPtr
  5886. customAttrDataPtr, // mCustomAttrDataPtr
  5887. };
  5888. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5889. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  5890. if (!needsTypeData)
  5891. {
  5892. // No need for anything beyond typeInstanceData
  5893. }
  5894. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5895. {
  5896. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5897. SizedArray<BfIRValue, 4> unspecializedData =
  5898. {
  5899. typeInstanceData,
  5900. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5901. };
  5902. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5903. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5904. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  5905. }
  5906. else if (typeInstance->IsGenericTypeInstance())
  5907. {
  5908. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5909. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5910. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5911. SizedArray<BfIRValue, 4> resolvedTypes;
  5912. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  5913. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5914. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5915. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5916. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5917. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  5918. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5919. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5920. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5921. SizedArray<BfIRValue, 3> specGenericData =
  5922. {
  5923. typeInstanceData,
  5924. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5925. resovledTypesPtr, // mFieldDataPtr
  5926. };
  5927. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5928. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  5929. if (typeInstance->IsArray())
  5930. {
  5931. auto arrayType = (BfArrayType*)typeInstance;
  5932. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  5933. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5934. SizedArray<BfIRValue, 4> arrayData =
  5935. {
  5936. typeInstanceData,
  5937. GetConstValue(elementType->mSize, intType), // mElementSize
  5938. GetConstValue(1, byteType), // mRank
  5939. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5940. };
  5941. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5942. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5943. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  5944. }
  5945. }
  5946. BfIRValue typeDataVar;
  5947. if (needsTypeData)
  5948. {
  5949. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5950. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5951. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5952. if (mBfIRBuilder->DbgHasInfo())
  5953. {
  5954. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5955. }
  5956. }
  5957. else
  5958. {
  5959. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5960. }
  5961. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5962. mTypeDataRefs[typeInstance] = typeDataVar;
  5963. if ((!mIsComptimeModule) && (classVDataVar))
  5964. {
  5965. BF_ASSERT(!classVDataName.IsEmpty());
  5966. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5967. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5968. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  5969. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5970. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5971. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5972. else
  5973. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5974. if (mBfIRBuilder->DbgHasInfo())
  5975. {
  5976. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5977. BfType* voidPtrType = CreatePointerType(voidType);
  5978. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5979. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5980. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  5981. }
  5982. }
  5983. return typeDataVar;
  5984. }
  5985. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5986. {
  5987. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  5988. return value;
  5989. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5990. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5991. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5992. }
  5993. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5994. {
  5995. // Note: this is not just for perf, it fixes a field var-type resolution issue
  5996. if (mBfIRBuilder->mIgnoreWrites)
  5997. return;
  5998. if (mIsComptimeModule)
  5999. return;
  6000. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6001. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6002. // When we access classes with static constructors FROM a static constructor,
  6003. // we call that other class's static constructor first. Recursion cannot occur, since
  6004. // we simply ignore subsequent attempts to re-enter the constructor
  6005. if (!typeInstance->mHasStaticInitMethod)
  6006. return;
  6007. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6008. return;
  6009. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6010. return;
  6011. auto checkTypeDef = typeInstance->mTypeDef;
  6012. checkTypeDef->PopulateMemberSets();
  6013. BfMethodDef* nextMethodDef = NULL;
  6014. BfMemberSetEntry* entry;
  6015. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6016. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6017. while (nextMethodDef != NULL)
  6018. {
  6019. auto checkMethod = nextMethodDef;
  6020. nextMethodDef = nextMethodDef->mNextWithSameName;
  6021. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6022. if (methodModule)
  6023. {
  6024. auto methodInstance = methodModule.mMethodInstance;
  6025. if ((methodInstance != NULL) &&
  6026. (methodInstance->mMethodDef->mIsStatic) &&
  6027. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6028. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6029. {
  6030. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6031. break;
  6032. }
  6033. }
  6034. }
  6035. }
  6036. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6037. {
  6038. auto methodOwner = methodInstance->GetOwner();
  6039. auto methodDef = methodInstance->mMethodDef;
  6040. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6041. if (!methodDef->mIsExtern)
  6042. return BfIRFunction();
  6043. if (methodInstance->GetCustomAttributes() == NULL)
  6044. return BfIRFunction();
  6045. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6046. {
  6047. String typeName = TypeToString(customAttribute.mType);
  6048. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6049. {
  6050. methodInstance->mIsIntrinsic = true;
  6051. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6052. String error;
  6053. if ((constant != NULL) && (constant->mTypeCode = BfTypeCode_StringId))
  6054. {
  6055. int stringId = constant->mInt32;
  6056. auto entry = mContext->mStringObjectIdMap[stringId];
  6057. String intrinName = entry.mString;
  6058. // if (intrinName.StartsWith(":"))
  6059. // {
  6060. // SizedArray<BfIRType, 2> paramTypes;
  6061. // for (auto& param : methodInstance->mParams)
  6062. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6063. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6064. // }
  6065. // else
  6066. {
  6067. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6068. if (intrinId != -1)
  6069. {
  6070. if (intrinId == BfIRIntrinsic_Malloc)
  6071. {
  6072. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6073. }
  6074. else if (intrinId == BfIRIntrinsic_Free)
  6075. {
  6076. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6077. }
  6078. SizedArray<BfIRType, 2> paramTypes;
  6079. for (auto& param : methodInstance->mParams)
  6080. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6081. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6082. }
  6083. else if (reportFailure)
  6084. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6085. }
  6086. }
  6087. else if (reportFailure)
  6088. error = "Intrinsic name must be a constant string";
  6089. if (reportFailure)
  6090. {
  6091. Fail(error, customAttribute.mRef);
  6092. }
  6093. }
  6094. }
  6095. return BfIRFunction();
  6096. }
  6097. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6098. {
  6099. if (mBfIRBuilder->mIgnoreWrites)
  6100. return mBfIRBuilder->GetFakeFunction();
  6101. if (!mBuiltInFuncs[(int)funcTypeId])
  6102. {
  6103. SizedArray<BfIRType, 4> paramTypes;
  6104. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6105. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6106. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6107. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6108. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6109. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6110. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6111. BfIRFunctionType funcType;
  6112. BfIRFunction func;
  6113. switch (funcTypeId)
  6114. {
  6115. case BfBuiltInFuncType_PrintF:
  6116. paramTypes.Add(nullPtrType);
  6117. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6118. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6119. break;
  6120. case BfBuiltInFuncType_Malloc:
  6121. {
  6122. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6123. {
  6124. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6125. }
  6126. else
  6127. {
  6128. String funcName = mCompiler->mOptions.mMallocLinkName;
  6129. if (funcName.IsEmpty())
  6130. funcName = "malloc";
  6131. func = mBfIRBuilder->GetFunction(funcName);
  6132. if (!func)
  6133. {
  6134. paramTypes.clear();
  6135. paramTypes.push_back(intType);
  6136. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6137. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6138. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6139. }
  6140. }
  6141. }
  6142. break;
  6143. case BfBuiltInFuncType_Free:
  6144. {
  6145. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6146. {
  6147. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6148. }
  6149. else
  6150. {
  6151. String funcName = mCompiler->mOptions.mFreeLinkName;
  6152. if (funcName.IsEmpty())
  6153. funcName = "free";
  6154. func = mBfIRBuilder->GetFunction(funcName);
  6155. if (!func)
  6156. {
  6157. paramTypes.clear();
  6158. paramTypes.push_back(nullPtrType);
  6159. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6160. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6161. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6162. }
  6163. }
  6164. }
  6165. break;
  6166. case BfBuiltInFuncType_LoadSharedLibraries:
  6167. paramTypes.clear();
  6168. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6169. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6170. break;
  6171. default: break;
  6172. }
  6173. mBuiltInFuncs[(int)funcTypeId] = func;
  6174. return func;
  6175. }
  6176. return mBuiltInFuncs[(int)funcTypeId];
  6177. }
  6178. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  6179. {
  6180. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6181. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6182. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  6183. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  6184. BfAutoComplete* bfAutocomplete = NULL;
  6185. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  6186. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  6187. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  6188. {
  6189. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  6190. {
  6191. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  6192. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  6193. {
  6194. String filter = nameNode->ToString();
  6195. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  6196. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  6197. if (nameIdx != 0)
  6198. {
  6199. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  6200. }
  6201. }
  6202. }
  6203. }
  6204. for (auto constraint : constraintDef->mConstraints)
  6205. {
  6206. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  6207. {
  6208. BfGenericOperatorConstraintInstance opConstraintInstance;
  6209. if (opConstraint->mLeftType != NULL)
  6210. {
  6211. if (bfAutocomplete != NULL)
  6212. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  6213. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces);
  6214. if (opConstraintInstance.mLeftType == NULL)
  6215. continue;
  6216. }
  6217. if (opConstraint->mRightType == NULL)
  6218. {
  6219. // We had a failure in parsing
  6220. continue;
  6221. }
  6222. if (opConstraint->mRightType != NULL)
  6223. {
  6224. if (bfAutocomplete != NULL)
  6225. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6226. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces);
  6227. if (opConstraintInstance.mRightType == NULL)
  6228. continue;
  6229. }
  6230. if (opConstraint->mOpToken == NULL)
  6231. {
  6232. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6233. continue;
  6234. }
  6235. if (opConstraint->mLeftType != NULL)
  6236. {
  6237. if (opConstraint->mRightType == NULL)
  6238. {
  6239. // Parse should have failed
  6240. continue;
  6241. }
  6242. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6243. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6244. {
  6245. Fail("Invalid binary operator", opConstraint->mOpToken);
  6246. continue;
  6247. }
  6248. }
  6249. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6250. {
  6251. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6252. }
  6253. else
  6254. {
  6255. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6256. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6257. {
  6258. Fail("Invalid unary operator", opConstraint->mOpToken);
  6259. continue;
  6260. }
  6261. }
  6262. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6263. continue;
  6264. }
  6265. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6266. if (bfAutocomplete != NULL)
  6267. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6268. //TODO: Constraints may refer to other generic params (of either type or method)
  6269. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  6270. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  6271. if (isUnspecialized)
  6272. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  6273. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, resolveFlags);
  6274. if (constraintType != NULL)
  6275. {
  6276. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6277. {
  6278. bool isValidTypeCode = false;
  6279. BfTypeCode typeCode = BfTypeCode_None;
  6280. if (constraintType->IsTypedPrimitive())
  6281. {
  6282. auto underlyingType = constraintType->GetUnderlyingType();
  6283. if (underlyingType->IsPrimitiveType())
  6284. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6285. }
  6286. if (constraintType->IsPrimitiveType())
  6287. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6288. switch (typeCode)
  6289. {
  6290. case BfTypeCode_Int8:
  6291. case BfTypeCode_UInt8:
  6292. case BfTypeCode_Int16:
  6293. case BfTypeCode_UInt16:
  6294. case BfTypeCode_Int32:
  6295. case BfTypeCode_UInt32:
  6296. case BfTypeCode_Int64:
  6297. case BfTypeCode_UInt64:
  6298. case BfTypeCode_IntPtr:
  6299. case BfTypeCode_UIntPtr:
  6300. case BfTypeCode_IntUnknown:
  6301. case BfTypeCode_UIntUnknown:
  6302. case BfTypeCode_Float:
  6303. case BfTypeCode_Double:
  6304. case BfTypeCode_Char8:
  6305. case BfTypeCode_Char16:
  6306. case BfTypeCode_Char32:
  6307. isValidTypeCode = true;
  6308. break;
  6309. default: break;
  6310. }
  6311. if (isValidTypeCode)
  6312. {
  6313. genericParamInstance->mTypeConstraint = constraintType;
  6314. }
  6315. else
  6316. {
  6317. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6318. }
  6319. }
  6320. else
  6321. {
  6322. bool checkEquality = false;
  6323. if (constraintType->IsVar())
  6324. {
  6325. // From a `comptype` generic undef resolution. Ignore.
  6326. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_ComptypeExpr;
  6327. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  6328. continue;
  6329. }
  6330. else if (constraintType->IsPrimitiveType())
  6331. {
  6332. if (isUnspecialized)
  6333. {
  6334. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6335. continue;
  6336. }
  6337. checkEquality = true;
  6338. }
  6339. if (constraintType->IsArray())
  6340. {
  6341. if (isUnspecialized)
  6342. {
  6343. 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);
  6344. continue;
  6345. }
  6346. checkEquality = true;
  6347. }
  6348. if (constraintType->IsGenericParam())
  6349. {
  6350. continue;
  6351. }
  6352. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6353. {
  6354. if (isUnspecialized)
  6355. {
  6356. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6357. continue;
  6358. }
  6359. checkEquality = true;
  6360. }
  6361. if (checkEquality)
  6362. {
  6363. genericParamInstance->mTypeConstraint = constraintType;
  6364. }
  6365. else if (constraintType->IsInterface())
  6366. {
  6367. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6368. }
  6369. else
  6370. {
  6371. auto constraintTypeInst = constraintType->ToTypeInstance();
  6372. if (genericParamInstance->mTypeConstraint != NULL)
  6373. {
  6374. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6375. {
  6376. // Allow more specific type
  6377. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6378. }
  6379. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6380. {
  6381. // Silently ignore less-specific type
  6382. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  6383. {
  6384. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  6385. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  6386. }
  6387. }
  6388. else
  6389. {
  6390. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  6391. return;
  6392. }
  6393. }
  6394. else
  6395. genericParamInstance->mTypeConstraint = constraintType;
  6396. }
  6397. }
  6398. }
  6399. }
  6400. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  6401. (genericParamInstance->mTypeConstraint == NULL))
  6402. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  6403. }
  6404. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  6405. {
  6406. if (genericParamSource.mMethodInstance != NULL)
  6407. {
  6408. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  6409. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(methodInst, NULL);
  6410. return MethodToString(genericParamSource.mMethodInstance);
  6411. }
  6412. else
  6413. {
  6414. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  6415. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  6416. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  6417. return TypeToString(typeInst);
  6418. }
  6419. }
  6420. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  6421. {
  6422. Array<String> methodParamNameOverrides;
  6423. auto _TypeToString = [&](BfType* type)
  6424. {
  6425. if (genericParamSource.mMethodInstance != NULL)
  6426. {
  6427. if (methodParamNameOverrides.IsEmpty())
  6428. {
  6429. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  6430. methodParamNameOverrides.Add(genericParam->mName);
  6431. }
  6432. return TypeToString(type, &methodParamNameOverrides);
  6433. }
  6434. return TypeToString(type);
  6435. };
  6436. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  6437. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  6438. BfType* origCheckArgType = checkArgType;
  6439. if (origCheckArgType->IsRef())
  6440. origCheckArgType = origCheckArgType->GetUnderlyingType();
  6441. bool argMayBeReferenceType = false;
  6442. int checkGenericParamFlags = 0;
  6443. if (checkArgType->IsGenericParam())
  6444. {
  6445. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  6446. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  6447. if (checkGenericParamInst->mTypeConstraint != NULL)
  6448. checkArgType = checkGenericParamInst->mTypeConstraint;
  6449. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  6450. {
  6451. argMayBeReferenceType = false;
  6452. }
  6453. else
  6454. {
  6455. argMayBeReferenceType = true;
  6456. }
  6457. }
  6458. if (checkArgType->IsObjectOrInterface())
  6459. argMayBeReferenceType = true;
  6460. BfTypeInstance* typeConstraintInst = NULL;
  6461. if (genericParamInst->mTypeConstraint != NULL)
  6462. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  6463. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  6464. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  6465. {
  6466. if (!ignoreErrors)
  6467. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  6468. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6469. return false;
  6470. }
  6471. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  6472. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  6473. {
  6474. if (!ignoreErrors)
  6475. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  6476. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6477. return false;
  6478. }
  6479. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  6480. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  6481. {
  6482. if (!ignoreErrors)
  6483. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  6484. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6485. return false;
  6486. }
  6487. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  6488. {
  6489. bool isEnum = checkArgType->IsEnum();
  6490. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  6491. isEnum = true;
  6492. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  6493. {
  6494. if (!ignoreErrors)
  6495. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  6496. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6497. return false;
  6498. }
  6499. }
  6500. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  6501. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  6502. {
  6503. if (!ignoreErrors)
  6504. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  6505. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6506. return false;
  6507. }
  6508. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  6509. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  6510. {
  6511. if (!ignoreErrors)
  6512. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  6513. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6514. return false;
  6515. }
  6516. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6517. {
  6518. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  6519. {
  6520. if (!ignoreErrors)
  6521. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  6522. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6523. return false;
  6524. }
  6525. }
  6526. else
  6527. {
  6528. if (checkArgType->IsConstExprValue())
  6529. {
  6530. if (!ignoreErrors)
  6531. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  6532. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6533. return false;
  6534. }
  6535. }
  6536. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6537. {
  6538. bool canDelete = false;
  6539. if (checkArgType->IsPointer())
  6540. canDelete = true;
  6541. else if (checkArgType->IsObjectOrInterface())
  6542. canDelete = true;
  6543. else if ((checkGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6544. canDelete = true;
  6545. if (!canDelete)
  6546. {
  6547. if (!ignoreErrors)
  6548. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  6549. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6550. return false;
  6551. }
  6552. }
  6553. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  6554. {
  6555. bool canAlloc = false;
  6556. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  6557. {
  6558. if (checkTypeInst->IsObjectOrStruct())
  6559. {
  6560. checkTypeInst->mTypeDef->PopulateMemberSets();
  6561. BfMemberSetEntry* entry = NULL;
  6562. BfMethodDef* checkMethodDef = NULL;
  6563. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  6564. if (entry != NULL)
  6565. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  6566. bool hadProtected = false;
  6567. while (checkMethodDef != NULL)
  6568. {
  6569. if (checkMethodDef->mProtection == BfProtection_Public)
  6570. {
  6571. canAlloc = true;
  6572. break;
  6573. }
  6574. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  6575. hadProtected = true;
  6576. checkMethodDef = checkMethodDef->mNextWithSameName;
  6577. }
  6578. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  6579. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  6580. }
  6581. }
  6582. else
  6583. {
  6584. // Any primitive types and stuff can be allocated
  6585. canAlloc = true;
  6586. }
  6587. if (!canAlloc)
  6588. {
  6589. if (!ignoreErrors)
  6590. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  6591. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6592. return false;
  6593. }
  6594. }
  6595. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  6596. return true;
  6597. if (checkArgType->IsPointer())
  6598. {
  6599. auto ptrType = (BfPointerType*)checkArgType;
  6600. checkArgType = ptrType->mElementType;
  6601. }
  6602. if (genericParamInst->mTypeConstraint != NULL)
  6603. {
  6604. bool constraintMatched = false;
  6605. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6606. {
  6607. if (checkArgType->IsConstExprValue())
  6608. {
  6609. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  6610. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  6611. {
  6612. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  6613. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  6614. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  6615. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  6616. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  6617. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  6618. {
  6619. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  6620. {
  6621. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6622. {
  6623. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  6624. {
  6625. if (!ignoreErrors)
  6626. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6627. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6628. return false;
  6629. }
  6630. }
  6631. else
  6632. {
  6633. if (!ignoreErrors)
  6634. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6635. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6636. return false;
  6637. }
  6638. }
  6639. else
  6640. {
  6641. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6642. {
  6643. char valStr[64];
  6644. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  6645. if (!ignoreErrors)
  6646. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6647. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6648. return false;
  6649. }
  6650. }
  6651. }
  6652. }
  6653. }
  6654. }
  6655. else
  6656. {
  6657. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  6658. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  6659. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6660. if (convCheckConstraint == NULL)
  6661. return false;
  6662. if (((checkArgType->IsMethodRef()) || (checkArgType->IsFunction())) && (convCheckConstraint->IsDelegate()))
  6663. {
  6664. BfMethodInstance* checkMethodInstance;
  6665. if (checkArgType->IsMethodRef())
  6666. {
  6667. auto methodRefType = (BfMethodRefType*)checkArgType;
  6668. checkMethodInstance = methodRefType->mMethodRef;
  6669. }
  6670. else
  6671. {
  6672. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  6673. }
  6674. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  6675. BfExprEvaluator exprEvaluator(this);
  6676. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  6677. constraintMatched = true;
  6678. }
  6679. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  6680. {
  6681. constraintMatched = true;
  6682. }
  6683. else if (origCheckArgType->IsWrappableType())
  6684. {
  6685. if (origCheckArgType->IsSizedArray())
  6686. {
  6687. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  6688. if (convCheckConstraint->IsGenericTypeInstance())
  6689. {
  6690. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  6691. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  6692. {
  6693. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  6694. {
  6695. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  6696. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  6697. constraintMatched = true;
  6698. }
  6699. }
  6700. }
  6701. }
  6702. if (!constraintMatched)
  6703. {
  6704. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6705. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  6706. constraintMatched = true;
  6707. }
  6708. }
  6709. if (!constraintMatched)
  6710. {
  6711. if (!ignoreErrors)
  6712. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  6713. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  6714. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  6715. return false;
  6716. }
  6717. }
  6718. }
  6719. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  6720. {
  6721. BfType* convCheckConstraint = checkConstraint;
  6722. if (convCheckConstraint->IsUnspecializedType())
  6723. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6724. if (convCheckConstraint == NULL)
  6725. return false;
  6726. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  6727. bool implementsInterface = false;
  6728. if (origCheckArgType != checkArgType)
  6729. {
  6730. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  6731. }
  6732. if (!implementsInterface)
  6733. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  6734. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  6735. {
  6736. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6737. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6738. implementsInterface = true;
  6739. }
  6740. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  6741. {
  6742. auto underlyingType = origCheckArgType->GetUnderlyingType();
  6743. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  6744. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6745. implementsInterface = true;
  6746. }
  6747. if (!implementsInterface)
  6748. {
  6749. if (!ignoreErrors)
  6750. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  6751. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  6752. return false;
  6753. }
  6754. }
  6755. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  6756. {
  6757. auto leftType = checkOpConstraint.mLeftType;
  6758. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  6759. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  6760. if (leftType != NULL)
  6761. leftType = FixIntUnknown(leftType);
  6762. auto rightType = checkOpConstraint.mRightType;
  6763. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  6764. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  6765. if (rightType != NULL)
  6766. rightType = FixIntUnknown(rightType);
  6767. BfConstraintState constraintSet;
  6768. constraintSet.mPrevState = mContext->mCurConstraintState;
  6769. constraintSet.mGenericParamInstance = genericParamInst;
  6770. constraintSet.mLeftType = leftType;
  6771. constraintSet.mRightType = rightType;
  6772. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  6773. if (!CheckConstraintState(NULL))
  6774. return false;
  6775. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  6776. {
  6777. BfExprEvaluator exprEvaluator(this);
  6778. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  6779. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6780. //
  6781. {
  6782. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6783. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6784. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  6785. }
  6786. if ((!exprEvaluator.mResult) ||
  6787. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  6788. {
  6789. if (!ignoreErrors)
  6790. {
  6791. if (genericParamInst->mExternType != NULL)
  6792. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  6793. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  6794. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6795. ), checkArgTypeRef);
  6796. else
  6797. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  6798. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6799. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6800. ), checkArgTypeRef);
  6801. }
  6802. return false;
  6803. }
  6804. }
  6805. else
  6806. {
  6807. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6808. StringT<128> failedOpName;
  6809. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  6810. {
  6811. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6812. failedOpName = "implicit conversion from '";
  6813. }
  6814. else
  6815. {
  6816. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6817. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6818. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  6819. {
  6820. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6821. failedOpName = "explicit conversion from '";
  6822. }
  6823. else
  6824. {
  6825. BfExprEvaluator exprEvaluator(this);
  6826. exprEvaluator.mResult = rightValue;
  6827. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  6828. if ((!exprEvaluator.mResult) ||
  6829. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  6830. {
  6831. failedOpName += "unary operation '";
  6832. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  6833. }
  6834. }
  6835. }
  6836. if (!failedOpName.IsEmpty())
  6837. {
  6838. if (!ignoreErrors)
  6839. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  6840. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6841. failedOpName.c_str(), TypeToString(rightType).c_str()
  6842. ), checkArgTypeRef);
  6843. return false;
  6844. }
  6845. }
  6846. }
  6847. return true;
  6848. }
  6849. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  6850. {
  6851. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  6852. {
  6853. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  6854. return genericParamType;
  6855. }
  6856. auto genericParamType = new BfGenericParamType();
  6857. genericParamType->mContext = mContext;
  6858. genericParamType->mGenericParamKind = paramKind;
  6859. genericParamType->mGenericParamIdx = paramIdx;
  6860. PopulateType(genericParamType);
  6861. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  6862. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  6863. BfResolvedTypeSet::LookupContext lookupCtx;
  6864. lookupCtx.mModule = this;
  6865. BfResolvedTypeSet::Entry* typeEntry = NULL;
  6866. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  6867. BF_ASSERT(inserted);
  6868. typeEntry->mValue = genericParamType;
  6869. return genericParamType;
  6870. }
  6871. static int sValueFromExprIdx = 0;
  6872. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  6873. {
  6874. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  6875. if ((result) && (!ignoreNullable))
  6876. {
  6877. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  6878. //TODO: Make this work, needed for 'void' and such
  6879. BfType* nullableType = NULL;
  6880. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  6881. {
  6882. BfTypeVector typeVec;
  6883. typeVec.push_back(result.mType);
  6884. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  6885. BF_ASSERT(nullableType != NULL);
  6886. }
  6887. // Go back to start and do any setup we need
  6888. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6889. BfTypedValue nullableTypedValue;
  6890. if (nullableType != NULL)
  6891. {
  6892. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  6893. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  6894. GetConstValue(nullableType->mSize), nullableType->mAlign);
  6895. }
  6896. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6897. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  6898. mBfIRBuilder->SetInsertPoint(notNullBB);
  6899. result = LoadValue(result);
  6900. if (nullableTypedValue)
  6901. {
  6902. auto elementType = nullableType->GetUnderlyingType();
  6903. if (elementType->IsVar())
  6904. {
  6905. // Do nothing
  6906. }
  6907. else if (elementType->IsValuelessType())
  6908. {
  6909. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  6910. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6911. }
  6912. else
  6913. {
  6914. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  6915. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  6916. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  6917. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6918. }
  6919. result = nullableTypedValue;
  6920. }
  6921. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6922. AddBasicBlock(pendingNullCond->mDoneBB);
  6923. if (nullableType == NULL)
  6924. {
  6925. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  6926. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  6927. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  6928. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  6929. {
  6930. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  6931. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  6932. }
  6933. result.mValue = phi;
  6934. }
  6935. }
  6936. else
  6937. {
  6938. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6939. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6940. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6941. AddBasicBlock(pendingNullCond->mDoneBB);
  6942. }
  6943. delete mCurMethodState->mPendingNullConditional;
  6944. mCurMethodState->mPendingNullConditional = NULL;
  6945. return result;
  6946. }
  6947. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  6948. {
  6949. BfScopeData newScope;
  6950. newScope.mOuterIsConditional = true;
  6951. newScope.mAllowTargeting = false;
  6952. mCurMethodState->AddScope(&newScope);
  6953. NewScopeState(true, false);
  6954. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  6955. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  6956. RestoreScopeState();
  6957. }
  6958. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6959. {
  6960. //
  6961. {
  6962. BP_ZONE("CreateValueFromExpression:CheckStack");
  6963. StackHelper stackHelper;
  6964. if (!stackHelper.CanStackExpand(64 * 1024))
  6965. {
  6966. BfTypedValue result;
  6967. if (!stackHelper.Execute([&]()
  6968. {
  6969. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6970. }))
  6971. {
  6972. Fail("Expression too complex to compile", expr);
  6973. }
  6974. return result;
  6975. }
  6976. }
  6977. BP_ZONE("BfModule::CreateValueFromExpression");
  6978. if (outOrigType != NULL)
  6979. *outOrigType = NULL;
  6980. exprEvaluator.mExpectingType = wantTypeRef;
  6981. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  6982. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  6983. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  6984. {
  6985. EvaluateWithNewScope(exprEvaluator, expr, flags);
  6986. }
  6987. else
  6988. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6989. if (!exprEvaluator.mResult)
  6990. {
  6991. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  6992. return exprEvaluator.mResult;
  6993. if (!mCompiler->mPassInstance->HasFailed())
  6994. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  6995. return BfTypedValue();
  6996. }
  6997. auto typedVal = exprEvaluator.mResult;
  6998. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6999. {
  7000. BF_ASSERT(typedVal.mType->IsGenericParam());
  7001. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7002. bool handled = false;
  7003. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7004. {
  7005. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7006. if (genericTypeConstraint != NULL)
  7007. {
  7008. auto primType = genericTypeConstraint->ToPrimitiveType();
  7009. if (primType != NULL)
  7010. {
  7011. BfTypedValue result;
  7012. result.mKind = BfTypedValueKind_Value;
  7013. result.mType = genericTypeConstraint;
  7014. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(primType));
  7015. typedVal = result;
  7016. handled = true;
  7017. }
  7018. }
  7019. }
  7020. if (!handled)
  7021. {
  7022. //Fail("Only const generic parameters can be used as values", expr);
  7023. AssertErrorState();
  7024. return BfTypedValue();
  7025. }
  7026. }
  7027. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7028. FixIntUnknown(typedVal);
  7029. if (!mBfIRBuilder->mIgnoreWrites)
  7030. FixValueActualization(typedVal);
  7031. exprEvaluator.CheckResultForReading(typedVal);
  7032. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7033. {
  7034. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7035. {
  7036. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7037. bool allowRef = false;
  7038. BfExpression* checkExpr = expr;
  7039. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7040. checkExpr = parenExpr->mExpression;
  7041. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7042. {
  7043. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7044. allowRef = true;
  7045. }
  7046. if (!allowRef)
  7047. typedVal = RemoveRef(typedVal);
  7048. }
  7049. }
  7050. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7051. {
  7052. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7053. {
  7054. BF_ASSERT(!typedVal.mValue.IsFake());
  7055. }
  7056. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7057. }
  7058. if (wantTypeRef != NULL)
  7059. {
  7060. if (outOrigType != NULL)
  7061. *outOrigType = typedVal.mType;
  7062. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7063. {
  7064. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7065. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7066. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7067. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7068. if (!typedVal)
  7069. return typedVal;
  7070. }
  7071. if (exprEvaluator.mIsVolatileReference)
  7072. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7073. }
  7074. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7075. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7076. return typedVal;
  7077. }
  7078. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7079. {
  7080. BfExprEvaluator exprEvaluator(this);
  7081. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7082. }
  7083. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7084. {
  7085. BfExprEvaluator exprEvaluator(this);
  7086. exprEvaluator.Evaluate(expr);
  7087. if (!exprEvaluator.mResult)
  7088. {
  7089. Fail("Invalid expression type", expr);
  7090. return BfTypedValue();
  7091. }
  7092. if (!exprEvaluator.mResult.IsAddr())
  7093. {
  7094. Fail("Cannot assign to value", expr);
  7095. return BfTypedValue();
  7096. }
  7097. return exprEvaluator.mResult;
  7098. }
  7099. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  7100. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  7101. {
  7102. auto typeInstance = typedValue.mType->ToTypeInstance();
  7103. if (zeroMemory)
  7104. {
  7105. int zeroAlign = typedValue.mType->mAlign;
  7106. if (typeInstance != NULL)
  7107. zeroAlign = typeInstance->mInstAlign;
  7108. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  7109. }
  7110. if (!typedValue.mType->IsObject())
  7111. {
  7112. return;
  7113. }
  7114. if ((scopeData == NULL) && (mCurMethodState != NULL))
  7115. return; // Handled in heap alloc funcs
  7116. auto typeDef = typeInstance->mTypeDef;
  7117. mBfIRBuilder->PopulateType(typedValue.mType);
  7118. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  7119. bool isAutocomplete = mCompiler->IsAutocomplete();
  7120. BfIRValue vDataRef;
  7121. if (!isAutocomplete)
  7122. {
  7123. vDataRef = GetClassVDataPtr(typeInstance);
  7124. }
  7125. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7126. auto ptrType = CreatePointerType(i8Type);
  7127. auto ptrPtrType = CreatePointerType(ptrType);
  7128. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  7129. PopulateType(ptrType, BfPopulateType_Declaration);
  7130. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  7131. if (!isAutocomplete)
  7132. {
  7133. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7134. {
  7135. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7136. SizedArray<BfIRValue, 4> llvmArgs;
  7137. llvmArgs.push_back(objectPtr);
  7138. llvmArgs.push_back(vDataRef);
  7139. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  7140. if (objectStackInitMethod)
  7141. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  7142. }
  7143. else
  7144. {
  7145. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  7146. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  7147. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7148. }
  7149. }
  7150. }
  7151. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  7152. {
  7153. BfIRValue result;
  7154. BfType* ptrType;
  7155. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  7156. ptrType = type;
  7157. else
  7158. ptrType = CreatePointerType(type);
  7159. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  7160. {
  7161. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7162. SizedArray<BfExpression*, 2> argExprs;
  7163. BfTypedValueExpression typedValueExpr;
  7164. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  7165. typedValueExpr.mRefNode = refNode;
  7166. argExprs.push_back(&typedValueExpr);
  7167. BfTypedValueExpression appendSizeValueExpr;
  7168. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  7169. appendSizeValueExpr.mRefNode = refNode;
  7170. argExprs.push_back(&appendSizeValueExpr);
  7171. BfExprEvaluator exprEvaluator(this);
  7172. BfTypedValue allocResult;
  7173. if (allocTarget.mScopedInvocationTarget != NULL)
  7174. {
  7175. SizedArray<BfTypeReference*, 2> genericArgs;
  7176. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  7177. allocResult = LoadValue(exprEvaluator.mResult);
  7178. }
  7179. else if (allocTarget.mCustomAllocator)
  7180. {
  7181. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7182. if (customTypeInst != NULL)
  7183. {
  7184. BfTypedValueExpression typeValueExpr;
  7185. String allocMethodName = "Alloc";
  7186. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  7187. {
  7188. allocMethodName = "AllocTyped";
  7189. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  7190. auto typeRefVal = CreateTypeDataRef(type);
  7191. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  7192. typeValueExpr.mRefNode = refNode;
  7193. argExprs.Insert(0, &typeValueExpr);
  7194. }
  7195. if (HasMixin(customTypeInst, allocMethodName, 2))
  7196. {
  7197. BfSizedArray<BfExpression*> argExprArr;
  7198. argExprArr.mSize = (int)argExprs.size();
  7199. argExprArr.mVals = &argExprs[0];
  7200. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  7201. allocResult = exprEvaluator.GetResult();
  7202. }
  7203. else
  7204. {
  7205. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7206. BfResolvedArgs argValues(&sizedArgExprs);
  7207. exprEvaluator.ResolveArgValues(argValues);
  7208. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  7209. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  7210. }
  7211. }
  7212. }
  7213. if (allocResult)
  7214. {
  7215. if (allocResult.mType->IsVoidPtr())
  7216. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  7217. else
  7218. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  7219. return result;
  7220. }
  7221. }
  7222. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  7223. return result;
  7224. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7225. {
  7226. BfIRValue allocData = GetDbgRawAllocData(type);
  7227. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  7228. SizedArray<BfIRValue, 2> llvmArgs;
  7229. llvmArgs.push_back(sizeValue);
  7230. llvmArgs.push_back(allocData);
  7231. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  7232. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7233. }
  7234. BfModuleMethodInstance moduleMethodInstance;
  7235. moduleMethodInstance = GetInternalMethod("Malloc");
  7236. SizedArray<BfIRValue, 1> llvmArgs;
  7237. llvmArgs.push_back(sizeValue);
  7238. auto func = moduleMethodInstance.mFunc;
  7239. if ((!func) || (func.IsFake()))
  7240. {
  7241. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  7242. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  7243. }
  7244. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7245. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7246. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7247. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7248. return result;
  7249. }
  7250. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7251. {
  7252. if (type->IsStruct())
  7253. {
  7254. auto typeInstance = type->ToTypeInstance();
  7255. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7256. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7257. }
  7258. else if (type->IsObjectOrInterface())
  7259. {
  7260. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7261. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7262. BF_ASSERT(moduleMethodInst.mFunc);
  7263. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7264. }
  7265. else
  7266. {
  7267. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7268. BfExprEvaluator exprEvaluator(this);
  7269. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7270. BfResolvedArg resolvedArg;
  7271. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7272. resolvedArgs.Add(resolvedArg);
  7273. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  7274. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7275. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7276. BF_ASSERT(moduleMethodInst.mFunc);
  7277. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7278. }
  7279. return BfIRValue();
  7280. }
  7281. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7282. {
  7283. BfIRValue allocDataValue;
  7284. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7285. return allocDataValue;
  7286. BfIRValue markFuncPtr;
  7287. if (type->WantsGCMarking())
  7288. markFuncPtr = GetMarkFuncPtr(type);
  7289. else
  7290. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7291. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7292. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7293. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7294. if (typeInstance == NULL)
  7295. {
  7296. typeInstance = GetWrappedStructType(type);
  7297. if (typeInstance != NULL)
  7298. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7299. }
  7300. if (typeInstance != NULL)
  7301. PopulateType(typeInstance);
  7302. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7303. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  7304. {
  7305. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7306. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7307. }
  7308. SizedArray<BfIRValue, 2> dataValues;
  7309. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  7310. dataValues.Add(typeDataRef);
  7311. dataValues.Add(markFuncPtr);
  7312. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  7313. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  7314. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  7315. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  7316. return allocDataValue;
  7317. }
  7318. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  7319. {
  7320. BP_ZONE("AllocFromType");
  7321. BfScopeData* scopeData = allocTarget.mScopeData;
  7322. BF_ASSERT(!type->IsVar());
  7323. auto typeInstance = type->ToTypeInstance();
  7324. if ((typeInstance == NULL) && (type->IsGenericParam()))
  7325. typeInstance = mContext->mBfObjectType;
  7326. bool isHeapAlloc = scopeData == NULL;
  7327. bool isScopeAlloc = scopeData != NULL;
  7328. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  7329. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  7330. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  7331. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  7332. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  7333. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  7334. {
  7335. BfPointerType* ptrType = CreatePointerType(type);
  7336. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  7337. return val;
  7338. }
  7339. if (typeInstance != NULL)
  7340. mBfIRBuilder->PopulateType(typeInstance);
  7341. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  7342. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  7343. {
  7344. return mBfIRBuilder->GetFakeVal();
  7345. }
  7346. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7347. BfIRValue sizeValue;
  7348. BfIRType allocType = mBfIRBuilder->MapType(type);
  7349. int allocSize = type->mSize;
  7350. int allocAlign = type->mAlign;
  7351. if (typeInstance != NULL)
  7352. {
  7353. if (!mBfIRBuilder->mIgnoreWrites)
  7354. typeInstance->mHasBeenInstantiated = true;
  7355. allocSize = typeInstance->mInstSize;
  7356. allocAlign = typeInstance->mInstAlign;
  7357. //if (typeInstance->IsEnum())
  7358. //allocType = typeInstance->mIRType;
  7359. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  7360. }
  7361. if (alignOverride != -1)
  7362. allocAlign = alignOverride;
  7363. // The "dynSize" cases:
  7364. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  7365. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  7366. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  7367. // though we'd expect their stack space to be released
  7368. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  7369. {
  7370. MarkDynStack(scopeData);
  7371. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7372. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  7373. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7374. BfType* voidPtrType = CreatePointerType(voidType);
  7375. if (!mCurMethodState->mDynStackRevIdx)
  7376. {
  7377. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  7378. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7379. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7380. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  7381. mBfIRBuilder->ClearDebugLocation(storeInst);
  7382. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7383. }
  7384. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  7385. auto bytePtrType = CreatePointerType(byteType);
  7386. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  7387. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  7388. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7389. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7390. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  7391. mBfIRBuilder->ClearDebugLocation(storeInst);
  7392. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  7393. mBfIRBuilder->ClearDebugLocation(storeInst);
  7394. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7395. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  7396. if (IsTargetingBeefBackend())
  7397. {
  7398. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  7399. // to ensure there isn't any register collision during looping is just to not allow it to
  7400. // bind to a register at all
  7401. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  7402. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  7403. }
  7404. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  7405. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  7406. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  7407. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  7408. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  7409. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  7410. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  7411. mBfIRBuilder->AddBlock(verCheckBB);
  7412. mBfIRBuilder->SetInsertPoint(verCheckBB);
  7413. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  7414. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  7415. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  7416. mBfIRBuilder->AddBlock(resizeBB);
  7417. mBfIRBuilder->SetInsertPoint(resizeBB);
  7418. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7419. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  7420. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  7421. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  7422. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  7423. mBfIRBuilder->CreateBr(endBB);
  7424. mBfIRBuilder->AddBlock(endBB);
  7425. mBfIRBuilder->SetInsertPoint(endBB);
  7426. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  7427. };
  7428. if (isScopeAlloc)
  7429. {
  7430. if (arraySize)
  7431. {
  7432. bool isConstantArraySize = arraySize.IsConst();
  7433. if (isRawArrayAlloc)
  7434. {
  7435. BfPointerType* ptrType = CreatePointerType(type);
  7436. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7437. {
  7438. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7439. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  7440. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  7441. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  7442. }
  7443. else
  7444. {
  7445. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7446. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  7447. if (!isDynAlloc)
  7448. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7449. else
  7450. {
  7451. MarkDynStack(scopeData);
  7452. SaveStackState(scopeData);
  7453. }
  7454. int typeSize = type->GetStride();
  7455. BfIRValue allocaInst;
  7456. BfIRValue result;
  7457. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  7458. {
  7459. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  7460. result = allocaInst;
  7461. }
  7462. else
  7463. {
  7464. if (typeInstance->IsStruct())
  7465. typeSize = typeInstance->GetInstStride();
  7466. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  7467. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  7468. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7469. auto ptrType = CreatePointerType(typeInstance);
  7470. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  7471. if (!isDynAlloc)
  7472. mBfIRBuilder->ClearDebugLocation(result);
  7473. }
  7474. if (!isDynAlloc)
  7475. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7476. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7477. if (!isDynAlloc)
  7478. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7479. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  7480. if (arraySize.IsConst())
  7481. {
  7482. auto constant = mBfIRBuilder->GetConstant(arraySize);
  7483. if (constant->mInt64 == 0)
  7484. noDtorCall = true;
  7485. }
  7486. if (!noDtorCall)
  7487. {
  7488. bool isConstSize = arraySize.IsConst();
  7489. BfIRBlock clearBlock;
  7490. BfIRBlock contBlock;
  7491. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  7492. if (wantsDeinit)
  7493. {
  7494. if (!isConstSize)
  7495. {
  7496. clearBlock = mBfIRBuilder->CreateBlock("clear");
  7497. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  7498. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  7499. mBfIRBuilder->AddBlock(clearBlock);
  7500. mBfIRBuilder->SetInsertPoint(clearBlock);
  7501. }
  7502. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7503. if (!isConstSize)
  7504. {
  7505. mBfIRBuilder->CreateBr(contBlock);
  7506. mBfIRBuilder->AddBlock(contBlock);
  7507. mBfIRBuilder->SetInsertPoint(contBlock);
  7508. }
  7509. }
  7510. }
  7511. return result;
  7512. }
  7513. }
  7514. else
  7515. {
  7516. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7517. {
  7518. // Generate and check new size
  7519. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7520. auto firstElementField = &arrayType->mFieldInstances.back();
  7521. int arrayClassSize = firstElementField->mDataOffset;
  7522. sizeValue = GetConstValue(arrayClassSize);
  7523. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7524. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7525. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  7526. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  7527. if (!noDtorCall)
  7528. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7529. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7530. return typedVal.mValue;
  7531. }
  7532. else
  7533. {
  7534. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7535. auto firstElementField = &arrayType->mFieldInstances.back();
  7536. if (!type->IsValuelessType())
  7537. {
  7538. int arrayClassSize = firstElementField->mDataOffset;
  7539. sizeValue = GetConstValue(arrayClassSize);
  7540. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7541. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7542. }
  7543. else
  7544. sizeValue = GetConstValue(arrayType->mInstSize);
  7545. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7546. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7547. if (!isDynAlloc)
  7548. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7549. else
  7550. {
  7551. MarkDynStack(scopeData);
  7552. SaveStackState(scopeData);
  7553. }
  7554. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  7555. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7556. if (!isDynAlloc)
  7557. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7558. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7559. if (!isDynAlloc)
  7560. mBfIRBuilder->SetInsertPoint(prevBlock);
  7561. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  7562. mBfIRBuilder->ClearDebugLocation_Last();
  7563. if (!noDtorCall)
  7564. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7565. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7566. return typedVal.mValue;
  7567. }
  7568. }
  7569. }
  7570. else if (appendSizeValue)
  7571. {
  7572. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  7573. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  7574. // use the "dynSize" version conservatively
  7575. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7576. {
  7577. // Generate and check new size
  7578. sizeValue = GetConstValue(typeInstance->mInstSize);
  7579. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7580. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  7581. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  7582. if (!noDtorCall)
  7583. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  7584. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7585. return typedVal.mValue;
  7586. }
  7587. else // stack alloc, unlooped, with append
  7588. {
  7589. sizeValue = GetConstValue(typeInstance->mInstSize);
  7590. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7591. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7592. bool wasDynAlloc = isDynAlloc;
  7593. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7594. if (!isDynAlloc)
  7595. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7596. else
  7597. {
  7598. MarkDynStack(scopeData);
  7599. SaveStackState(scopeData);
  7600. }
  7601. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  7602. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  7603. if (!isDynAlloc)
  7604. {
  7605. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7606. }
  7607. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7608. bool mayBeLarge = false;
  7609. if (sizeValue.IsConst())
  7610. {
  7611. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  7612. if (constantInt->mInt64 >= 4096)
  7613. mayBeLarge = true;
  7614. }
  7615. else
  7616. mayBeLarge = true;
  7617. if (((type->IsObject() && (!mayBeLarge))) ||
  7618. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7619. ((zeroMemory) && (!mayBeLarge)))
  7620. {
  7621. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7622. }
  7623. BfIRValue castedVal;
  7624. if (!isDynAlloc)
  7625. {
  7626. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7627. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7628. mBfIRBuilder->ClearDebugLocation(castedVal);
  7629. mBfIRBuilder->SetInsertPoint(prevBlock);
  7630. if (WantsLifetimes())
  7631. {
  7632. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7633. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7634. }
  7635. }
  7636. else
  7637. {
  7638. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7639. }
  7640. auto typedVal = BfTypedValue(castedVal, typeInstance);
  7641. if (!noDtorCall)
  7642. {
  7643. bool doCondAlloca = false;
  7644. if (!IsTargetingBeefBackend())
  7645. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  7646. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  7647. }
  7648. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7649. return typedVal.mValue;
  7650. }
  7651. }
  7652. else // "Normal" stack alloc
  7653. {
  7654. BF_ASSERT(!sizeValue);
  7655. //TODO: If sizeValue is a constant then do this in the head IR builder
  7656. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7657. if (!isLoopedAlloc)
  7658. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7659. else
  7660. {
  7661. MarkDynStack(scopeData);
  7662. SaveStackState(scopeData);
  7663. }
  7664. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  7665. if (!isLoopedAlloc)
  7666. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7667. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7668. bool mayBeLarge = allocSize >= 4096;
  7669. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  7670. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7671. ((zeroMemory) && (!mayBeLarge)))
  7672. {
  7673. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  7674. // and memset is always safe
  7675. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7676. }
  7677. auto typedVal = BfTypedValue(allocaInst, type);
  7678. if (!isLoopedAlloc)
  7679. {
  7680. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7681. mBfIRBuilder->SetInsertPoint(prevBlock);
  7682. if (WantsLifetimes())
  7683. {
  7684. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7685. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7686. }
  7687. }
  7688. if (!noDtorCall)
  7689. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7690. if (typeInstance != NULL)
  7691. {
  7692. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  7693. }
  7694. else
  7695. {
  7696. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  7697. }
  7698. return allocaInst;
  7699. }
  7700. }
  7701. else if (arraySize)
  7702. {
  7703. if (isRawArrayAlloc)
  7704. {
  7705. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7706. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  7707. }
  7708. else
  7709. {
  7710. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7711. typeInstance = arrayType;
  7712. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7713. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7714. appendSizeValue = elementDataSize;
  7715. if (!type->IsSizeAligned())
  7716. {
  7717. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  7718. }
  7719. }
  7720. }
  7721. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  7722. {
  7723. auto vDataRef = GetClassVDataPtr(typeInstance);
  7724. BfIRValue result;
  7725. bool isResultInitialized = false;
  7726. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7727. if (typeInstance->mTypeOptionsIdx != -1)
  7728. {
  7729. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7730. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7731. }
  7732. if (mIsComptimeModule)
  7733. stackCount = 0;
  7734. if (!sizeValue)
  7735. sizeValue = GetConstValue(typeInstance->mInstSize);
  7736. if (appendSizeValue)
  7737. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7738. BfIRValue origSizeValue = sizeValue;
  7739. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  7740. if (isAllocEx)
  7741. {
  7742. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  7743. if (prepareStackTraceMethod)
  7744. {
  7745. SizedArray<BfIRValue, 2> irArgs;
  7746. irArgs.Add(sizeValue);
  7747. irArgs.Add(GetConstValue(stackCount));
  7748. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  7749. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  7750. }
  7751. }
  7752. if (allocTarget.mCustomAllocator)
  7753. {
  7754. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7755. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  7756. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  7757. {
  7758. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7759. mBfIRBuilder->PopulateType(classVDataType);
  7760. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7761. mBfIRBuilder->PopulateType(typeInstType);
  7762. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  7763. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  7764. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  7765. BfTypedValueExpression typedValueExpr;
  7766. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  7767. typedValueExpr.mRefNode = allocTarget.mRefNode;
  7768. BfExprEvaluator exprEvaluator(this);
  7769. SizedArray<BfExpression*, 2> argExprs;
  7770. argExprs.push_back(&typedValueExpr);
  7771. BfTypedValueExpression sizeValueExpr;
  7772. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  7773. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  7774. argExprs.push_back(&sizeValueExpr);
  7775. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7776. BfResolvedArgs argValues(&sizedArgExprs);
  7777. exprEvaluator.ResolveArgValues(argValues);
  7778. exprEvaluator.mNoBind = true;
  7779. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  7780. if (allocResult)
  7781. {
  7782. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  7783. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  7784. else
  7785. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  7786. isResultInitialized = true;
  7787. }
  7788. }
  7789. }
  7790. bool wasAllocated = false;
  7791. if (!result)
  7792. {
  7793. if (hasCustomAllocator)
  7794. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  7795. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7796. {
  7797. SizedArray<BfIRValue, 4> llvmArgs;
  7798. llvmArgs.push_back(sizeValue);
  7799. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7800. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7801. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7802. wasAllocated = true;
  7803. }
  7804. }
  7805. if (result)
  7806. {
  7807. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7808. {
  7809. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  7810. SizedArray<BfIRValue, 4> llvmArgs;
  7811. llvmArgs.push_back(objectPtr);
  7812. llvmArgs.push_back(origSizeValue);
  7813. llvmArgs.push_back(vDataRef);
  7814. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  7815. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  7816. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  7817. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  7818. if (wasAllocated)
  7819. {
  7820. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  7821. auto bytePtrType = CreatePointerType(byteType);
  7822. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  7823. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  7824. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  7825. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  7826. }
  7827. }
  7828. else
  7829. {
  7830. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  7831. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7832. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  7833. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  7834. }
  7835. }
  7836. else
  7837. {
  7838. if ((mBfIRBuilder->mIgnoreWrites) ||
  7839. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  7840. return GetDefaultValue(typeInstance);
  7841. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7842. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  7843. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7844. {
  7845. SizedArray<BfIRValue, 4> llvmArgs;
  7846. llvmArgs.push_back(vData);
  7847. llvmArgs.push_back(sizeValue);
  7848. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  7849. llvmArgs.push_back(GetConstValue(stackCount));
  7850. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  7851. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  7852. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7853. }
  7854. else
  7855. {
  7856. SizedArray<BfIRValue, 4> llvmArgs;
  7857. llvmArgs.push_back(sizeValue);
  7858. BfIRFunction irFunc;
  7859. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7860. {
  7861. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  7862. irFunc = moduleMethodInstance.mFunc;
  7863. }
  7864. if (!irFunc)
  7865. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7866. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7867. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  7868. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  7869. if (mIsComptimeModule)
  7870. {
  7871. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  7872. }
  7873. mBfIRBuilder->CreateStore(vData, vdataPtr);
  7874. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7875. }
  7876. }
  7877. if ((zeroMemory) && (arraySize))
  7878. {
  7879. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7880. typeInstance = arrayType;
  7881. auto firstElementField = &arrayType->mFieldInstances.back();
  7882. int arrayClassSize = firstElementField->mDataOffset;
  7883. BfIRValue elementDataSize;
  7884. bool skipZero = false;
  7885. if (arraySize.IsConst())
  7886. {
  7887. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7888. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7889. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  7890. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  7891. if (constVal->mInt64 <= 0)
  7892. skipZero = true;
  7893. }
  7894. else
  7895. {
  7896. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  7897. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7898. }
  7899. if (!skipZero)
  7900. {
  7901. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7902. auto ptrType = CreatePointerType(i8Type);
  7903. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  7904. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  7905. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  7906. appendSizeValue = elementDataSize;
  7907. }
  7908. }
  7909. return result;
  7910. }
  7911. else
  7912. {
  7913. if (!sizeValue)
  7914. sizeValue = GetConstValue(allocSize);
  7915. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  7916. }
  7917. }
  7918. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  7919. {
  7920. if ((type == NULL) || (refNode == NULL))
  7921. return;
  7922. auto typeInstance = type->ToTypeInstance();
  7923. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  7924. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  7925. }
  7926. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  7927. {
  7928. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7929. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7930. }
  7931. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  7932. {
  7933. if (sizeMultiple == 0)
  7934. sizeMultiple = align;
  7935. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  7936. {
  7937. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  7938. {
  7939. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7940. BF_ASSERT(localVar->mName == "appendIdx");
  7941. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  7942. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7943. if (align > 1)
  7944. {
  7945. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7946. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7947. }
  7948. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  7949. }
  7950. else
  7951. {
  7952. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  7953. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  7954. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  7955. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7956. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7957. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  7958. }
  7959. }
  7960. if (mCurMethodState->mCurAppendAlign == 0)
  7961. mCurMethodState->mCurAppendAlign = sizeMultiple;
  7962. else
  7963. {
  7964. if (sizeMultiple % align == 0)
  7965. mCurMethodState->mCurAppendAlign = align;
  7966. else
  7967. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  7968. }
  7969. }
  7970. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  7971. {
  7972. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7973. BF_ASSERT(localVar->mName == "appendIdx");
  7974. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  7975. BfIRValue retValue;
  7976. BfTypeInstance* retTypeInstance = NULL;
  7977. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  7978. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  7979. if (arraySize)
  7980. {
  7981. if (isRawArrayAlloc)
  7982. {
  7983. EmitAppendAlign(type->mAlign);
  7984. BfPointerType* ptrType = CreatePointerType(type);
  7985. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7986. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7987. if (mSystem->mPtrSize != 4)
  7988. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7989. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7990. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7991. if (zeroMemory)
  7992. {
  7993. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  7994. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  7995. }
  7996. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  7997. }
  7998. else
  7999. {
  8000. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8001. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8002. auto firstElementField = &arrayType->mFieldInstances.back();
  8003. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8004. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8005. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8006. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8007. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8008. if (mSystem->mPtrSize != 4)
  8009. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8010. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8011. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8012. if (zeroMemory)
  8013. {
  8014. // Only zero out the actual elements
  8015. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8016. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8017. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8018. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8019. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8020. }
  8021. retTypeInstance = arrayType;
  8022. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8023. }
  8024. }
  8025. else
  8026. {
  8027. auto typeInst = type->ToTypeInstance();
  8028. BfIRValue sizeValue;
  8029. BfIRType toType;
  8030. if (typeInst != NULL)
  8031. {
  8032. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8033. sizeValue = GetConstValue(typeInst->mInstSize);
  8034. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8035. }
  8036. else
  8037. {
  8038. EmitAppendAlign(type->mAlign, type->mSize);
  8039. sizeValue = GetConstValue(type->mSize);
  8040. auto toPtrType = CreatePointerType(type);
  8041. toType = mBfIRBuilder->MapType(toPtrType);
  8042. }
  8043. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8044. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8045. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8046. retTypeInstance = typeInst;
  8047. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8048. }
  8049. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  8050. {
  8051. mBfIRBuilder->PopulateType(retTypeInstance);
  8052. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  8053. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  8054. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  8055. auto curThis = GetThis();
  8056. BfIRValue newFlags;
  8057. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8058. {
  8059. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  8060. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  8061. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  8062. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  8063. }
  8064. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  8065. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  8066. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  8067. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8068. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8069. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8070. {
  8071. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  8072. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  8073. }
  8074. }
  8075. if (appendSizeValue)
  8076. {
  8077. EmitAppendAlign(appendAllocAlign);
  8078. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8079. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  8080. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8081. }
  8082. return retValue;
  8083. }
  8084. bool BfModule::IsOptimized()
  8085. {
  8086. if (mProject == NULL)
  8087. return false;
  8088. int optLevel = GetModuleOptions().mOptLevel;
  8089. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  8090. }
  8091. bool BfModule::IsTargetingBeefBackend()
  8092. {
  8093. if (mProject == NULL)
  8094. return true;
  8095. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8096. }
  8097. bool BfModule::WantsLifetimes()
  8098. {
  8099. if (mProject == NULL)
  8100. return false;
  8101. if (mBfIRBuilder->mIgnoreWrites)
  8102. return false;
  8103. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8104. }
  8105. bool BfModule::HasCompiledOutput()
  8106. {
  8107. return (!mSystem->mIsResolveOnly) && (mIsReified) && (!mIsComptimeModule);
  8108. }
  8109. // We will skip the object access check for any occurances of this value
  8110. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  8111. {
  8112. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8113. return;
  8114. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8115. return;
  8116. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  8117. return;
  8118. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  8119. }
  8120. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  8121. {
  8122. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8123. return;
  8124. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8125. return;
  8126. if (typedVal.mValue.IsConst())
  8127. {
  8128. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8129. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8130. return;
  8131. if (constant->mConstType == BfConstType_BitCastNull)
  8132. return;
  8133. }
  8134. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  8135. auto typeOptions = GetTypeOptions();
  8136. if (typeOptions != NULL)
  8137. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  8138. if (!emitObjectAccessCheck)
  8139. return;
  8140. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  8141. {
  8142. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  8143. return;
  8144. }
  8145. if (typedVal.IsAddr())
  8146. typedVal = LoadValue(typedVal);
  8147. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  8148. }
  8149. void BfModule::EmitEnsureInstructionAt()
  8150. {
  8151. if (mProject == NULL)
  8152. return;
  8153. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  8154. return;
  8155. mBfIRBuilder->CreateEnsureInstructionAt();
  8156. }
  8157. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  8158. {
  8159. if (mBfIRBuilder->mIgnoreWrites)
  8160. return; // Nothing needed here
  8161. auto irb = mBfIRBuilder;
  8162. if (mIsComptimeModule)
  8163. {
  8164. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8165. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  8166. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8167. return;
  8168. }
  8169. auto checkBB = irb->CreateBlock("as.check");
  8170. auto isNull = irb->CreateIsNull(targetValue.mValue);
  8171. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  8172. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8173. auto intPtrType = CreatePointerType(intType);
  8174. auto intPtrPtrType = CreatePointerType(intPtrType);
  8175. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  8176. auto int32PtrType = CreatePointerType(int32Type);
  8177. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8178. if (mCompiler->mOptions.mAllowHotSwapping)
  8179. {
  8180. BfExprEvaluator exprEvaluator(this);
  8181. AddBasicBlock(checkBB);
  8182. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8183. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  8184. SizedArray<BfIRValue, 4> irArgs;
  8185. irArgs.push_back(objectParam);
  8186. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  8187. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  8188. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  8189. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8190. }
  8191. else
  8192. {
  8193. AddBasicBlock(checkBB);
  8194. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  8195. vDataPtr = irb->CreateLoad(vDataPtr);
  8196. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8197. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  8198. if (targetType->IsInterface())
  8199. {
  8200. auto targetTypeInst = targetType->ToTypeInstance();
  8201. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8202. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  8203. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  8204. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8205. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  8206. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  8207. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  8208. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  8209. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  8210. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8211. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  8212. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  8213. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8214. }
  8215. else
  8216. {
  8217. if (!targetType->IsTypeInstance())
  8218. targetType = GetWrappedStructType(targetType);
  8219. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8220. int inheritanceIdOfs = mSystem->mPtrSize;
  8221. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8222. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8223. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  8224. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  8225. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  8226. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  8227. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  8228. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8229. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  8230. fieldInst = &typeTypeInstance->mFieldInstances[10];
  8231. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  8232. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8233. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  8234. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  8235. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  8236. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8237. }
  8238. }
  8239. }
  8240. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  8241. {
  8242. if (mBfIRBuilder->mIgnoreWrites)
  8243. return;
  8244. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  8245. auto typeOptions = GetTypeOptions();
  8246. if (typeOptions != NULL)
  8247. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  8248. if (emitDynamicCastCheck)
  8249. {
  8250. int wantTypeId = 0;
  8251. if (!type->IsGenericParam())
  8252. wantTypeId = type->mTypeId;
  8253. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  8254. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8255. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8256. AddBasicBlock(failBlock);
  8257. if (mIsComptimeModule)
  8258. {
  8259. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  8260. }
  8261. else
  8262. {
  8263. SizedArray<BfIRValue, 8> llvmArgs;
  8264. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8265. llvmArgs.push_back(bitAddr);
  8266. llvmArgs.push_back(GetConstValue32(wantTypeId));
  8267. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  8268. BF_ASSERT(objDynCheck);
  8269. if (objDynCheck)
  8270. {
  8271. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  8272. }
  8273. }
  8274. mBfIRBuilder->CreateBr(endBlock);
  8275. AddBasicBlock(endBlock);
  8276. }
  8277. }
  8278. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  8279. {
  8280. if (mBfIRBuilder->mIgnoreWrites)
  8281. {
  8282. if (toType == mContext->mBfObjectType)
  8283. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8284. if (toType->IsBoxed())
  8285. {
  8286. BfBoxedType* boxedType = (BfBoxedType*)toType;
  8287. if (boxedType->mElementType->IsGenericParam())
  8288. {
  8289. if (typedVal.mType == boxedType->mElementType)
  8290. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8291. else
  8292. return BfTypedValue();
  8293. }
  8294. }
  8295. }
  8296. BP_ZONE("BoxValue");
  8297. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8298. if (typedVal.mType->IsNullable())
  8299. {
  8300. typedVal = MakeAddressable(typedVal);
  8301. auto innerType = typedVal.mType->GetUnderlyingType();
  8302. if (!innerType->IsValueType())
  8303. {
  8304. if (!mIgnoreErrors)
  8305. Fail("Only value types can be boxed", srcNode);
  8306. return BfTypedValue();
  8307. }
  8308. auto boxedType = CreateBoxedType(innerType);
  8309. auto resultType = toType;
  8310. if (resultType == NULL)
  8311. resultType = boxedType;
  8312. if (mBfIRBuilder->mIgnoreWrites)
  8313. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  8314. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8315. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  8316. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  8317. mBfIRBuilder->PopulateType(typedVal.mType);
  8318. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  8319. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  8320. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  8321. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8322. mBfIRBuilder->AddBlock(boxBB);
  8323. mBfIRBuilder->SetInsertPoint(boxBB);
  8324. BfScopeData newScope;
  8325. newScope.mOuterIsConditional = true;
  8326. mCurMethodState->AddScope(&newScope);
  8327. NewScopeState();
  8328. BfIRValue nullableValueAddr;
  8329. BfIRValue loadedVal;
  8330. if (innerType->IsValuelessType())
  8331. {
  8332. loadedVal = mBfIRBuilder->GetFakeVal();
  8333. }
  8334. else
  8335. {
  8336. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  8337. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  8338. }
  8339. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  8340. RestoreScopeState();
  8341. if (!boxedVal)
  8342. return BfTypedValue();
  8343. mBfIRBuilder->CreateBr(endBB);
  8344. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  8345. mBfIRBuilder->AddBlock(endBB);
  8346. mBfIRBuilder->SetInsertPoint(endBB);
  8347. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  8348. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  8349. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  8350. return BfTypedValue(phi, resultType);
  8351. }
  8352. bool alreadyCheckedCast = false;
  8353. BfTypeInstance* toTypeInstance = NULL;
  8354. if (toType != NULL)
  8355. toTypeInstance = toType->ToTypeInstance();
  8356. bool isStructPtr = typedVal.mType->IsStructPtr();
  8357. if (fromStructTypeInstance == NULL)
  8358. {
  8359. auto primType = (BfPrimitiveType*)typedVal.mType;
  8360. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  8361. {
  8362. // Can always do IHashable
  8363. alreadyCheckedCast = true;
  8364. }
  8365. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  8366. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8367. if (isStructPtr)
  8368. {
  8369. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8370. alreadyCheckedCast = true;
  8371. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  8372. }
  8373. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  8374. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8375. }
  8376. if (fromStructTypeInstance == NULL)
  8377. return BfTypedValue();
  8378. // Need to box it
  8379. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  8380. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8381. {
  8382. if (mBfIRBuilder->mIgnoreWrites)
  8383. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  8384. auto boxedType = CreateBoxedType(typedVal.mType);
  8385. mBfIRBuilder->PopulateType(boxedType);
  8386. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8387. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  8388. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  8389. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  8390. if (boxedType->IsUnspecializedType())
  8391. {
  8392. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  8393. }
  8394. else
  8395. {
  8396. PopulateType(fromStructTypeInstance);
  8397. if (!fromStructTypeInstance->IsValuelessType())
  8398. {
  8399. typedVal = LoadValue(typedVal);
  8400. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  8401. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  8402. {
  8403. auto ptrType = CreatePointerType(typedVal.mType);
  8404. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  8405. }
  8406. if (typedVal.IsSplat())
  8407. {
  8408. AggregateSplatIntoAddr(typedVal, valPtr);
  8409. }
  8410. else
  8411. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  8412. }
  8413. }
  8414. if (toType == NULL)
  8415. {
  8416. return BfTypedValue(allocaInst, boxedType);
  8417. }
  8418. else
  8419. {
  8420. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  8421. return BfTypedValue(castedValue, toType);
  8422. }
  8423. }
  8424. return BfTypedValue();
  8425. }
  8426. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  8427. {
  8428. BfTypeInstance* checkTypeInst = typeInst;
  8429. while (checkTypeInst != NULL)
  8430. {
  8431. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  8432. {
  8433. if (checkProp->mName == propDef->mName)
  8434. {
  8435. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  8436. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  8437. {
  8438. propDef = checkProp;
  8439. typeInst = checkTypeInst;
  8440. return true;
  8441. }
  8442. }
  8443. }
  8444. checkTypeInst = checkTypeInst->mBaseType;
  8445. }
  8446. return false;
  8447. }
  8448. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  8449. {
  8450. if (!typeInstance->mResolvingVarField)
  8451. {
  8452. if (!typeInstance->DefineStateAllowsStaticMethods())
  8453. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  8454. }
  8455. else
  8456. {
  8457. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  8458. {
  8459. AssertErrorState();
  8460. return NULL;
  8461. }
  8462. }
  8463. if (assertName != NULL)
  8464. {
  8465. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8466. }
  8467. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  8468. if (methodGroup.mDefault == NULL)
  8469. {
  8470. if (!mCompiler->mIsResolveOnly)
  8471. {
  8472. // Get it from the owning module so we don't create a reference prematurely...
  8473. auto declModule = typeInstance->mModule;
  8474. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  8475. {
  8476. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  8477. if (!declModule->mIsScratchModule)
  8478. declModule->mOnDemandMethodCount++;
  8479. }
  8480. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  8481. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  8482. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  8483. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  8484. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  8485. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  8486. }
  8487. else
  8488. {
  8489. auto declModule = typeInstance->mModule;
  8490. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  8491. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  8492. }
  8493. }
  8494. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8495. //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
  8496. // be from a call to the NON-raw version
  8497. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  8498. // {
  8499. // methodInstance->mIsReified = mIsReified;
  8500. // if (methodInstance->mMethodProcessRequest == NULL)
  8501. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  8502. // }
  8503. return methodInstance;
  8504. }
  8505. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  8506. {
  8507. if (methodDef->mIsLocalMethod)
  8508. {
  8509. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  8510. }
  8511. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  8512. }
  8513. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  8514. {
  8515. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8516. while (typeInstance != NULL)
  8517. {
  8518. typeInstance->mTypeDef->PopulateMemberSets();
  8519. BfMemberSetEntry* entry = NULL;
  8520. BfMethodDef* methodDef = NULL;
  8521. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8522. methodDef = (BfMethodDef*)entry->mMemberDef;
  8523. while (methodDef != NULL)
  8524. {
  8525. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  8526. (methodDef->mGenericParams.size() == 0) &&
  8527. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8528. return GetRawMethodInstance(typeInstance, methodDef);
  8529. methodDef = methodDef->mNextWithSameName;
  8530. }
  8531. if (!checkBase)
  8532. break;
  8533. typeInstance = typeInstance->mBaseType;
  8534. }
  8535. return NULL;
  8536. }
  8537. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  8538. {
  8539. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8540. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  8541. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  8542. if (!useUnspecializedType)
  8543. return methodInstance;
  8544. if (!owner->IsGenericTypeInstance())
  8545. return methodInstance;
  8546. if ((owner->IsDelegateFromTypeRef()) ||
  8547. (owner->IsFunctionFromTypeRef()) ||
  8548. (owner->IsTuple()))
  8549. {
  8550. return methodInstance;
  8551. }
  8552. auto genericType = (BfTypeInstance*)owner;
  8553. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  8554. return methodInstance;
  8555. if (methodInstance->mMethodDef->mIsLocalMethod)
  8556. return methodInstance;
  8557. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  8558. if (unspecializedType == NULL)
  8559. {
  8560. AssertErrorState();
  8561. return methodInstance;
  8562. }
  8563. if (unspecializedType == NULL)
  8564. return methodInstance;
  8565. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  8566. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  8567. }
  8568. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  8569. {
  8570. int genericCount = 0;
  8571. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  8572. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  8573. {
  8574. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  8575. if (param->IsGenericParam())
  8576. genericCount++;
  8577. }
  8578. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  8579. genericCount++;
  8580. return genericCount;
  8581. }
  8582. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  8583. {
  8584. BF_ASSERT(!mIsScratchModule);
  8585. BF_ASSERT(mIsReified);
  8586. BfModule* mainModule = this;
  8587. if (mParentModule != NULL)
  8588. mainModule = mParentModule;
  8589. BfModule* specModule = NULL;
  8590. BfModule** specModulePtr = NULL;
  8591. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  8592. {
  8593. return *specModulePtr;
  8594. }
  8595. else
  8596. {
  8597. String specModuleName = mModuleName;
  8598. for (auto bfProject : projectList)
  8599. {
  8600. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  8601. }
  8602. specModule = new BfModule(mContext, specModuleName);
  8603. specModule->mProject = mainModule->mProject;
  8604. specModule->mParentModule = mainModule;
  8605. specModule->mIsSpecializedMethodModuleRoot = true;
  8606. specModule->Init();
  8607. Array<BfProject*> projList;
  8608. for (auto project : projectList)
  8609. projList.Add(project);
  8610. mainModule->mSpecializedMethodModules[projList] = specModule;
  8611. }
  8612. return specModule;
  8613. }
  8614. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  8615. {
  8616. if (IsSkippingExtraResolveChecks())
  8617. return BfIRValue();
  8618. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  8619. {
  8620. //BF_ASSERT(!methodInstance->mIRFunction);
  8621. return BfIRValue();
  8622. }
  8623. auto methodDef = methodInstance->mMethodDef;
  8624. StringT<128> methodName;
  8625. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  8626. if (isInlined != methodInstance->mAlwaysInline)
  8627. {
  8628. if (isInlined)
  8629. methodName += "__INLINE";
  8630. else
  8631. methodName += "__NOINLINE";
  8632. }
  8633. if (tryExisting)
  8634. {
  8635. auto func = mBfIRBuilder->GetFunction(methodName);
  8636. if (func)
  8637. return func;
  8638. }
  8639. auto intrinsic = GetIntrinsic(methodInstance);
  8640. if (intrinsic)
  8641. return intrinsic;
  8642. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  8643. {
  8644. return CreateDllImportGlobalVar(methodInstance, false);
  8645. }
  8646. BfIRType returnType;
  8647. SizedArray<BfIRType, 8> paramTypes;
  8648. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  8649. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  8650. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  8651. auto callingConv = GetIRCallingConvention(methodInstance);
  8652. if (callingConv != BfIRCallingConv_CDecl)
  8653. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  8654. SetupIRMethod(methodInstance, func, isInlined);
  8655. // auto srcModule = methodInstance->GetOwner()->GetModule();
  8656. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  8657. // {
  8658. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  8659. // {
  8660. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  8661. // }
  8662. // }
  8663. return func;
  8664. }
  8665. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  8666. {
  8667. if (assertName != NULL)
  8668. {
  8669. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8670. }
  8671. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8672. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8673. BfMethodDef* methodDef = NULL;
  8674. BfTypeInstance* foreignType = NULL;
  8675. if (methodInstance != NULL)
  8676. {
  8677. methodDef = methodInstance->mMethodDef;
  8678. if (methodInstance->mMethodInfoEx != NULL)
  8679. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  8680. }
  8681. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  8682. {
  8683. // Can't use it, not reified
  8684. methodInstance = NULL;
  8685. }
  8686. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  8687. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  8688. {
  8689. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  8690. return BfModuleMethodInstance(methodInstance, func);
  8691. }
  8692. if (foreignType != NULL)
  8693. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  8694. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  8695. }
  8696. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8697. {
  8698. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8699. while (typeInstance != NULL)
  8700. {
  8701. typeInstance->mTypeDef->PopulateMemberSets();
  8702. BfMemberSetEntry* entry = NULL;
  8703. BfMethodDef* methodDef = NULL;
  8704. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8705. methodDef = (BfMethodDef*)entry->mMemberDef;
  8706. while (methodDef != NULL)
  8707. {
  8708. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8709. (methodDef->mGenericParams.size() == 0) &&
  8710. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8711. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8712. methodDef = methodDef->mNextWithSameName;
  8713. }
  8714. if (!checkBase)
  8715. break;
  8716. typeInstance = typeInstance->mBaseType;
  8717. }
  8718. return BfModuleMethodInstance();
  8719. }
  8720. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  8721. {
  8722. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8723. while (typeInstance != NULL)
  8724. {
  8725. typeInstance->mTypeDef->PopulateMemberSets();
  8726. BfMemberSetEntry* entry = NULL;
  8727. BfMethodDef* methodDef = NULL;
  8728. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8729. methodDef = (BfMethodDef*)entry->mMemberDef;
  8730. while (methodDef != NULL)
  8731. {
  8732. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8733. (methodDef->mGenericParams.size() == 0) &&
  8734. (paramTypes.size() == methodDef->mParams.size()))
  8735. {
  8736. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8737. if (moduleMethodInstance.mMethodInstance != NULL)
  8738. {
  8739. bool matches = true;
  8740. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8741. {
  8742. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  8743. matches = false;
  8744. }
  8745. if (matches)
  8746. return moduleMethodInstance;
  8747. }
  8748. }
  8749. methodDef = methodDef->mNextWithSameName;
  8750. }
  8751. if (!checkBase)
  8752. break;
  8753. typeInstance = typeInstance->mBaseType;
  8754. }
  8755. return BfModuleMethodInstance();
  8756. }
  8757. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  8758. {
  8759. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  8760. PopulateType(internalType);
  8761. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  8762. if (!moduleMethodInstance)
  8763. {
  8764. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  8765. }
  8766. return moduleMethodInstance;
  8767. }
  8768. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  8769. {
  8770. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  8771. typeInstance->mOperatorInfo.Add(NULL);
  8772. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  8773. {
  8774. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  8775. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  8776. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  8777. BfTypeState typeState;
  8778. typeState.mTypeInstance = typeInstance;
  8779. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  8780. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  8781. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  8782. if (operatorDef->mReturnTypeRef != NULL)
  8783. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  8784. if (operatorDef->mParams.size() >= 1)
  8785. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  8786. if (operatorDef->mParams.size() >= 2)
  8787. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  8788. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  8789. }
  8790. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  8791. }
  8792. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  8793. {
  8794. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  8795. if (operatorInfo == NULL)
  8796. return NULL;
  8797. if (operatorInfo->mReturnType == NULL)
  8798. return NULL;
  8799. if (lhs)
  8800. {
  8801. if (operatorInfo->mLHSType == NULL)
  8802. return NULL;
  8803. if (!CanCast(lhs, operatorInfo->mLHSType, BfCastFlags_IsConstraintCheck))
  8804. return NULL;
  8805. }
  8806. if (rhs)
  8807. {
  8808. if (operatorInfo->mRHSType == NULL)
  8809. return NULL;
  8810. if (!CanCast(rhs, operatorInfo->mRHSType, BfCastFlags_IsConstraintCheck))
  8811. return NULL;
  8812. }
  8813. return operatorInfo->mReturnType;
  8814. }
  8815. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8816. {
  8817. while (typeInstance != NULL)
  8818. {
  8819. typeInstance->mTypeDef->PopulateMemberSets();
  8820. BfMemberSetEntry* entry = NULL;
  8821. BfMethodDef* methodDef = NULL;
  8822. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8823. methodDef = (BfMethodDef*)entry->mMemberDef;
  8824. while (methodDef != NULL)
  8825. {
  8826. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8827. (methodDef->mGenericParams.size() == 0) &&
  8828. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8829. {
  8830. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  8831. if (!methodInstanceGroup.IsImplemented())
  8832. return false;
  8833. if (methodInstanceGroup.mDefault == NULL)
  8834. return false;
  8835. return methodInstanceGroup.mDefault->mIsReified;
  8836. }
  8837. methodDef = methodDef->mNextWithSameName;
  8838. }
  8839. if (!checkBase)
  8840. break;
  8841. typeInstance = typeInstance->mBaseType;
  8842. }
  8843. return false;
  8844. }
  8845. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8846. {
  8847. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8848. while (typeInstance != NULL)
  8849. {
  8850. typeInstance->mTypeDef->PopulateMemberSets();
  8851. BfMemberSetEntry* entry = NULL;
  8852. BfMethodDef* methodDef = NULL;
  8853. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8854. methodDef = (BfMethodDef*)entry->mMemberDef;
  8855. while (methodDef != NULL)
  8856. {
  8857. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  8858. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8859. return true;
  8860. methodDef = methodDef->mNextWithSameName;
  8861. }
  8862. if (!checkBase)
  8863. break;
  8864. typeInstance = typeInstance->mBaseType;
  8865. }
  8866. return BfModuleMethodInstance();
  8867. }
  8868. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  8869. {
  8870. auto methodDef = methodInst->mMethodDef;
  8871. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  8872. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8873. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  8874. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  8875. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  8876. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  8877. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  8878. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8879. if (allowResolveGenericParamNames)
  8880. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8881. StringT<128> methodName;
  8882. auto _AddTypeName = [&](BfType* type)
  8883. {
  8884. auto typeNameFlags = BfTypeNameFlags_None;
  8885. if (allowResolveGenericParamNames)
  8886. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8887. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  8888. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs);
  8889. methodName += TypeToString(type, typeNameFlags);
  8890. };
  8891. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  8892. {
  8893. _AddTypeName(methodInst->mReturnType);
  8894. methodName += " ";
  8895. }
  8896. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  8897. {
  8898. methodName += TypeToString(type, typeNameFlags);
  8899. if (methodName == "$")
  8900. methodName = "";
  8901. else if (!methodName.IsEmpty())
  8902. methodName += ".";
  8903. }
  8904. String accessorString;
  8905. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  8906. if (methodInst->mMethodDef->mIsLocalMethod)
  8907. {
  8908. int atPos = (int)methodDefName.IndexOf('$');
  8909. methodDefName.RemoveToEnd(atPos);
  8910. methodDefName.Replace("@", ".");
  8911. }
  8912. else
  8913. {
  8914. int atPos = (int)methodDefName.IndexOf('$');
  8915. if (atPos != -1)
  8916. {
  8917. accessorString = methodDefName.Substring(0, atPos);
  8918. if ((accessorString == "get") || (accessorString == "set"))
  8919. {
  8920. methodDefName = methodDefName.Substring(atPos + 1);
  8921. }
  8922. else
  8923. accessorString = "";
  8924. }
  8925. }
  8926. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  8927. {
  8928. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8929. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8930. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8931. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  8932. methodName += ".";
  8933. }
  8934. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  8935. {
  8936. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8937. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8938. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8939. methodName += "[";
  8940. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  8941. methodName += "].";
  8942. }
  8943. if (methodDef->mMethodType == BfMethodType_Operator)
  8944. {
  8945. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  8946. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  8947. {
  8948. // Don't add explicit/implicit part, since that's not available in GCC mangling
  8949. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  8950. {
  8951. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8952. methodName += "explicit ";
  8953. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8954. methodName += "explicit ";
  8955. }*/
  8956. methodName += "operator ";
  8957. if (methodInst->mReturnType != NULL)
  8958. methodName += TypeToString(methodInst->mReturnType);
  8959. }
  8960. else
  8961. {
  8962. methodName += "operator";
  8963. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  8964. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  8965. }
  8966. }
  8967. else if (methodDef->mMethodType == BfMethodType_Ctor)
  8968. {
  8969. if (methodDef->mIsStatic)
  8970. methodName += "__BfStaticCtor";
  8971. else
  8972. methodName += "this";
  8973. accessorString = "";
  8974. }
  8975. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  8976. {
  8977. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8978. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8979. {
  8980. methodName += "get indexer";
  8981. }
  8982. else
  8983. {
  8984. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8985. propertyDecl->mNameNode->ToString(methodName);
  8986. methodName += " get accessor";
  8987. return methodName;
  8988. }
  8989. }
  8990. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8991. {
  8992. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8993. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8994. {
  8995. methodName += "set indexer";
  8996. }
  8997. else
  8998. {
  8999. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9000. propertyDecl->mNameNode->ToString(methodName);
  9001. methodName += " set accessor";
  9002. return methodName;
  9003. }
  9004. }
  9005. else
  9006. methodName += methodDefName;
  9007. if (methodDef->mMethodType == BfMethodType_Mixin)
  9008. methodName += "!";
  9009. BfTypeVector newMethodGenericArgs;
  9010. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9011. {
  9012. methodName += "<";
  9013. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  9014. {
  9015. if (i > 0)
  9016. methodName += ", ";
  9017. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9018. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  9019. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9020. if (allowResolveGenericParamNames)
  9021. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9022. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  9023. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  9024. {
  9025. bool hasEmpty = false;
  9026. for (auto arg : *methodGenericArgs)
  9027. {
  9028. if (arg == NULL)
  9029. hasEmpty = true;
  9030. }
  9031. if (hasEmpty)
  9032. {
  9033. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  9034. {
  9035. auto arg = (*methodGenericArgs)[genericIdx];
  9036. if (arg != NULL)
  9037. newMethodGenericArgs.push_back(arg);
  9038. else
  9039. {
  9040. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  9041. if (genericParamInst->mTypeConstraint != NULL)
  9042. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  9043. else
  9044. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  9045. }
  9046. }
  9047. methodGenericArgs = &newMethodGenericArgs;
  9048. }
  9049. if (type->IsUnspecializedType())
  9050. type = ResolveGenericType(type, NULL, methodGenericArgs);
  9051. }
  9052. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  9053. {
  9054. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  9055. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  9056. methodName += TypeToString(type, typeNameFlags);
  9057. }
  9058. else
  9059. methodName += TypeToString(type, typeNameFlags);
  9060. }
  9061. methodName += ">";
  9062. }
  9063. if (accessorString.length() == 0)
  9064. {
  9065. int dispParamIdx = 0;
  9066. methodName += "(";
  9067. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  9068. {
  9069. int paramKind = methodInst->GetParamKind(paramIdx);
  9070. if (paramKind == BfParamKind_ImplicitCapture)
  9071. continue;
  9072. if (dispParamIdx > 0)
  9073. methodName += ", ";
  9074. if (paramKind == BfParamKind_Params)
  9075. methodName += "params ";
  9076. BfType* type = methodInst->GetParamType(paramIdx);
  9077. _AddTypeName(type);
  9078. methodName += " ";
  9079. methodName += methodInst->GetParamName(paramIdx);
  9080. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  9081. if (paramInitializer != NULL)
  9082. {
  9083. methodName += " = ";
  9084. methodName += paramInitializer->ToString();
  9085. }
  9086. dispParamIdx++;
  9087. }
  9088. methodName += ")";
  9089. }
  9090. if (accessorString.length() != 0)
  9091. {
  9092. methodName += " " + accessorString;
  9093. }
  9094. return methodName;
  9095. }
  9096. void BfModule::pt(BfType* type)
  9097. {
  9098. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  9099. }
  9100. void BfModule::pm(BfMethodInstance* type)
  9101. {
  9102. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  9103. }
  9104. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  9105. {
  9106. if ((flagsLeft & checkFlag) == 0)
  9107. return;
  9108. if (!str.empty())
  9109. {
  9110. if (flagsLeft == checkFlag)
  9111. {
  9112. if ((int)str.IndexOf(',') != -1)
  9113. str += ", and ";
  9114. else
  9115. str += " and ";
  9116. }
  9117. else
  9118. str += ", ";
  9119. }
  9120. str += addString;
  9121. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  9122. }
  9123. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  9124. {
  9125. String resultStr;
  9126. auto flagsLeft = attrTarget;
  9127. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  9128. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  9129. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  9130. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  9131. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  9132. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  9133. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  9134. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  9135. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  9136. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  9137. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  9138. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  9139. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  9140. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  9141. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  9142. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  9143. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  9144. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  9145. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  9146. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  9147. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  9148. if (resultStr.IsEmpty())
  9149. return "<nothing>";
  9150. return resultStr;
  9151. }
  9152. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  9153. {
  9154. auto constant = mBfIRBuilder->GetConstant(irVal);
  9155. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  9156. if (stringPoolIdx != -1)
  9157. {
  9158. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  9159. return;
  9160. }
  9161. if (constant->mConstType == BfConstType_Agg)
  9162. {
  9163. auto constArray = (BfConstantAgg*)constant;
  9164. SizedArray<BfIRValue, 8> newVals;
  9165. for (auto val : constArray->mValues)
  9166. {
  9167. auto newVal = val;
  9168. CurrentAddToConstHolder(newVal);
  9169. newVals.push_back(newVal);
  9170. }
  9171. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(constArray->mType, newVals);
  9172. return;
  9173. }
  9174. auto origConst = irVal;
  9175. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  9176. {
  9177. auto bitcast = (BfConstantBitCast*)constant;
  9178. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  9179. }
  9180. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  9181. }
  9182. void BfModule::ClearConstData()
  9183. {
  9184. mBfIRBuilder->ClearConstData();
  9185. mStringObjectPool.Clear();
  9186. mStringCharPtrPool.Clear();
  9187. mStringPoolRefs.Clear();
  9188. }
  9189. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  9190. {
  9191. switch (constant->mTypeCode)
  9192. {
  9193. case BfTypeCode_StringId:
  9194. case BfTypeCode_Boolean:
  9195. case BfTypeCode_Int8:
  9196. case BfTypeCode_UInt8:
  9197. case BfTypeCode_Int16:
  9198. case BfTypeCode_UInt16:
  9199. case BfTypeCode_Int32:
  9200. case BfTypeCode_UInt32:
  9201. case BfTypeCode_Int64:
  9202. case BfTypeCode_UInt64:
  9203. case BfTypeCode_IntPtr:
  9204. case BfTypeCode_UIntPtr:
  9205. case BfTypeCode_IntUnknown:
  9206. case BfTypeCode_UIntUnknown:
  9207. case BfTypeCode_Char8:
  9208. case BfTypeCode_Char16:
  9209. case BfTypeCode_Char32:
  9210. case BfTypeCode_Float:
  9211. case BfTypeCode_Double:
  9212. {
  9213. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9214. BfTypedValue typedValue;
  9215. if (constant->mTypeCode == BfTypeCode_StringId)
  9216. {
  9217. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9218. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9219. {
  9220. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType), wantType);
  9221. return typedValue;
  9222. }
  9223. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  9224. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType), stringType);
  9225. }
  9226. if (!typedValue)
  9227. {
  9228. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  9229. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  9230. }
  9231. if (typedValue.mType == wantType)
  9232. return typedValue;
  9233. if (wantType->IsTypedPrimitive())
  9234. {
  9235. if (typedValue.mType == wantType->GetUnderlyingType())
  9236. {
  9237. typedValue.mType = wantType;
  9238. return typedValue;
  9239. }
  9240. }
  9241. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  9242. if (!castedTypedValue)
  9243. return BfTypedValue();
  9244. return castedTypedValue;
  9245. }
  9246. break;
  9247. default: break;
  9248. }
  9249. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  9250. BF_ASSERT(irValue);
  9251. if (!irValue)
  9252. return BfTypedValue();
  9253. if (constant->mConstType == BfConstType_GlobalVar)
  9254. {
  9255. mBfIRBuilder->PopulateType(wantType);
  9256. auto result = BfTypedValue(irValue, wantType, true);
  9257. if (!wantType->IsComposite())
  9258. result = LoadValue(result);
  9259. return result;
  9260. }
  9261. return BfTypedValue(irValue, wantType, false);
  9262. }
  9263. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowStringId)
  9264. {
  9265. if (constant->mTypeCode == BfTypeCode_NullPtr)
  9266. {
  9267. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  9268. wantType = mContext->mTypes[constant->mIRType.mId];
  9269. if (wantType == NULL)
  9270. return constHolder->CreateConstNull();
  9271. return GetDefaultValue(wantType);
  9272. }
  9273. if (constant->mTypeCode == BfTypeCode_StringId)
  9274. {
  9275. if (!allowStringId)
  9276. {
  9277. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  9278. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  9279. {
  9280. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  9281. BfIRValue stringObjConst = GetStringObjectValue(str);
  9282. if (wantType->IsPointer())
  9283. return GetStringCharPtr(stringObjConst);
  9284. return stringObjConst;
  9285. }
  9286. }
  9287. }
  9288. if (constant->mConstType == BfConstType_Agg)
  9289. {
  9290. auto constArray = (BfConstantAgg*)constant;
  9291. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  9292. wantType = mContext->mTypes[constArray->mType.mId];
  9293. SizedArray<BfIRValue, 8> newVals;
  9294. if (wantType->IsSizedArray())
  9295. {
  9296. auto elementType = wantType->GetUnderlyingType();
  9297. for (auto val : constArray->mValues)
  9298. {
  9299. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  9300. }
  9301. }
  9302. else
  9303. {
  9304. auto wantTypeInst = wantType->ToTypeInstance();
  9305. if (wantTypeInst->mBaseType != NULL)
  9306. {
  9307. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  9308. newVals.Add(baseVal);
  9309. }
  9310. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  9311. {
  9312. if (fieldInstance.mDataIdx < 0)
  9313. continue;
  9314. auto val = constArray->mValues[fieldInstance.mDataIdx];
  9315. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  9316. if (fieldInstance.mDataIdx == newVals.mSize)
  9317. newVals.Add(memberVal);
  9318. else
  9319. {
  9320. while (fieldInstance.mDataIdx >= newVals.mSize)
  9321. newVals.Add(BfIRValue());
  9322. newVals[fieldInstance.mDataIdx] = memberVal;
  9323. }
  9324. }
  9325. for (auto& val : newVals)
  9326. {
  9327. if (!val)
  9328. val = mBfIRBuilder->CreateConstArrayZero(0);
  9329. }
  9330. }
  9331. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  9332. }
  9333. return mBfIRBuilder->CreateConst(constant, constHolder);
  9334. }
  9335. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  9336. {
  9337. if (attrTarget == BfAttributeTargets_SkipValidate)
  9338. return;
  9339. for (auto& customAttribute : customAttributes->mAttributes)
  9340. {
  9341. if (!customAttribute.mAwaitingValidation)
  9342. continue;
  9343. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  9344. {
  9345. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  9346. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  9347. }
  9348. customAttribute.mAwaitingValidation = false;
  9349. }
  9350. }
  9351. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9352. {
  9353. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9354. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9355. {
  9356. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9357. }
  9358. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  9359. if (mCompiler->IsAutocomplete())
  9360. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  9361. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  9362. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  9363. BfAutoComplete* autoComplete = NULL;
  9364. if (mCompiler->mResolvePassData != NULL)
  9365. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  9366. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  9367. {
  9368. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  9369. {
  9370. if (captureInfo == NULL)
  9371. {
  9372. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  9373. continue;
  9374. }
  9375. BfCaptureInfo::Entry captureEntry;
  9376. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  9377. if (!attributesDirective->mArguments.IsEmpty())
  9378. {
  9379. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  9380. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  9381. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  9382. }
  9383. captureInfo->mCaptures.Add(captureEntry);
  9384. continue;
  9385. }
  9386. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  9387. BfCustomAttribute customAttribute;
  9388. customAttribute.mAwaitingValidation = true;
  9389. customAttribute.mRef = attributesDirective;
  9390. if (attributesDirective->mAttrOpenToken != NULL)
  9391. targetOverride = (BfAttributeTargets)0;
  9392. if (attributesDirective->mAttributeTypeRef == NULL)
  9393. {
  9394. AssertErrorState();
  9395. continue;
  9396. }
  9397. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  9398. BfTypeDef* attrTypeDef = NULL;
  9399. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  9400. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  9401. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  9402. {
  9403. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  9404. if (attrTypeDef != NULL)
  9405. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  9406. }
  9407. bool isBypassedAttr = false;
  9408. if (attrTypeDef != NULL)
  9409. {
  9410. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  9411. // We solve it by having a 'bypass' for known attributes that Object depends on
  9412. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  9413. {
  9414. //if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  9415. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  9416. {
  9417. for (auto methodDef : attrTypeDef->mMethods)
  9418. {
  9419. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  9420. {
  9421. customAttribute.mType = attrType->ToTypeInstance();
  9422. customAttribute.mCtor = methodDef;
  9423. isBypassedAttr = true;
  9424. break;
  9425. }
  9426. }
  9427. }
  9428. }
  9429. if (isBypassedAttr)
  9430. {
  9431. customAttribute.mAwaitingValidation = false;
  9432. customAttributes->mAttributes.push_back(customAttribute);
  9433. continue;
  9434. }
  9435. if (mContext->mCurTypeState != NULL)
  9436. {
  9437. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  9438. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9439. }
  9440. else
  9441. {
  9442. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9443. }
  9444. }
  9445. BfTypeInstance* attrTypeInst = NULL;
  9446. if (attrType == NULL)
  9447. continue;
  9448. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  9449. attrTypeInst = attrType->ToTypeInstance();
  9450. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  9451. {
  9452. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  9453. continue;
  9454. }
  9455. if (mCurTypeInstance != NULL)
  9456. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9457. customAttribute.mType = attrTypeInst;
  9458. bool allocatedMethodState = NULL;
  9459. defer(
  9460. {
  9461. if (allocatedMethodState)
  9462. {
  9463. delete mCurMethodState;
  9464. mCurMethodState = NULL;
  9465. }
  9466. });
  9467. if (mCurMethodState == NULL)
  9468. {
  9469. allocatedMethodState = true;
  9470. mCurMethodState = new BfMethodState();
  9471. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  9472. }
  9473. BfConstResolver constResolver(this);
  9474. if (allowNonConstArgs)
  9475. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  9476. bool inPropSet = false;
  9477. SizedArray<BfResolvedArg, 2> argValues;
  9478. for (BfExpression* arg : attributesDirective->mArguments)
  9479. {
  9480. if (arg == NULL)
  9481. {
  9482. continue;
  9483. }
  9484. if (autoComplete != NULL)
  9485. autoComplete->mShowAttributeProperties = attrTypeInst;
  9486. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  9487. {
  9488. inPropSet = true;
  9489. if (autoComplete != NULL)
  9490. autoComplete->CheckNode(assignExpr->mLeft);
  9491. String findName = assignExpr->mLeft->ToString();
  9492. BfPropertyDef* bestProp = NULL;
  9493. BfTypeInstance* bestPropTypeInst = NULL;
  9494. BfFieldDef* bestField = NULL;
  9495. BfTypeInstance* bestFieldTypeInst = NULL;
  9496. auto checkTypeInst = attrTypeInst;
  9497. while (checkTypeInst != NULL)
  9498. {
  9499. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  9500. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  9501. {
  9502. if (prop->mName == findName)
  9503. {
  9504. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  9505. {
  9506. bestProp = prop;
  9507. bestPropTypeInst = checkTypeInst;
  9508. }
  9509. }
  9510. }
  9511. for (auto field : checkTypeInst->mTypeDef->mFields)
  9512. {
  9513. if (field->mName == findName)
  9514. {
  9515. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  9516. {
  9517. bestField = field;
  9518. bestFieldTypeInst = checkTypeInst;
  9519. }
  9520. }
  9521. }
  9522. if ((bestProp != NULL) || (bestField != NULL))
  9523. break;
  9524. checkTypeInst = checkTypeInst->mBaseType;
  9525. }
  9526. bool handledExpr = false;
  9527. if (bestField != NULL)
  9528. {
  9529. handledExpr = true;
  9530. if (mCompiler->mResolvePassData != NULL)
  9531. {
  9532. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  9533. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9534. {
  9535. autoComplete->mDefField = bestField;
  9536. autoComplete->mDefType = attrTypeDef;
  9537. }
  9538. }
  9539. if (bestField->mProtection != BfProtection_Public)
  9540. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9541. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9542. BfCustomAttributeSetField setField;
  9543. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  9544. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  9545. if (assignExpr->mRight != NULL)
  9546. {
  9547. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  9548. if (result)
  9549. {
  9550. CurrentAddToConstHolder(result.mValue);
  9551. setField.mParam = result;
  9552. customAttribute.mSetField.push_back(setField);
  9553. }
  9554. }
  9555. }
  9556. else if (bestProp == NULL)
  9557. {
  9558. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  9559. }
  9560. else
  9561. {
  9562. BfMethodDef* setMethod = NULL;
  9563. for (auto methodDef : bestProp->mMethods)
  9564. {
  9565. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9566. {
  9567. setMethod = methodDef;
  9568. break;
  9569. }
  9570. }
  9571. if (setMethod == NULL)
  9572. {
  9573. Fail("Property has no setter", assignExpr->mLeft);
  9574. }
  9575. else
  9576. {
  9577. if (mCompiler->mResolvePassData != NULL)
  9578. {
  9579. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  9580. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9581. {
  9582. autoComplete->mDefProp = bestProp;
  9583. autoComplete->mDefType = attrTypeDef;
  9584. }
  9585. }
  9586. handledExpr = true;
  9587. if (bestProp->mProtection != BfProtection_Public)
  9588. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9589. BfResolvedArg resolvedArg;
  9590. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9591. BfCustomAttributeSetProperty setProperty;
  9592. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  9593. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  9594. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  9595. if (methodInstance.mMethodInstance != NULL)
  9596. {
  9597. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  9598. if (assignExpr->mRight != NULL)
  9599. {
  9600. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  9601. if (result)
  9602. {
  9603. BF_ASSERT(result.mType == propType);
  9604. CurrentAddToConstHolder(result.mValue);
  9605. setProperty.mParam = result;
  9606. customAttribute.mSetProperties.push_back(setProperty);
  9607. }
  9608. }
  9609. }
  9610. }
  9611. }
  9612. if ((!handledExpr) && (assignExpr->mRight != NULL))
  9613. constResolver.Resolve(assignExpr->mRight);
  9614. }
  9615. else
  9616. {
  9617. if (inPropSet)
  9618. {
  9619. Fail("Named attribute argument expected", arg); // CS1016
  9620. }
  9621. BfDeferEvalChecker deferEvalChecker;
  9622. arg->Accept(&deferEvalChecker);
  9623. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  9624. BfResolvedArg resolvedArg;
  9625. resolvedArg.mExpression = arg;
  9626. if (deferParamEval)
  9627. {
  9628. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  9629. }
  9630. else
  9631. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  9632. if (!inPropSet)
  9633. {
  9634. argValues.push_back(resolvedArg);
  9635. }
  9636. }
  9637. if (autoComplete != NULL)
  9638. autoComplete->mShowAttributeProperties = NULL;
  9639. }
  9640. auto wasCapturingMethodInfo = false;
  9641. if (autoComplete != NULL)
  9642. {
  9643. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9644. if (attributesDirective->mCtorOpenParen != NULL)
  9645. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  9646. }
  9647. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  9648. attrTypeDef = attrTypeInst->mTypeDef;
  9649. bool success = true;
  9650. bool isFailurePass = false;
  9651. for (int pass = 0; pass < 2; pass++)
  9652. {
  9653. bool isFailurePass = pass == 1;
  9654. for (auto checkMethod : attrTypeDef->mMethods)
  9655. {
  9656. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  9657. continue; // Don't match private default ctor if there's a user-defined one
  9658. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  9659. continue;
  9660. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  9661. continue;
  9662. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  9663. }
  9664. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  9665. break;
  9666. }
  9667. if (autoComplete != NULL)
  9668. {
  9669. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  9670. {
  9671. autoComplete->mIsCapturingMethodMatchInfo = true;
  9672. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  9673. }
  9674. else
  9675. autoComplete->mIsCapturingMethodMatchInfo = false;
  9676. }
  9677. if (methodMatcher.mBestMethodDef == NULL)
  9678. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  9679. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  9680. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  9681. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  9682. {
  9683. Fail("Custom attribute circular reference", attributesDirective);
  9684. }
  9685. if (mCurTypeInstance != NULL)
  9686. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9687. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  9688. success = false;
  9689. for (auto& arg : argValues)
  9690. {
  9691. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  9692. {
  9693. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  9694. constResolver.Resolve(expr);
  9695. }
  9696. }
  9697. // Move all those to the constHolder
  9698. for (auto& ctorArg : customAttribute.mCtorArgs)
  9699. {
  9700. if (ctorArg.IsConst())
  9701. CurrentAddToConstHolder(ctorArg);
  9702. }
  9703. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  9704. {
  9705. targetOverride = BfAttributeTargets_ReturnValue;
  9706. if (attrTarget != BfAttributeTargets_Method)
  9707. {
  9708. 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.",
  9709. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  9710. }
  9711. success = false;
  9712. }
  9713. if ((success) && (targetOverride != (BfAttributeTargets)0))
  9714. {
  9715. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  9716. {
  9717. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  9718. if (methodInfoEx->mMethodCustomAttributes == NULL)
  9719. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  9720. if (success)
  9721. {
  9722. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  9723. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  9724. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  9725. }
  9726. }
  9727. else
  9728. {
  9729. // Failed - ignore
  9730. success = false;
  9731. }
  9732. }
  9733. if (success)
  9734. {
  9735. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  9736. {
  9737. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  9738. {
  9739. if (prevCustomAttribute.mType == attrTypeInst)
  9740. {
  9741. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  9742. }
  9743. }
  9744. }
  9745. }
  9746. if (success)
  9747. {
  9748. customAttributes->mAttributes.push_back(customAttribute);
  9749. }
  9750. }
  9751. ValidateCustomAttributes(customAttributes, attrTarget);
  9752. }
  9753. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9754. {
  9755. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  9756. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  9757. return customAttributes;
  9758. }
  9759. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  9760. {
  9761. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  9762. Warn(0, "Unused attributes", attributeState->mSrc);
  9763. }
  9764. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  9765. {
  9766. if (mCurTypeInstance->mCustomAttributes != NULL)
  9767. {
  9768. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9769. {
  9770. String typeName = TypeToString(customAttribute.mType);
  9771. if (typeName == "System.PackedAttribute")
  9772. {
  9773. isPacked = true;
  9774. }
  9775. else if (typeName == "System.UnionAttribute")
  9776. {
  9777. isUnion = true;
  9778. }
  9779. else if (typeName == "System.CReprAttribute")
  9780. {
  9781. isCRepr = true;
  9782. isOrdered = true;
  9783. }
  9784. else if (typeName == "System.OrderedAttribute")
  9785. {
  9786. isOrdered = true;
  9787. }
  9788. else if (typeName == "System.AlwaysIncludeAttribute")
  9789. {
  9790. for (auto setProp : customAttribute.mSetProperties)
  9791. {
  9792. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  9793. if (propertyDef->mName == "AssumeInstantiated")
  9794. {
  9795. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9796. if ((constant != NULL) && (constant->mBool))
  9797. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  9798. }
  9799. else if (propertyDef->mName == "IncludeAllMethods")
  9800. {
  9801. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9802. if ((constant != NULL) && (constant->mBool))
  9803. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  9804. }
  9805. }
  9806. }
  9807. else if (typeName == "System.AlignAttribute")
  9808. {
  9809. if (customAttribute.mCtorArgs.size() >= 1)
  9810. {
  9811. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9812. alignOverride = alignConstant->mInt32;
  9813. }
  9814. }
  9815. else if (typeName == "System.UnderlyingArrayAttribute")
  9816. {
  9817. if (customAttribute.mCtorArgs.size() >= 2)
  9818. {
  9819. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9820. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  9821. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  9822. {
  9823. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  9824. underlyingArraySize = sizeConstant->mInt32;
  9825. }
  9826. }
  9827. }
  9828. if (customAttribute.mType->mAttributeData == NULL)
  9829. PopulateType(customAttribute.mType);
  9830. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  9831. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  9832. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  9833. }
  9834. }
  9835. }
  9836. // Checking to see if we're an attribute or not
  9837. void BfModule::ProcessCustomAttributeData()
  9838. {
  9839. bool isAttribute = false;
  9840. auto checkTypeInst = mCurTypeInstance->mBaseType;
  9841. while (checkTypeInst != NULL)
  9842. {
  9843. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  9844. isAttribute = true;
  9845. checkTypeInst = checkTypeInst->mBaseType;
  9846. }
  9847. if (!isAttribute)
  9848. return;
  9849. auto attributeData = new BfAttributeData();
  9850. bool hasCustomAttribute = false;
  9851. if (mCurTypeInstance->mCustomAttributes != NULL)
  9852. {
  9853. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9854. {
  9855. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  9856. {
  9857. if (customAttribute.mCtorArgs.size() > 0)
  9858. {
  9859. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9860. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  9861. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9862. }
  9863. for (auto& setProp : customAttribute.mSetProperties)
  9864. {
  9865. BfPropertyDef* propDef = setProp.mPropertyRef;
  9866. if (propDef->mName == "AllowMultiple")
  9867. {
  9868. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9869. if (constant != NULL)
  9870. attributeData->mAllowMultiple = constant->mBool;
  9871. }
  9872. else if (propDef->mName == "Inherited")
  9873. {
  9874. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9875. if (constant != NULL)
  9876. attributeData->mInherited = constant->mBool;
  9877. }
  9878. else if (propDef->mName == "ValidOn")
  9879. {
  9880. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9881. if (constant != NULL)
  9882. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9883. }
  9884. else if (propDef->mName == "AlwaysIncludeUser")
  9885. {
  9886. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9887. if (constant != NULL)
  9888. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  9889. }
  9890. }
  9891. hasCustomAttribute = true;
  9892. }
  9893. }
  9894. }
  9895. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  9896. {
  9897. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  9898. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  9899. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  9900. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  9901. }
  9902. mCurTypeInstance->mAttributeData = attributeData;
  9903. }
  9904. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  9905. {
  9906. auto constant = constHolder->GetConstant(irValue);
  9907. if (constant == NULL)
  9908. return false;
  9909. if (constant->mTypeCode != BfTypeCode_StringId)
  9910. return false;
  9911. int stringId = constant->mInt32;
  9912. BfStringPoolEntry* entry = NULL;
  9913. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  9914. {
  9915. str = entry->mString;
  9916. }
  9917. else
  9918. {
  9919. BF_DBG_FATAL("Failed to find string by id");
  9920. }
  9921. return true;
  9922. }
  9923. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  9924. {
  9925. BfVariant variant;
  9926. variant.mTypeCode = BfTypeCode_None;
  9927. BfType* primType = NULL;
  9928. if (value.mType->IsPrimitiveType())
  9929. primType = (BfPrimitiveType*)value.mType;
  9930. else if (value.mType->IsTypedPrimitive())
  9931. primType = value.mType->GetUnderlyingType();
  9932. if (primType)
  9933. {
  9934. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  9935. if (constant != NULL)
  9936. {
  9937. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  9938. {
  9939. variant.mUInt64 = 0;
  9940. variant.mTypeCode = BfTypeCode_Let;
  9941. return variant;
  9942. }
  9943. switch (constant->mTypeCode)
  9944. {
  9945. case BfTypeCode_Int8:
  9946. case BfTypeCode_UInt8:
  9947. case BfTypeCode_Int16:
  9948. case BfTypeCode_UInt16:
  9949. case BfTypeCode_Int32:
  9950. case BfTypeCode_UInt32:
  9951. case BfTypeCode_Int64:
  9952. case BfTypeCode_UInt64:
  9953. case BfTypeCode_IntPtr:
  9954. case BfTypeCode_UIntPtr:
  9955. case BfTypeCode_IntUnknown:
  9956. case BfTypeCode_UIntUnknown:
  9957. case BfTypeCode_Float:
  9958. case BfTypeCode_Double:
  9959. case BfTypeCode_Char8:
  9960. case BfTypeCode_Char16:
  9961. case BfTypeCode_Char32:
  9962. variant.mTypeCode = constant->mTypeCode;
  9963. variant.mInt64 = constant->mInt64;
  9964. break;
  9965. default:
  9966. if (refNode != NULL)
  9967. Fail("Invalid const expression type", refNode);
  9968. break;
  9969. }
  9970. }
  9971. }
  9972. return variant;
  9973. }
  9974. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  9975. {
  9976. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  9977. {
  9978. auto refType = (BfRefType*)typedValue.mType;
  9979. auto elementType = typedValue.mType->GetUnderlyingType();
  9980. if (typedValue.IsAddr())
  9981. {
  9982. if (elementType->IsValuelessType())
  9983. {
  9984. BF_ASSERT(!typedValue.mValue);
  9985. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9986. }
  9987. else
  9988. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  9989. }
  9990. else
  9991. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9992. if (typedValue.mType->IsValuelessType())
  9993. {
  9994. BF_ASSERT(typedValue.mValue.IsFake());
  9995. }
  9996. if (refType->mRefKind == BfRefType::RefKind_In)
  9997. {
  9998. if (typedValue.mKind == BfTypedValueKind_Addr)
  9999. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  10000. }
  10001. }
  10002. return typedValue;
  10003. }
  10004. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  10005. {
  10006. if (refType == NULL)
  10007. refType = CreateRefType(typedValue.mType);
  10008. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  10009. {
  10010. return LoadValue(typedValue);
  10011. }
  10012. if (refType->mRefKind == BfRefType::RefKind_Mut)
  10013. refType = CreateRefType(typedValue.mType);
  10014. typedValue = MakeAddressable(typedValue);
  10015. return BfTypedValue(typedValue.mValue, refType);
  10016. }
  10017. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  10018. {
  10019. if (!typedValue.IsAddr())
  10020. return typedValue;
  10021. PopulateType(typedValue.mType);
  10022. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  10023. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  10024. if (typedValue.mValue.IsConst())
  10025. {
  10026. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  10027. if (constantValue != NULL)
  10028. {
  10029. if (constantValue->mConstType == BfConstType_GlobalVar)
  10030. {
  10031. auto globalVar = (BfGlobalVar*)constantValue;
  10032. if (globalVar->mName[0] == '#')
  10033. {
  10034. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  10035. if (result)
  10036. return result;
  10037. return GetDefaultTypedValue(typedValue.mType);
  10038. }
  10039. }
  10040. }
  10041. }
  10042. BfIRValue loadedVal = typedValue.mValue;
  10043. if (loadedVal)
  10044. {
  10045. if (typedValue.mType->IsVar())
  10046. {
  10047. return BfTypedValue(loadedVal, typedValue.mType, false);
  10048. }
  10049. /*if (isVolatile)
  10050. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  10051. PopulateType(typedValue.mType, BfPopulateType_Data);
  10052. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  10053. }
  10054. return BfTypedValue(loadedVal, typedValue.mType, false);
  10055. }
  10056. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  10057. {
  10058. if (!typedValue.mValue.IsConst())
  10059. return typedValue;
  10060. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  10061. if (constant->mTypeCode == BfTypeCode_StringId)
  10062. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  10063. return typedValue;
  10064. }
  10065. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  10066. {
  10067. if (typedValue.IsSplat())
  10068. return AggregateSplat(typedValue);
  10069. if (typedValue.IsAddr())
  10070. return LoadValue(typedValue);
  10071. return typedValue;
  10072. }
  10073. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  10074. {
  10075. if (!typedValue.IsSplat())
  10076. return typedValue;
  10077. BF_ASSERT(!mIsComptimeModule);
  10078. if (typedValue.mType->IsValuelessType())
  10079. return typedValue;
  10080. int elementIdx = 0;
  10081. auto _ExtractValue = [&](BfType* checkType)
  10082. {
  10083. if (valueArrPtr != NULL)
  10084. return valueArrPtr[elementIdx++];
  10085. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  10086. };
  10087. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10088. {
  10089. if (checkType->IsStruct())
  10090. {
  10091. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  10092. auto checkTypeInstance = checkType->ToTypeInstance();
  10093. if (checkTypeInstance->mBaseType != NULL)
  10094. {
  10095. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  10096. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  10097. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  10098. }
  10099. if (checkTypeInstance->mIsUnion)
  10100. {
  10101. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  10102. if (!unionInnerType->IsValuelessType())
  10103. {
  10104. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  10105. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  10106. }
  10107. if (checkTypeInstance->IsEnum())
  10108. {
  10109. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  10110. BfIRValue fieldValue = checkTypeLambda(dscrType);
  10111. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  10112. }
  10113. }
  10114. else
  10115. {
  10116. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10117. {
  10118. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10119. if (fieldInstance->mDataIdx >= 0)
  10120. {
  10121. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  10122. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  10123. }
  10124. }
  10125. }
  10126. return curValue;
  10127. }
  10128. else if (checkType->IsMethodRef())
  10129. {
  10130. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  10131. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  10132. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  10133. {
  10134. BfIRValue fieldValue;
  10135. auto checkType = methodRefType->GetCaptureType(dataIdx);
  10136. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  10137. {
  10138. fieldValue = checkTypeLambda(checkType);
  10139. }
  10140. else
  10141. {
  10142. fieldValue = _ExtractValue(checkType);
  10143. }
  10144. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  10145. }
  10146. return curValue;
  10147. }
  10148. else if (!checkType->IsValuelessType())
  10149. {
  10150. return _ExtractValue(checkType);
  10151. }
  10152. return BfIRValue();
  10153. };
  10154. BfIRValue value = checkTypeLambda(typedValue.mType);
  10155. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  10156. }
  10157. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  10158. {
  10159. if (!typedValue.IsSplat())
  10160. return;
  10161. if (typedValue.mType->IsValuelessType())
  10162. return;
  10163. BF_ASSERT(!mIsComptimeModule);
  10164. /*static int sCallIdx = 0;
  10165. if (!mCompiler->mIsResolveOnly)
  10166. sCallIdx++;
  10167. int callIdx = sCallIdx;*/
  10168. int elementIdx = 0;
  10169. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  10170. {
  10171. if (checkType->IsStruct())
  10172. {
  10173. auto checkTypeInstance = checkType->ToTypeInstance();
  10174. if (checkTypeInstance->mBaseType != NULL)
  10175. {
  10176. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  10177. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  10178. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  10179. }
  10180. if (checkTypeInstance->mIsUnion)
  10181. {
  10182. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  10183. if (!unionInnerType->IsValuelessType())
  10184. {
  10185. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  10186. checkTypeLambda(unionInnerType, fieldAddrVal);
  10187. }
  10188. if (checkTypeInstance->IsEnum())
  10189. {
  10190. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  10191. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  10192. checkTypeLambda(dscrType, fieldAddrVal);
  10193. }
  10194. }
  10195. else
  10196. {
  10197. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10198. {
  10199. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10200. if (fieldInstance->mDataIdx >= 0)
  10201. {
  10202. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  10203. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  10204. }
  10205. }
  10206. }
  10207. }
  10208. else if (checkType->IsMethodRef())
  10209. {
  10210. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  10211. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  10212. {
  10213. auto dataType = methodRefType->GetCaptureType(dataIdx);
  10214. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  10215. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  10216. {
  10217. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  10218. }
  10219. else
  10220. {
  10221. // static int sItrCount = 0;
  10222. // sItrCount++;
  10223. // int curItr = sItrCount;
  10224. // if (curItr == 1)
  10225. // {
  10226. // NOP;
  10227. // }
  10228. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  10229. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  10230. }
  10231. }
  10232. }
  10233. else if (!checkType->IsValuelessType())
  10234. {
  10235. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  10236. mBfIRBuilder->CreateStore(val, curAddrVal);
  10237. }
  10238. };
  10239. checkTypeLambda(typedValue.mType, addrVal);
  10240. }
  10241. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable)
  10242. {
  10243. bool wasReadOnly = typedVal.IsReadOnly();
  10244. if ((typedVal.mType->IsValueType()) &&
  10245. (!typedVal.mType->IsValuelessType()))
  10246. {
  10247. wasReadOnly = true; // Any non-addr is implicitly read-only
  10248. //static int gCallIdx = 0;
  10249. if (typedVal.IsAddr())
  10250. return typedVal;
  10251. BfType* type = typedVal.mType;
  10252. PopulateType(type);
  10253. auto tempVar = CreateAlloca(type);
  10254. if (typedVal.IsSplat())
  10255. AggregateSplatIntoAddr(typedVal, tempVar);
  10256. else
  10257. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  10258. if (forceMutable)
  10259. wasReadOnly = false;
  10260. return BfTypedValue(tempVar, type,
  10261. typedVal.IsThis() ?
  10262. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  10263. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  10264. }
  10265. return LoadValue(typedVal);
  10266. }
  10267. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  10268. {
  10269. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  10270. typedValue.mKind = BfTypedValueKind_Addr;
  10271. return typedValue;
  10272. }
  10273. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  10274. {
  10275. return MakeAddressable(LoadValue(typedValue), true);
  10276. }
  10277. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  10278. {
  10279. BF_ASSERT(!mIsComptimeModule);
  10280. BfIRValue val;
  10281. if (typedValue.mValue.IsArg())
  10282. {
  10283. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  10284. if (isAddr != NULL)
  10285. {
  10286. if (wantType != NULL)
  10287. *isAddr = wantType->IsComposite();
  10288. else
  10289. *isAddr = false;
  10290. }
  10291. else if (wantType->IsComposite())
  10292. val = mBfIRBuilder->CreateLoad(val);
  10293. }
  10294. if (!val)
  10295. {
  10296. auto checkMethodState = mCurMethodState;
  10297. while (checkMethodState != NULL)
  10298. {
  10299. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  10300. {
  10301. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  10302. if (decompAddr == typedValue.mValue)
  10303. {
  10304. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  10305. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  10306. {
  10307. // This is really backing for a POINTER to a composite inside a methodRef
  10308. val = mBfIRBuilder->CreateLoad(val);
  10309. }
  10310. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  10311. {
  10312. *isAddr = true;
  10313. return val;
  10314. }
  10315. else
  10316. {
  10317. val = mBfIRBuilder->CreateLoad(val);
  10318. break;
  10319. }
  10320. }
  10321. }
  10322. if (val)
  10323. break;
  10324. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  10325. {
  10326. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10327. return mBfIRBuilder->GetFakeVal();
  10328. }
  10329. checkMethodState = checkMethodState->mPrevMethodState;
  10330. }
  10331. }
  10332. if (val)
  10333. {
  10334. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  10335. {
  10336. BF_ASSERT(wantType != NULL);
  10337. if (wantType != NULL)
  10338. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  10339. }
  10340. return val;
  10341. }
  10342. BFMODULE_FATAL(this, "Splat not found");
  10343. return BfIRValue();
  10344. }
  10345. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  10346. {
  10347. int useFieldIdx = fieldIdx;
  10348. BfType* fieldType = NULL;
  10349. if (fieldInstance != NULL)
  10350. {
  10351. fieldType = fieldInstance->mResolvedType;
  10352. if (typedValue.mType->IsUnion())
  10353. {
  10354. if (fieldIdx == 1)
  10355. {
  10356. if (typedValue.IsSplat())
  10357. {
  10358. BfTypedValue innerVal = typedValue;
  10359. innerVal.mType = fieldType;
  10360. return innerVal;
  10361. }
  10362. }
  10363. }
  10364. }
  10365. else
  10366. {
  10367. if (typedValue.mType->IsPayloadEnum())
  10368. {
  10369. auto typeInst = typedValue.mType->ToTypeInstance();
  10370. if (fieldIdx == 1)
  10371. fieldType = typeInst->GetUnionInnerType();
  10372. else if (fieldIdx == 2)
  10373. {
  10374. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  10375. }
  10376. }
  10377. else if (typedValue.mType->IsUnion())
  10378. {
  10379. if (fieldIdx == 1)
  10380. {
  10381. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  10382. if (typedValue.IsSplat())
  10383. {
  10384. BfTypedValue innerVal = typedValue;
  10385. innerVal.mType = fieldType;
  10386. return innerVal;
  10387. }
  10388. }
  10389. }
  10390. }
  10391. BF_ASSERT(typedValue.mType->IsStruct());
  10392. if (typedValue.IsSplat())
  10393. {
  10394. if (typedValue.mType->IsPayloadEnum())
  10395. {
  10396. if (fieldIdx == 1)
  10397. {
  10398. // Payload
  10399. auto typeInst = typedValue.mType->ToTypeInstance();
  10400. auto unionInnerType = typeInst->GetUnionInnerType();
  10401. bool isAddr = false;
  10402. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  10403. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  10404. }
  10405. if (fieldIdx == 2)
  10406. {
  10407. // Discriminator
  10408. auto typeInst = typedValue.mType->ToTypeInstance();
  10409. auto unionInnerType = typeInst->GetUnionInnerType();
  10410. auto dscrType = typeInst->GetDiscriminatorType();
  10411. int argIdx = typedValue.mValue.mId;
  10412. int componentIdx = 0;
  10413. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  10414. bool isAddr;
  10415. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  10416. return BfTypedValue(irVal, dscrType, isAddr);
  10417. }
  10418. }
  10419. int componentIdx = 0;
  10420. BfTypedValue retVal;
  10421. BfFieldInstance* wantFieldInstance = fieldInstance;
  10422. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10423. {
  10424. if (checkType->IsStruct())
  10425. {
  10426. auto checkTypeInstance = checkType->ToTypeInstance();
  10427. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  10428. {
  10429. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  10430. fieldType = checkTypeInstance->GetUnionInnerType();
  10431. checkTypeLambda(fieldType);
  10432. if (checkType->IsEnum())
  10433. {
  10434. // Past discriminator...
  10435. componentIdx++;
  10436. }
  10437. return;
  10438. }
  10439. if (checkTypeInstance->mBaseType != NULL)
  10440. checkTypeLambda(checkTypeInstance->mBaseType);
  10441. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10442. {
  10443. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10444. if (fieldInstance == wantFieldInstance)
  10445. {
  10446. bool isAddr = false;
  10447. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  10448. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  10449. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  10450. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  10451. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  10452. {
  10453. retVal = LoadValue(retVal);
  10454. }
  10455. break;
  10456. }
  10457. if (fieldInstance->mDataIdx >= 0)
  10458. checkTypeLambda(fieldInstance->GetResolvedType());
  10459. }
  10460. }
  10461. else if (!checkType->IsValuelessType())
  10462. {
  10463. componentIdx++;
  10464. //argIdx++;
  10465. }
  10466. };
  10467. checkTypeLambda(typedValue.mType);
  10468. BF_ASSERT(retVal);
  10469. return retVal;
  10470. }
  10471. if (typedValue.IsAddr())
  10472. {
  10473. BF_ASSERT(fieldType != NULL);
  10474. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  10475. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  10476. }
  10477. else
  10478. {
  10479. BF_ASSERT(fieldType != NULL);
  10480. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  10481. }
  10482. }
  10483. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  10484. {
  10485. if (typedValue.IsAddr())
  10486. {
  10487. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  10488. return mBfIRBuilder->CreateLoad(addrVal);
  10489. }
  10490. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  10491. }
  10492. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  10493. {
  10494. if (isElementIndex)
  10495. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  10496. else
  10497. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10498. // if (elementType->IsSizeAligned())
  10499. // {
  10500. // if (isElementIndex)
  10501. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  10502. // else
  10503. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10504. // }
  10505. //
  10506. // auto ptrType = CreatePointerType(elementType);
  10507. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  10508. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  10509. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  10510. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  10511. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  10512. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  10513. }
  10514. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  10515. {
  10516. if (elementType->IsSizeAligned())
  10517. {
  10518. if (isElementIndex)
  10519. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  10520. else
  10521. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10522. }
  10523. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  10524. }
  10525. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  10526. {
  10527. if (modifyType == NULL)
  10528. modifyType = "modify";
  10529. if (typedValue.mType->IsVar())
  10530. return true;
  10531. if (typedValue.IsReadOnly())
  10532. {
  10533. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  10534. return false;
  10535. }
  10536. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  10537. {
  10538. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  10539. return false;
  10540. }
  10541. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  10542. {
  10543. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  10544. return false;
  10545. }
  10546. return true;
  10547. }
  10548. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10549. {
  10550. // If one is an interface and the other is an impl, B is the impl
  10551. auto implOwner = methodB->GetOwner();
  10552. if (methodA->mMethodDef->mIsLocalMethod)
  10553. {
  10554. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  10555. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  10556. if (sepPosA != sepPosB)
  10557. return false;
  10558. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  10559. return false;
  10560. }
  10561. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  10562. return false;
  10563. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  10564. return false;
  10565. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  10566. return false;
  10567. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  10568. return false;
  10569. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  10570. {
  10571. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10572. return false;
  10573. }
  10574. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  10575. {
  10576. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  10577. return false;
  10578. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  10579. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  10580. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  10581. return false;
  10582. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  10583. return false;
  10584. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  10585. return false;
  10586. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  10587. {
  10588. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  10589. return false;
  10590. }
  10591. }
  10592. int implicitParamCountA = methodA->GetImplicitParamCount();
  10593. int implicitParamCountB = methodB->GetImplicitParamCount();
  10594. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  10595. return false;
  10596. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  10597. return false;
  10598. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  10599. {
  10600. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  10601. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  10602. return false;
  10603. }
  10604. // Compare generic params. Generic params are part of the method signature here
  10605. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  10606. return false;
  10607. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  10608. {
  10609. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  10610. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  10611. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  10612. return false;
  10613. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  10614. return false;
  10615. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  10616. return false;
  10617. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  10618. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  10619. return false;
  10620. }
  10621. return true;
  10622. }
  10623. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10624. {
  10625. if (!CompareMethodSignatures(methodA, methodB))
  10626. return false;
  10627. if (methodA->mReturnType != methodB->mReturnType)
  10628. return false;
  10629. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10630. return false;
  10631. return true;
  10632. }
  10633. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  10634. {
  10635. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  10636. return false;
  10637. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  10638. return false;
  10639. if (iMethodInst->mMethodDef->mIsOperator)
  10640. {
  10641. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  10642. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  10643. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  10644. return false;
  10645. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  10646. return false;
  10647. }
  10648. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  10649. return false;
  10650. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  10651. {
  10652. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  10653. return false;
  10654. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  10655. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  10656. if (iParamType->IsSelf())
  10657. {
  10658. if (methodParamType != methodInstance->GetOwner())
  10659. return false;
  10660. }
  10661. else if (!iParamType->IsGenericParam())
  10662. {
  10663. if (methodParamType != iParamType)
  10664. return false;
  10665. }
  10666. else
  10667. {
  10668. if (!methodParamType->IsGenericParam())
  10669. return false;
  10670. auto genericParamType = (BfGenericParamType*)methodParamType;
  10671. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  10672. return false;
  10673. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  10674. bool hadInterface = false;
  10675. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  10676. if (interfaceConstraint == iParamType)
  10677. hadInterface = true;
  10678. if (!hadInterface)
  10679. return false;
  10680. }
  10681. }
  10682. return true;
  10683. }
  10684. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  10685. {
  10686. BfMethodInstance* methodInstance = methodRef;
  10687. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  10688. {
  10689. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  10690. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  10691. {
  10692. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  10693. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  10694. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10695. BfMethodRef methodRef = methodInstance;
  10696. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  10697. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  10698. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  10699. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  10700. (mIsReified))
  10701. {
  10702. specializedMethodRefInfo->mHasReifiedRef = true;
  10703. }
  10704. }
  10705. }
  10706. }
  10707. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10708. {
  10709. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  10710. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10711. if (mBfIRBuilder == NULL)
  10712. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10713. if (methodInstance->GetOwner()->IsFunction())
  10714. {
  10715. // No actual ref needed- not an actual generated function
  10716. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10717. }
  10718. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  10719. if (!isGenFunction)
  10720. AddMethodReference(methodInstance, flags);
  10721. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  10722. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  10723. if (IsSkippingExtraResolveChecks())
  10724. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10725. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10726. {
  10727. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10728. }
  10729. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10730. BfMethodRef methodRef = methodInstance;
  10731. if (isInlined)
  10732. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  10733. else
  10734. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  10735. if (!isGenFunction)
  10736. {
  10737. BfIRValue* irFuncPtr = NULL;
  10738. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  10739. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  10740. }
  10741. if (mAwaitingInitFinish)
  10742. FinishInit();
  10743. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  10744. if (!isGenFunction)
  10745. {
  10746. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  10747. mFuncReferences[methodRef] = func;
  10748. }
  10749. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  10750. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  10751. {
  10752. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  10753. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  10754. // type instance
  10755. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  10756. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  10757. for (auto ownedTypeInst : mOwnedTypeInstances)
  10758. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  10759. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  10760. {
  10761. mIncompleteMethodCount++;
  10762. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10763. inlineMethodRequest->mType = methodInstance->GetOwner();
  10764. inlineMethodRequest->mFromModule = this;
  10765. inlineMethodRequest->mFunc = func;
  10766. inlineMethodRequest->mFromModuleRevision = mRevision;
  10767. inlineMethodRequest->mMethodInstance = methodInstance;
  10768. BF_ASSERT(mIsModuleMutable);
  10769. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10770. }
  10771. }
  10772. return BfModuleMethodInstance(methodInstance, func);
  10773. }
  10774. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  10775. {
  10776. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  10777. if (mBfIRBuilder == NULL)
  10778. {
  10779. // To allow for custom attribute data
  10780. PrepareForIRWriting(typeInst);
  10781. }
  10782. BfModule* declareModule = this;
  10783. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  10784. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  10785. declareModule = declareModule->mParentModule;
  10786. // Check for attributes
  10787. if (typeInst == mContext->mBfObjectType)
  10788. {
  10789. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  10790. if (methodDecl != NULL)
  10791. {
  10792. auto attributesDirective = methodDecl->mAttributes;
  10793. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  10794. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  10795. {
  10796. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  10797. }
  10798. }
  10799. }
  10800. else
  10801. {
  10802. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  10803. GetMethodCustomAttributes(methodInstance);
  10804. }
  10805. BF_ASSERT(mModuleOptions == NULL);
  10806. if (methodInstance->GetCustomAttributes() != NULL)
  10807. {
  10808. auto project = typeInst->mTypeDef->mProject;
  10809. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  10810. BfModuleOptions wantOptions = moduleOptions;
  10811. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  10812. if (typeOptions != NULL)
  10813. {
  10814. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  10815. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  10816. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  10817. }
  10818. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  10819. {
  10820. StringT<128> attrName;
  10821. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  10822. {
  10823. attrName.Clear();
  10824. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  10825. Array<int>* arrPtr;
  10826. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  10827. {
  10828. for (auto optionsIdx : *arrPtr)
  10829. {
  10830. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  10831. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  10832. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  10833. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  10834. }
  10835. }
  10836. }
  10837. }
  10838. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  10839. {
  10840. auto lastCheckModule = this;
  10841. auto checkModule = this->mNextAltModule;
  10842. while (checkModule != NULL)
  10843. {
  10844. if (*checkModule->mModuleOptions == wantOptions)
  10845. {
  10846. declareModule = checkModule;
  10847. break;
  10848. }
  10849. lastCheckModule = checkModule;
  10850. checkModule = checkModule->mNextAltModule;
  10851. }
  10852. // Not found?
  10853. if (declareModule == this)
  10854. {
  10855. String specModuleName = mModuleName + "@@";
  10856. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  10857. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  10858. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  10859. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  10860. declareModule = new BfModule(mContext, specModuleName);
  10861. declareModule->mProject = project;
  10862. declareModule->mModuleOptions = new BfModuleOptions();
  10863. *declareModule->mModuleOptions = wantOptions;
  10864. declareModule->mParentModule = lastCheckModule;
  10865. declareModule->Init();
  10866. lastCheckModule->mNextAltModule = declareModule;
  10867. }
  10868. }
  10869. }
  10870. declareModule->PrepareForIRWriting(typeInst);
  10871. return declareModule;
  10872. }
  10873. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  10874. {
  10875. if (methodDef->mMethodType == BfMethodType_Init)
  10876. return BfModuleMethodInstance();
  10877. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  10878. {
  10879. // Don't bother inlining for resolve-only
  10880. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10881. }
  10882. bool processNow = false;
  10883. bool keepInCurrentModule = false;
  10884. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  10885. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  10886. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  10887. {
  10888. return BfModuleMethodInstance();
  10889. }
  10890. if (methodDef->mIsLocalMethod)
  10891. {
  10892. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10893. BfLocalMethod* localMethod;
  10894. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  10895. {
  10896. // Handle the def in the correct method state
  10897. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  10898. }
  10899. BFMODULE_FATAL(this, "Cannot find local method");
  10900. return BfModuleMethodInstance();
  10901. }
  10902. #ifdef _DEBUG
  10903. for (auto arg : methodGenericArguments)
  10904. BF_ASSERT(!arg->IsVar());
  10905. #endif
  10906. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  10907. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  10908. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  10909. // a FinishInit
  10910. if ((typeInst->IsIncomplete()) &&
  10911. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  10912. {
  10913. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  10914. // for resolve-only because we don't differentiate between reified/unreified there
  10915. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  10916. {
  10917. if (!typeInst->DefineStateAllowsStaticMethods())
  10918. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  10919. }
  10920. else
  10921. PopulateType(typeInst, BfPopulateType_Full);
  10922. }
  10923. bool tryModuleMethodLookup = false;
  10924. BfModuleMethodInstance moduleMethodInst;
  10925. BfModule* instModule = typeInst->mModule;
  10926. if (keepInCurrentModule)
  10927. {
  10928. // Stay here
  10929. instModule = this;
  10930. }
  10931. if (this == mContext->mUnreifiedModule)
  10932. {
  10933. // Stay in this 'resolve only' module here
  10934. }
  10935. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  10936. {
  10937. BF_ASSERT(this == mContext->mUnreifiedModule);
  10938. }
  10939. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  10940. {
  10941. BF_ASSERT(instModule == mParentModule);
  10942. }
  10943. else if (instModule != this)
  10944. {
  10945. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  10946. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  10947. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  10948. {
  10949. BF_ASSERT(!mCompiler->mIsResolveOnly);
  10950. // A resolve-only module is specializing a method from a type in a reified module,
  10951. // we need to take care that this doesn't cause anything new to become reified
  10952. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  10953. if (!moduleMethodInstance)
  10954. return moduleMethodInstance;
  10955. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  10956. return moduleMethodInstance;
  10957. }
  10958. else
  10959. {
  10960. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  10961. {
  10962. if (!typeInst->IsUnspecializedTypeVariation())
  10963. {
  10964. if (!instModule->mReifyQueued)
  10965. {
  10966. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  10967. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  10968. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  10969. mContext->mReifyModuleWorkList.Add(instModule);
  10970. instModule->mReifyQueued = true;
  10971. }
  10972. // This ensures that the method will actually be created when it gets reified
  10973. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  10974. specializationRequest->mFromModule = typeInst->mModule;
  10975. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  10976. specializationRequest->Init(typeInst, foreignType, methodDef);
  10977. //specializationRequest->mMethodDef = methodDef;
  10978. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  10979. specializationRequest->mType = typeInst;
  10980. specializationRequest->mFlags = flags;
  10981. }
  10982. }
  10983. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10984. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  10985. if (mIsComptimeModule)
  10986. {
  10987. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  10988. if (!mCompiler->mIsResolveOnly)
  10989. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  10990. }
  10991. // Not extern
  10992. // Create the instance in the proper module and then create a reference in this one
  10993. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  10994. if (!moduleMethodInst)
  10995. return moduleMethodInst;
  10996. tryModuleMethodLookup = true;
  10997. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  10998. {
  10999. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  11000. }
  11001. }
  11002. }
  11003. if (tryModuleMethodLookup)
  11004. {
  11005. SetMethodDependency(moduleMethodInst.mMethodInstance);
  11006. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  11007. }
  11008. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  11009. {
  11010. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  11011. if (moduleMethodInstance)
  11012. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  11013. return moduleMethodInst;
  11014. }
  11015. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  11016. bool hadConcreteInterfaceGenericArgument = false;
  11017. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  11018. isReified = false;
  11019. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  11020. {
  11021. isReified = false;
  11022. }
  11023. BfTypeVector sanitizedMethodGenericArguments;
  11024. SizedArray<BfProject*, 4> projectList;
  11025. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  11026. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  11027. isUnspecializedPass = false;
  11028. // 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
  11029. bool isExternalExtensionMethod = false;
  11030. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  11031. {
  11032. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  11033. {
  11034. auto specProject = methodDef->mDeclaringType->mProject;
  11035. isExternalExtensionMethod = true;
  11036. if (typeInst->IsGenericTypeInstance())
  11037. {
  11038. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11039. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11040. genericTypeInst->GenerateProjectsReferenced();
  11041. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  11042. {
  11043. // This is a generic type where a generic param is already confined to the project in question
  11044. isExternalExtensionMethod = false;
  11045. }
  11046. }
  11047. if (isExternalExtensionMethod)
  11048. {
  11049. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  11050. projectList.push_back(methodDef->mDeclaringType->mProject);
  11051. }
  11052. }
  11053. }
  11054. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  11055. {
  11056. int typeProjectsCounts = 0;
  11057. if (typeInst->IsGenericTypeInstance())
  11058. {
  11059. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11060. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  11061. genericTypeInst->GenerateProjectsReferenced();
  11062. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  11063. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  11064. }
  11065. else
  11066. {
  11067. typeProjectsCounts = 1;
  11068. projectList.Insert(0, typeInst->mTypeDef->mProject);
  11069. }
  11070. isUnspecializedPass = true;
  11071. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  11072. {
  11073. auto genericArgType = methodGenericArguments[genericArgIdx];
  11074. //BF_ASSERT(!genericArgType->IsRef());
  11075. if (genericArgType->IsConcreteInterfaceType())
  11076. {
  11077. hadConcreteInterfaceGenericArgument = true;
  11078. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  11079. genericArgType = concreteInterfaceType->mInterface;
  11080. }
  11081. if (genericArgType->IsGenericParam())
  11082. {
  11083. auto genericParam = (BfGenericParamType*) genericArgType;
  11084. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  11085. isUnspecializedPass = false;
  11086. }
  11087. else
  11088. {
  11089. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  11090. isUnspecializedPass = false;
  11091. }
  11092. sanitizedMethodGenericArguments.push_back(genericArgType);
  11093. }
  11094. if ((int)projectList.size() > typeProjectsCounts)
  11095. {
  11096. // Just leave the new items
  11097. projectList.RemoveRange(0, typeProjectsCounts);
  11098. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  11099. {
  11100. return lhs->mName < rhs->mName;
  11101. });
  11102. }
  11103. else
  11104. {
  11105. projectList.Clear();
  11106. }
  11107. }
  11108. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  11109. BfMethodInstanceGroup* methodInstGroup = NULL;
  11110. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  11111. {
  11112. BF_ASSERT(!typeInst->IsInterface());
  11113. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  11114. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  11115. {
  11116. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  11117. // if (checkGroup.mDefault == NULL)
  11118. // {
  11119. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  11120. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  11121. // methodInstGroup = &checkGroup;
  11122. // break;
  11123. // }
  11124. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  11125. {
  11126. methodInstGroup = &checkGroup;
  11127. break;
  11128. }
  11129. }
  11130. if (methodInstGroup == NULL)
  11131. {
  11132. // Allocate a new entry
  11133. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  11134. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  11135. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  11136. methodInstGroup->mOwner = typeInst;
  11137. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  11138. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11139. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  11140. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11141. else
  11142. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  11143. }
  11144. }
  11145. else
  11146. {
  11147. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  11148. }
  11149. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  11150. {
  11151. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  11152. {
  11153. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  11154. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  11155. }
  11156. }
  11157. BfIRFunction prevIRFunc;
  11158. bool doingRedeclare = false;
  11159. BfMethodInstance* methodInstance = NULL;
  11160. auto _SetReified = [&]()
  11161. {
  11162. methodInstance->mIsReified = true;
  11163. };
  11164. if (lookupMethodGenericArguments.size() == 0)
  11165. {
  11166. methodInstance = methodInstGroup->mDefault;
  11167. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  11168. return methodInstance;
  11169. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  11170. {
  11171. MarkDerivedDirty(typeInst);
  11172. if (mIsScratchModule)
  11173. {
  11174. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  11175. _SetReified();
  11176. CheckHotMethod(methodInstance, "");
  11177. }
  11178. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  11179. {
  11180. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  11181. // the specializations to handle that for us
  11182. return BfModuleMethodInstance(methodInstance);
  11183. }
  11184. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  11185. {
  11186. if (methodDef->mIsAbstract)
  11187. {
  11188. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  11189. _SetReified();
  11190. }
  11191. else
  11192. {
  11193. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  11194. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  11195. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  11196. doingRedeclare = true;
  11197. mOnDemandMethodCount++;
  11198. VerifyOnDemandMethods();
  11199. }
  11200. }
  11201. else
  11202. {
  11203. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  11204. // We haven't processed it yet
  11205. _SetReified();
  11206. CheckHotMethod(methodInstance, "");
  11207. if (methodInstance->mDeclModule == this)
  11208. {
  11209. if (methodInstance->mMethodProcessRequest != NULL)
  11210. {
  11211. // Disconnect method process request
  11212. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  11213. }
  11214. }
  11215. else
  11216. {
  11217. if (methodInstance->mMethodProcessRequest != NULL)
  11218. {
  11219. // Disconnect method process request
  11220. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  11221. methodInstance->mMethodProcessRequest = NULL;
  11222. }
  11223. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  11224. {
  11225. // Add new request in proper module
  11226. methodInstance->mDeclModule = this;
  11227. }
  11228. else
  11229. {
  11230. if (methodInstance->mDeclModule == NULL)
  11231. {
  11232. //
  11233. }
  11234. else if (methodInstance->mDeclModule != this)
  11235. {
  11236. // Is from specialized module?
  11237. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  11238. }
  11239. }
  11240. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  11241. {
  11242. methodInstance->mIRFunction = BfIRFunction();
  11243. if (!mIsModuleMutable)
  11244. StartExtension();
  11245. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  11246. {
  11247. StringT<128> mangledName;
  11248. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  11249. bool isIntrinsic = false;
  11250. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  11251. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  11252. }
  11253. }
  11254. AddMethodToWorkList(methodInstance);
  11255. }
  11256. }
  11257. }
  11258. }
  11259. else
  11260. {
  11261. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  11262. if (methodInstGroup->mMethodSpecializationMap == NULL)
  11263. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  11264. BfMethodInstance** methodInstancePtr = NULL;
  11265. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  11266. {
  11267. methodInstance = *methodInstancePtr;
  11268. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  11269. return methodInstance;
  11270. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  11271. {
  11272. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  11273. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  11274. if (methodInstance->mMethodProcessRequest == NULL)
  11275. AddMethodToWorkList(methodInstance);
  11276. methodInstance->mRequestedByAutocomplete = false;
  11277. }
  11278. if ((isReified) && (!methodInstance->mIsReified))
  11279. {
  11280. MarkDerivedDirty(typeInst);
  11281. if (methodInstance->mHasBeenProcessed)
  11282. {
  11283. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  11284. delete methodInstance;
  11285. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  11286. methodInstance = NULL;
  11287. }
  11288. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  11289. {
  11290. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  11291. delete methodInstance;
  11292. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  11293. methodInstance = NULL;
  11294. }
  11295. else
  11296. {
  11297. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  11298. // We haven't processed it yet
  11299. _SetReified();
  11300. CheckHotMethod(methodInstance, "");
  11301. }
  11302. }
  11303. }
  11304. }
  11305. if ((methodInstance != NULL) && (!doingRedeclare))
  11306. {
  11307. SetMethodDependency(methodInstance);
  11308. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  11309. {
  11310. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  11311. BF_ASSERT(!methodInstance->mIsReified);*/
  11312. if (methodInstance->mIsReified != isReified)
  11313. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  11314. if ((!isReified) &&
  11315. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  11316. {
  11317. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  11318. methodInstance->mIRFunction = BfIRFunction();
  11319. }
  11320. methodInstance->mIsReified = isReified;
  11321. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  11322. {
  11323. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  11324. }
  11325. if (!methodInstance->mMethodDef->mIsAbstract)
  11326. {
  11327. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  11328. {
  11329. // Wait until unreified
  11330. }
  11331. else
  11332. AddMethodToWorkList(methodInstance);
  11333. }
  11334. else
  11335. {
  11336. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  11337. auto owningModule = methodInstance->GetOwner()->mModule;
  11338. if (!owningModule->mIsScratchModule)
  11339. {
  11340. owningModule->mOnDemandMethodCount--;
  11341. owningModule->VerifyOnDemandMethods();
  11342. }
  11343. }
  11344. }
  11345. if (mExtensionCount > 0)
  11346. {
  11347. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  11348. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  11349. {
  11350. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  11351. if (mAwaitingInitFinish)
  11352. FinishInit();
  11353. // We need to refer to a function that was defined in a prior module
  11354. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  11355. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  11356. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  11357. methodInstance->mDeclModule = this;
  11358. // Add this inlined def to ourselves
  11359. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  11360. {
  11361. mIncompleteMethodCount++;
  11362. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  11363. inlineMethodRequest->mType = typeInst;
  11364. inlineMethodRequest->mFromModule = this;
  11365. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  11366. inlineMethodRequest->mFromModuleRevision = mRevision;
  11367. inlineMethodRequest->mMethodInstance = methodInstance;
  11368. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  11369. BF_ASSERT(mIsModuleMutable);
  11370. }
  11371. }
  11372. }
  11373. if (IsSkippingExtraResolveChecks())
  11374. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11375. else
  11376. {
  11377. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  11378. return methodInstance;
  11379. if (methodInstance->mDeclModule != this)
  11380. return ReferenceExternalMethodInstance(methodInstance, flags);
  11381. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  11382. {
  11383. auto importKind = methodInstance->GetImportCallKind();
  11384. if (importKind != BfImportCallKind_None)
  11385. {
  11386. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  11387. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  11388. auto func = CreateDllImportGlobalVar(methodInstance, true);
  11389. BF_ASSERT(func);
  11390. mFuncReferences[methodInstance] = func;
  11391. }
  11392. }
  11393. return BfModuleMethodInstance(methodInstance);
  11394. }
  11395. }
  11396. if (!doingRedeclare)
  11397. {
  11398. BfModule* specModule = NULL;
  11399. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  11400. {
  11401. specModule = GetSpecializedMethodModule(projectList);
  11402. }
  11403. if ((specModule != NULL) && (specModule != this))
  11404. {
  11405. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  11406. if (mAwaitingInitFinish)
  11407. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  11408. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  11409. return specMethodInstance.mMethodInstance;
  11410. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  11411. }
  11412. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  11413. {
  11414. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  11415. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  11416. }
  11417. }
  11418. if (methodInstance == NULL)
  11419. {
  11420. if (lookupMethodGenericArguments.size() == 0)
  11421. {
  11422. BF_ASSERT(methodInstGroup->mDefault == NULL);
  11423. methodInstance = new BfMethodInstance();
  11424. methodInstGroup->mDefault = methodInstance;
  11425. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  11426. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  11427. }
  11428. else
  11429. {
  11430. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  11431. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  11432. depthExceeded = true;
  11433. if (depthExceeded)
  11434. {
  11435. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  11436. return BfModuleMethodInstance();
  11437. }
  11438. BfMethodInstance** methodInstancePtr = NULL;
  11439. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  11440. BF_ASSERT(added);
  11441. methodInstance = new BfMethodInstance();
  11442. *methodInstancePtr = methodInstance;
  11443. if (mCompiler->IsAutocomplete())
  11444. methodInstance->mRequestedByAutocomplete = true;
  11445. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  11446. }
  11447. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  11448. methodInstance->mIRFunction = prevIRFunc; // Take it over
  11449. }
  11450. methodInstance->mMethodDef = methodDef;
  11451. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  11452. methodInstance->mMethodInstanceGroup = methodInstGroup;
  11453. methodInstance->mIsReified = isReified;
  11454. SetupMethodIdHash(methodInstance);
  11455. if (hadConcreteInterfaceGenericArgument)
  11456. methodInstance->mIgnoreBody = true;
  11457. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  11458. {
  11459. methodInstance->mIsForeignMethodDef = true;
  11460. BF_ASSERT(foreignType != NULL);
  11461. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  11462. }
  11463. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  11464. {
  11465. if (!lookupMethodGenericArguments.empty())
  11466. {
  11467. auto compareType = lookupMethodGenericArguments[0];
  11468. PopulateType(compareType, BfPopulateType_Data);
  11469. if (compareType->IsSplattable())
  11470. methodInstance->mAlwaysInline = true;
  11471. }
  11472. }
  11473. if (methodDef->mMethodType == BfMethodType_Init)
  11474. {
  11475. methodInstance->mMangleWithIdx = true;
  11476. }
  11477. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  11478. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  11479. declareModule = methodInstance->mDeclModule;
  11480. BF_ASSERT(typeInst == methodInstance->GetOwner());
  11481. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11482. if (isUnspecializedPass)
  11483. {
  11484. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  11485. {
  11486. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  11487. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  11488. }
  11489. }
  11490. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  11491. {
  11492. if (!sanitizedMethodGenericArguments.IsEmpty())
  11493. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  11494. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  11495. {
  11496. Fail("Internal error");
  11497. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  11498. return NULL;
  11499. }
  11500. for (auto genericArg : sanitizedMethodGenericArguments)
  11501. {
  11502. if (genericArg->IsPrimitiveType())
  11503. genericArg = GetWrappedStructType(genericArg);
  11504. if (genericArg != NULL)
  11505. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  11506. }
  11507. }
  11508. // Generic constraints
  11509. if (!methodDef->mGenericParams.IsEmpty())
  11510. {
  11511. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  11512. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  11513. {
  11514. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  11515. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11516. }
  11517. }
  11518. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  11519. {
  11520. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  11521. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11522. }
  11523. bool addToWorkList = !processNow;
  11524. if (mCompiler->GetAutoComplete() != NULL)
  11525. {
  11526. if (typeInst->IsSpecializedByAutoCompleteMethod())
  11527. addToWorkList = false;
  11528. if (methodInstance->mRequestedByAutocomplete)
  11529. addToWorkList = false;
  11530. }
  11531. BF_ASSERT(declareModule != NULL);
  11532. methodInstance->mDeclModule = declareModule;
  11533. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  11534. {
  11535. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  11536. // of a reified module -
  11537. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  11538. // BUT if we don't reify it then we have to remove the body after processing.
  11539. // 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
  11540. // the proper reified module.
  11541. declareModule = mContext->mUnreifiedModule;
  11542. }
  11543. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  11544. {
  11545. if (!methodInstance->mIsReified)
  11546. {
  11547. declareModule = mContext->mUnreifiedModule;
  11548. }
  11549. else
  11550. {
  11551. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  11552. }
  11553. }
  11554. SetMethodDependency(methodInstance);
  11555. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  11556. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  11557. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  11558. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  11559. {
  11560. // For mixins we only process the unspecialized version
  11561. addToWorkList = false;
  11562. }
  11563. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  11564. {
  11565. addToWorkList = false;
  11566. }
  11567. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  11568. // addToWorkList = false;
  11569. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  11570. if (processNow)
  11571. {
  11572. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  11573. ProcessMethod(methodInstance);
  11574. }
  11575. if (IsSkippingExtraResolveChecks())
  11576. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11577. if (methodInstance->mDeclModule != this)
  11578. return ReferenceExternalMethodInstance(methodInstance, flags);
  11579. return BfModuleMethodInstance(methodInstance);
  11580. }
  11581. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11582. {
  11583. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  11584. if (methodInstance->mIsForeignMethodDef)
  11585. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  11586. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  11587. }
  11588. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  11589. {
  11590. if (!methodInstance->mMethodDef->mIsLocalMethod)
  11591. return NULL;
  11592. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  11593. if (outerLocal == NULL)
  11594. return NULL;
  11595. BfTypeVector genericArgs;
  11596. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  11597. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  11598. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  11599. }
  11600. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  11601. {
  11602. HashContext hashCtx;
  11603. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  11604. {
  11605. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  11606. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  11607. if (methodInstance->GetNumGenericArguments() != 0)
  11608. {
  11609. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  11610. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  11611. hashCtx.Mixin(methodGenericArg->mTypeId);
  11612. }
  11613. };
  11614. _MixinMethodInstance(methodInstance);
  11615. if (methodInstance->mMethodDef->mIsLocalMethod)
  11616. {
  11617. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  11618. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  11619. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  11620. }
  11621. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  11622. }
  11623. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  11624. {
  11625. if (methodInstance->mHasBeenDeclared)
  11626. return true;
  11627. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  11628. return false;
  11629. }
  11630. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  11631. {
  11632. BfIRValue globalValue;
  11633. BfIRValue* globalValuePtr = NULL;
  11634. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  11635. {
  11636. globalValue = *globalValuePtr;
  11637. }
  11638. if (!globalValue)
  11639. {
  11640. // This is necessary to reify the interface type
  11641. PopulateType(ifaceType);
  11642. StringT<128> slotVarName;
  11643. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  11644. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  11645. BfIRValue value;
  11646. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  11647. {
  11648. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  11649. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  11650. int virtSlotIdx = ifaceType->mSlotNum + 1;
  11651. value = GetConstValue32(virtSlotIdx);*/
  11652. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  11653. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  11654. }
  11655. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  11656. mInterfaceSlotRefs[ifaceType] = globalValue;
  11657. }
  11658. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  11659. }
  11660. void BfModule::HadSlotCountDependency()
  11661. {
  11662. if (mCompiler->mIsResolveOnly)
  11663. return;
  11664. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  11665. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  11666. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  11667. }
  11668. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  11669. {
  11670. if (str == "#IsComptime")
  11671. {
  11672. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  11673. }
  11674. if (str == "#IsBuilding")
  11675. {
  11676. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  11677. }
  11678. if (str == "#IsReified")
  11679. {
  11680. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  11681. }
  11682. if (str == "#CompileRev")
  11683. {
  11684. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  11685. }
  11686. if (str == "#ModuleName")
  11687. {
  11688. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  11689. }
  11690. if (str == "#ProjectName")
  11691. {
  11692. if (mProject != NULL)
  11693. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  11694. }
  11695. if (str == "#TimeLocal")
  11696. {
  11697. time_t rawtime;
  11698. time(&rawtime);
  11699. tm* timeinfo = localtime(&rawtime);
  11700. char result[32];
  11701. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  11702. 1900 + timeinfo->tm_year,
  11703. timeinfo->tm_mon,
  11704. timeinfo->tm_mday,
  11705. timeinfo->tm_hour,
  11706. timeinfo->tm_min,
  11707. timeinfo->tm_sec);
  11708. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  11709. }
  11710. return BfTypedValue();
  11711. }
  11712. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  11713. {
  11714. BfIRValue globalValue;
  11715. auto fieldDef = fieldInstance->GetFieldDef();
  11716. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  11717. {
  11718. if (fieldInstance->mConstIdx != -1)
  11719. {
  11720. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  11721. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  11722. }
  11723. else
  11724. {
  11725. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  11726. }
  11727. }
  11728. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly))
  11729. {
  11730. // Just fake it for the extern and unspecialized modules
  11731. // We can't do this for compilation because unreified methods with default params need to get acutal global variable refs
  11732. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  11733. }
  11734. BfIRValue* globalValuePtr = NULL;
  11735. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  11736. {
  11737. globalValue = *globalValuePtr;
  11738. BF_ASSERT(globalValue);
  11739. }
  11740. else
  11741. {
  11742. StringT<128> staticVarName;
  11743. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  11744. auto typeType = fieldInstance->GetResolvedType();
  11745. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  11746. {
  11747. typeType = typeType->GetUnderlyingType();
  11748. }
  11749. if (mIsComptimeModule)
  11750. {
  11751. mCompiler->mCEMachine->QueueStaticField(fieldInstance, staticVarName);
  11752. }
  11753. PopulateType(typeType);
  11754. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  11755. {
  11756. BfIRType irType = mBfIRBuilder->MapType(typeType);
  11757. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  11758. globalValue = mBfIRBuilder->CreateGlobalVariable(
  11759. irType,
  11760. false,
  11761. BfIRLinkageType_External,
  11762. BfIRValue(),
  11763. staticVarName,
  11764. IsThreadLocal(fieldInstance));
  11765. if (!mBfIRBuilder->mIgnoreWrites)
  11766. {
  11767. // Only store this if we actually did the creation
  11768. BF_ASSERT(globalValue);
  11769. mStaticFieldRefs[fieldInstance] = globalValue;
  11770. }
  11771. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  11772. }
  11773. }
  11774. auto type = fieldInstance->GetResolvedType();
  11775. if (type->IsValuelessType())
  11776. return BfTypedValue(globalValue, type);
  11777. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  11778. }
  11779. BfTypedValue BfModule::GetThis()
  11780. {
  11781. auto useMethodState = mCurMethodState;
  11782. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  11783. {
  11784. useMethodState = useMethodState->mPrevMethodState;
  11785. }
  11786. if (useMethodState != NULL)
  11787. {
  11788. // Fake a 'this' for var field resolution
  11789. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  11790. {
  11791. auto thisType = mCurTypeInstance;
  11792. if (thisType->IsValueType())
  11793. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  11794. else
  11795. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  11796. }
  11797. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  11798. {
  11799. return BfTypedValue();
  11800. }
  11801. }
  11802. else
  11803. {
  11804. //TODO: Do we allow useMethodState to be NULL anymore?
  11805. return BfTypedValue();
  11806. }
  11807. // if (useMethodState->HasNonStaticMixin())
  11808. // {
  11809. // auto checkMethodState = useMethodState;
  11810. // while (checkMethodState != NULL)
  11811. // {
  11812. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  11813. // {
  11814. // auto varDecl = checkMethodState->mLocals[localIdx];
  11815. // if (varDecl->mName == "this")
  11816. // {
  11817. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11818. // if (varDecl->mIsSplat)
  11819. // {
  11820. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11821. // }
  11822. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  11823. // {
  11824. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  11825. // }
  11826. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  11827. // }
  11828. // }
  11829. //
  11830. // checkMethodState = checkMethodState->mPrevMethodState;
  11831. // }
  11832. // }
  11833. // Check mixin state for 'this'
  11834. {
  11835. auto checkMethodState = mCurMethodState;
  11836. while (checkMethodState != NULL)
  11837. {
  11838. if (checkMethodState->mMixinState != NULL)
  11839. {
  11840. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  11841. if (thisValue.HasType())
  11842. {
  11843. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11844. if (!thisValue.mType->IsValueType())
  11845. thisValue = LoadValue(thisValue);
  11846. return thisValue;
  11847. }
  11848. }
  11849. checkMethodState = checkMethodState->mPrevMethodState;
  11850. }
  11851. }
  11852. auto curMethodInstance = mCurMethodInstance;
  11853. if (useMethodState->mMethodInstance != NULL)
  11854. curMethodInstance = useMethodState->mMethodInstance;
  11855. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  11856. {
  11857. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  11858. {
  11859. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  11860. if (constLocal.mIsThis)
  11861. {
  11862. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  11863. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  11864. }
  11865. }
  11866. return BfTypedValue();
  11867. }
  11868. if (useMethodState->mLocals.IsEmpty())
  11869. {
  11870. // 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
  11871. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  11872. return BfTypedValue();
  11873. }
  11874. auto thisLocal = useMethodState->mLocals[0];
  11875. BF_ASSERT(thisLocal->mIsThis);
  11876. bool preferValue = !IsTargetingBeefBackend();
  11877. if (!thisLocal->mAddr)
  11878. preferValue = true;
  11879. bool usedVal = false;
  11880. BfIRValue thisValue;
  11881. if ((preferValue) && (!thisLocal->mIsLowered))
  11882. {
  11883. thisValue = thisLocal->mValue;
  11884. usedVal = true;
  11885. }
  11886. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  11887. thisValue = thisLocal->mAddr;
  11888. else
  11889. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  11890. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11891. if (useMethodState->mClosureState != NULL)
  11892. {
  11893. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  11894. if (closureTypeInst != NULL)
  11895. {
  11896. if (closureTypeInst->mFieldInstances.size() > 0)
  11897. {
  11898. auto& field = closureTypeInst->mFieldInstances[0];
  11899. auto fieldDef = field.GetFieldDef();
  11900. if (fieldDef->mName == "__this")
  11901. {
  11902. if (mCurMethodState->mClosureState->mCapturing)
  11903. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11904. // This is a captured 'this'
  11905. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11906. if (field.mResolvedType->IsRef())
  11907. {
  11908. auto refType = (BfRefType*)field.mResolvedType;
  11909. auto underlyingType = refType->GetUnderlyingType();
  11910. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  11911. }
  11912. if (field.mResolvedType->IsObject())
  11913. {
  11914. result = LoadValue(result);
  11915. result.mKind = BfTypedValueKind_ThisValue;
  11916. }
  11917. else
  11918. {
  11919. if (fieldDef->mIsReadOnly)
  11920. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  11921. else
  11922. result.mKind = BfTypedValueKind_ThisAddr;
  11923. }
  11924. return result;
  11925. }
  11926. }
  11927. return BfTypedValue();
  11928. }
  11929. if (useMethodState->mClosureState->mCapturing)
  11930. {
  11931. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  11932. if (thisType->IsValueType())
  11933. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  11934. else
  11935. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  11936. }
  11937. }
  11938. auto localDef = useMethodState->mLocals[0];
  11939. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  11940. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  11941. {
  11942. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  11943. {
  11944. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  11945. }
  11946. if (localDef->mIsSplat)
  11947. {
  11948. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11949. }
  11950. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  11951. }
  11952. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  11953. }
  11954. BfLocalVariable* BfModule::GetThisVariable()
  11955. {
  11956. if (mCurMethodState == NULL)
  11957. return NULL;
  11958. auto methodState = mCurMethodState->GetNonCaptureState();
  11959. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  11960. return methodState->mLocals[0];
  11961. return NULL;
  11962. }
  11963. bool BfModule::IsInGeneric()
  11964. {
  11965. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  11966. }
  11967. bool BfModule::InDefinitionSection()
  11968. {
  11969. if (mCurTypeInstance != NULL)
  11970. {
  11971. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11972. return false;
  11973. }
  11974. return !IsInSpecializedSection();
  11975. }
  11976. bool BfModule::IsInSpecializedGeneric()
  11977. {
  11978. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  11979. return true;
  11980. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  11981. return false;
  11982. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  11983. }
  11984. bool BfModule::IsInSpecializedSection()
  11985. {
  11986. return IsInSpecializedGeneric() ||
  11987. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  11988. }
  11989. bool BfModule::IsInUnspecializedGeneric()
  11990. {
  11991. if (mCurMethodInstance != NULL)
  11992. return mCurMethodInstance->mIsUnspecialized;
  11993. return false;
  11994. }
  11995. //////////////////////////////////////////////////////////////////////////
  11996. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  11997. {
  11998. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  11999. if (type->IsValuelessType())
  12000. return mBfIRBuilder->GetFakeVal();
  12001. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  12002. if ((!doLifetimeEnd) && (WantsLifetimes()))
  12003. {
  12004. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  12005. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  12006. }
  12007. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  12008. auto typeOptions = GetTypeOptions();
  12009. if (typeOptions != NULL)
  12010. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  12011. // Local variable inits are implicitly handled in the Beef Backend
  12012. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  12013. {
  12014. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12015. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  12016. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  12017. mBfIRBuilder->ClearDebugLocation(storeInst);
  12018. mBfIRBuilder->SetInsertPoint(prevBlock);
  12019. }
  12020. return allocaInst;
  12021. }
  12022. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  12023. {
  12024. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  12025. mCurMethodState->mLocals.push_back(localVar);
  12026. BfLocalVarEntry* localVarEntryPtr;
  12027. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  12028. {
  12029. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  12030. localVarEntryPtr->mLocalVar = localVar;
  12031. }
  12032. }
  12033. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  12034. {
  12035. if (localVarDef->mResolvedType->IsVar())
  12036. return;
  12037. if ((mBfIRBuilder->DbgHasInfo()) &&
  12038. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  12039. (mHasFullDebugInfo) &&
  12040. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  12041. {
  12042. auto varType = localVarDef->mResolvedType;
  12043. if (localVarDef->mResolvedType->IsValuelessType())
  12044. {
  12045. }
  12046. else
  12047. {
  12048. bool isByAddr = false;
  12049. auto diValue = localVarDef->mValue;
  12050. if (localVarDef->mConstValue)
  12051. diValue = localVarDef->mConstValue;
  12052. else if (localVarDef->mAddr)
  12053. {
  12054. diValue = localVarDef->mAddr;
  12055. isByAddr = true;
  12056. }
  12057. if (diValue.IsConst())
  12058. {
  12059. auto constant = mBfIRBuilder->GetConstant(diValue);
  12060. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  12061. {
  12062. // Ignore for now
  12063. return;
  12064. }
  12065. }
  12066. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  12067. bool didConstToMem = false;
  12068. bool isConstant = false;
  12069. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  12070. diType = mBfIRBuilder->DbgCreateConstType(diType);
  12071. else if (localVarDef->mConstValue)
  12072. {
  12073. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  12074. isConstant =
  12075. (constant->mConstType < BfConstType_GlobalVar) ||
  12076. (constant->mConstType == BfConstType_AggZero) ||
  12077. (constant->mConstType == BfConstType_Agg);
  12078. if (isConstant)
  12079. {
  12080. if (localVarDef->mResolvedType->IsComposite())
  12081. {
  12082. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  12083. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  12084. // if (IsTargetingBeefBackend())
  12085. // {
  12086. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  12087. // didConstToMem = true;
  12088. //
  12089. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  12090. // }
  12091. //else
  12092. {
  12093. isByAddr = true;
  12094. mBfIRBuilder->SaveDebugLocation();
  12095. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12096. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  12097. mBfIRBuilder->ClearDebugLocation();
  12098. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  12099. auto addrVal = CreateAlloca(ptrType);
  12100. mBfIRBuilder->CreateStore(constMem, addrVal);
  12101. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  12102. diValue = addrVal;
  12103. didConstToMem = true;
  12104. mBfIRBuilder->SetInsertPoint(prevBlock);
  12105. mBfIRBuilder->RestoreDebugLocation();
  12106. }
  12107. }
  12108. if (mCompiler->mOptions.IsCodeView())
  12109. diType = mBfIRBuilder->DbgCreateConstType(diType);
  12110. }
  12111. }
  12112. if (!mBfIRBuilder->mIgnoreWrites)
  12113. {
  12114. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12115. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  12116. localVarDef->mDbgVarInst = diVariable;
  12117. if (mBfIRBuilder->HasDebugLocation())
  12118. {
  12119. if ((isConstant) && (!didConstToMem))
  12120. {
  12121. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  12122. }
  12123. else
  12124. {
  12125. if ((IsTargetingBeefBackend()) && (doAliasValue))
  12126. {
  12127. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  12128. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  12129. }
  12130. if (isByAddr)
  12131. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  12132. else if (diValue)
  12133. {
  12134. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  12135. }
  12136. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  12137. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  12138. }
  12139. }
  12140. }
  12141. }
  12142. }
  12143. }
  12144. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  12145. {
  12146. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  12147. {
  12148. if ((!localVarDef->mValue.IsConst()) &&
  12149. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  12150. {
  12151. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  12152. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  12153. }
  12154. }
  12155. if (addDebugInfo)
  12156. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  12157. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  12158. DoAddLocalVariable(localVarDef);
  12159. auto rootMethodState = mCurMethodState->GetRootMethodState();
  12160. if (localVarDef->mLocalVarId == -1)
  12161. {
  12162. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  12163. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  12164. }
  12165. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule))
  12166. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  12167. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  12168. {
  12169. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  12170. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (!mIsComptimeModule))
  12171. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  12172. }
  12173. return localVarDef;
  12174. }
  12175. void BfModule::CreateDIRetVal()
  12176. {
  12177. if (!WantsDebugInfo())
  12178. return;
  12179. /*if (!mCurMethodState->mRetVal)
  12180. {
  12181. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  12182. return;
  12183. }*/
  12184. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  12185. {
  12186. BfType* dbgType = mCurMethodInstance->mReturnType;
  12187. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  12188. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  12189. {
  12190. BF_ASSERT(mCurMethodState->mRetValAddr);
  12191. dbgType = CreatePointerType(dbgType);
  12192. dbgValue = mCurMethodState->mRetValAddr;
  12193. }
  12194. else
  12195. {
  12196. BF_ASSERT(!mCurMethodState->mRetValAddr);
  12197. }
  12198. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12199. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  12200. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  12201. }
  12202. }
  12203. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  12204. {
  12205. BfTypeVector fieldTypes;
  12206. for (auto arg : values)
  12207. fieldTypes.Add(arg.mType);
  12208. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  12209. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  12210. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  12211. {
  12212. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  12213. if (fieldInstance.mDataIdx <= 0)
  12214. continue;
  12215. auto typedVal = values[fieldIdx];
  12216. typedVal = LoadOrAggregateValue(typedVal);
  12217. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  12218. }
  12219. return tupleTypedValue;
  12220. }
  12221. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  12222. {
  12223. if (variableDef->mName.IsEmpty())
  12224. return;
  12225. BfLocalVarEntry* localVarEntryPtr = NULL;
  12226. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  12227. {
  12228. auto checkLocal = localVarEntryPtr->mLocalVar;
  12229. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  12230. {
  12231. BfError* error;
  12232. if (checkLocal->mIsImplicitParam)
  12233. return; // Ignore 'redefinition'
  12234. if (checkLocal->IsParam())
  12235. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  12236. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  12237. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  12238. else
  12239. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  12240. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  12241. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  12242. return;
  12243. }
  12244. }
  12245. }
  12246. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  12247. {
  12248. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  12249. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  12250. {
  12251. if (tokenNode->GetToken() == BfToken_Colon)
  12252. {
  12253. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  12254. {
  12255. Fail("Cannot access method scope across deferred block boundary", scopeName);
  12256. return NULL;
  12257. }
  12258. return &mCurMethodState->mHeadScope;
  12259. }
  12260. else if (tokenNode->GetToken() == BfToken_Mixin)
  12261. {
  12262. if (fromMixinState == NULL)
  12263. {
  12264. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  12265. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  12266. return mCurMethodState->mCurScope;
  12267. }
  12268. fromMixinState->mUsedInvocationScope = true;
  12269. return fromMixinState->mTargetScope;
  12270. }
  12271. else if (tokenNode->GetToken() == BfToken_New)
  12272. return NULL;
  12273. }
  12274. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  12275. {
  12276. auto findLabel = scopeName->ToString();
  12277. bool crossedDeferredBlock = false;
  12278. auto checkScope = mCurMethodState->mCurScope;
  12279. while (checkScope != NULL)
  12280. {
  12281. if (checkScope->mIsDeferredBlock)
  12282. crossedDeferredBlock = true;
  12283. if (checkScope->mLabel == findLabel)
  12284. {
  12285. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  12286. {
  12287. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  12288. return NULL;
  12289. }
  12290. return checkScope;
  12291. }
  12292. checkScope = checkScope->mPrevScope;
  12293. }
  12294. if (!inMixinDecl)
  12295. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  12296. }
  12297. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  12298. {
  12299. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  12300. }
  12301. return mCurMethodState->mCurScope;
  12302. }
  12303. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  12304. {
  12305. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  12306. }
  12307. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  12308. {
  12309. auto scopeData = FindScope(scopeName, false);
  12310. if (scopeData == NULL)
  12311. return NULL;
  12312. int scopeDepth = scopeData->GetDepth();
  12313. // Find the first break data that is at or below the depth of our requested scope
  12314. auto breakData = mCurMethodState->mBreakData;
  12315. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  12316. {
  12317. if (breakData->mScope->mIsConditional)
  12318. return NULL;
  12319. breakData = breakData->mPrevBreakData;
  12320. }
  12321. return breakData;
  12322. }
  12323. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  12324. {
  12325. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  12326. if (!IsTargetingBeefBackend())
  12327. return;
  12328. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  12329. {
  12330. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12331. }
  12332. }
  12333. void BfModule::ClearLifetimeEnds()
  12334. {
  12335. auto scopeData = mCurMethodState->mCurScope;
  12336. while (scopeData != NULL)
  12337. {
  12338. scopeData->mDeferredLifetimeEnds.Clear();
  12339. scopeData = scopeData->mPrevScope;
  12340. }
  12341. }
  12342. bool BfModule::WantsDebugInfo()
  12343. {
  12344. if ((mCurMethodInstance != NULL) &&
  12345. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  12346. return false;
  12347. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  12348. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  12349. }
  12350. BfTypeOptions* BfModule::GetTypeOptions()
  12351. {
  12352. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  12353. return mCurMethodState->mMethodTypeOptions;
  12354. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  12355. }
  12356. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  12357. {
  12358. BfReflectKind reflectKind = BfReflectKind_None;
  12359. if (attrType->mCustomAttributes != NULL)
  12360. {
  12361. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  12362. {
  12363. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  12364. {
  12365. for (auto& prop : customAttr.mSetProperties)
  12366. {
  12367. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  12368. if (propDef->mName == "ReflectUser")
  12369. {
  12370. if (prop.mParam.mValue.IsConst())
  12371. {
  12372. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  12373. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  12374. }
  12375. }
  12376. }
  12377. // Check for Flags arg
  12378. if (customAttr.mCtorArgs.size() < 2)
  12379. continue;
  12380. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  12381. if (constant == NULL)
  12382. continue;
  12383. if (constant->mTypeCode == BfTypeCode_Boolean)
  12384. continue;
  12385. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  12386. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  12387. }
  12388. }
  12389. }
  12390. return reflectKind;
  12391. }
  12392. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  12393. {
  12394. auto checkTypeInstance = typeInstance;
  12395. while (checkTypeInstance != NULL)
  12396. {
  12397. if (checkTypeInstance->mCustomAttributes != NULL)
  12398. {
  12399. auto checkReflectKind = BfReflectKind_None;
  12400. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  12401. {
  12402. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  12403. {
  12404. if (customAttr.mCtorArgs.size() > 0)
  12405. {
  12406. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  12407. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  12408. }
  12409. else
  12410. {
  12411. checkReflectKind = BfReflectKind_All;
  12412. }
  12413. }
  12414. else
  12415. {
  12416. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  12417. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  12418. }
  12419. }
  12420. if ((checkTypeInstance == typeInstance) ||
  12421. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  12422. {
  12423. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  12424. }
  12425. }
  12426. for (auto ifaceEntry : typeInstance->mInterfaces)
  12427. {
  12428. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  12429. {
  12430. auto iface = ifaceEntry.mInterfaceType;
  12431. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  12432. if (customAttr != NULL)
  12433. {
  12434. for (auto& prop : customAttr->mSetProperties)
  12435. {
  12436. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  12437. if (propDef->mName == "ReflectImplementer")
  12438. {
  12439. if (prop.mParam.mValue.IsConst())
  12440. {
  12441. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  12442. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  12443. }
  12444. }
  12445. }
  12446. }
  12447. }
  12448. }
  12449. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  12450. }
  12451. return reflectKind;
  12452. }
  12453. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  12454. {
  12455. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12456. while (checkScope != NULL)
  12457. {
  12458. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  12459. return true;
  12460. if (checkScope == scope)
  12461. break;
  12462. checkScope = checkScope->mPrevScope;
  12463. }
  12464. return false;
  12465. }
  12466. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  12467. {
  12468. // Is there anything we need to do here?
  12469. if (mBfIRBuilder->mIgnoreWrites)
  12470. {
  12471. // Just visit deferred blocks
  12472. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12473. while (checkScope != NULL)
  12474. {
  12475. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12476. while (deferredCallEntry != NULL)
  12477. {
  12478. if (deferredCallEntry->mDeferredBlock != NULL)
  12479. {
  12480. if (checkScope == &mCurMethodState->mHeadScope)
  12481. CreateRetValLocal();
  12482. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  12483. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  12484. }
  12485. deferredCallEntry = deferredCallEntry->mNext;
  12486. }
  12487. if (checkScope == scopeData)
  12488. break;
  12489. checkScope = checkScope->mPrevScope;
  12490. }
  12491. return;
  12492. }
  12493. // Why did we want to do SetIllegalSrcPos here?
  12494. // Don't we always want to step onto these instances?
  12495. // Find a case where we don't and perhaps only do it there.
  12496. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  12497. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  12498. //SetIllegalSrcPos();
  12499. bool setSrcPos = false;
  12500. bool wantsNop = true;
  12501. BfAstNode* deferCloseNode = NULL;
  12502. if (mCurMethodState->mInPostReturn)
  12503. {
  12504. // These won't get used, they are post-return
  12505. return;
  12506. }
  12507. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  12508. BfScopeData* scopeJumpBlock = NULL;
  12509. bool hadExtraDeferredLifetimeEnds = false;
  12510. auto _FlushLifetimeEnds = [&]()
  12511. {
  12512. for (auto lifetimeEnd : deferredLifetimeEnds)
  12513. {
  12514. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12515. mBfIRBuilder->ClearDebugLocation_Last();
  12516. }
  12517. deferredLifetimeEnds.clear();
  12518. };
  12519. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12520. while (checkScope != NULL)
  12521. {
  12522. if (checkScope->mCloseNode != NULL)
  12523. deferCloseNode = checkScope->mCloseNode;
  12524. if (doneBlock)
  12525. {
  12526. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  12527. for (auto& checkHandler : checkScope->mDeferredHandlers)
  12528. {
  12529. if (checkHandler.mDoneBlock == doneBlock)
  12530. {
  12531. scopeJumpBlock = checkScope;
  12532. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  12533. mBfIRBuilder->ClearDebugLocation_Last();
  12534. _FlushLifetimeEnds();
  12535. break;
  12536. }
  12537. }
  12538. if (scopeJumpBlock != NULL)
  12539. break;
  12540. }
  12541. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  12542. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  12543. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  12544. if (hasWork)
  12545. {
  12546. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  12547. if (deferCloseNode != NULL)
  12548. {
  12549. UpdateSrcPos(deferCloseNode);
  12550. }
  12551. if (checkScope == &mCurMethodState->mHeadScope)
  12552. CreateRetValLocal();
  12553. if (doneBlock)
  12554. {
  12555. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  12556. String blockName = "deferredCalls";
  12557. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  12558. BfDeferredHandler deferredHandler;
  12559. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  12560. {
  12561. mBfIRBuilder->SaveDebugLocation();
  12562. mBfIRBuilder->ClearDebugLocation();
  12563. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  12564. mBfIRBuilder->RestoreDebugLocation();
  12565. }
  12566. else
  12567. {
  12568. // Definitely chain
  12569. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  12570. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  12571. mBfIRBuilder->ClearDebugLocation_Last();
  12572. _FlushLifetimeEnds();
  12573. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  12574. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  12575. }
  12576. deferredHandler.mDoneBlock = doneBlock;
  12577. if (!mBfIRBuilder->mIgnoreWrites)
  12578. checkScope->mDeferredHandlers.push_back(deferredHandler);
  12579. if (checkScope == &mCurMethodState->mHeadScope)
  12580. {
  12581. if (!mCurMethodState->mDIRetVal)
  12582. {
  12583. // 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
  12584. // be scoped to the physical method
  12585. /*if (deferCloseNode != NULL)
  12586. {
  12587. UpdateSrcPos(deferCloseNode);
  12588. }*/
  12589. CreateDIRetVal();
  12590. }
  12591. }
  12592. if (checkScope != mCurMethodState->mTailScope)
  12593. {
  12594. if (deferredHandler.mHandlerBlock.IsFake())
  12595. {
  12596. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12597. }
  12598. if (!mBfIRBuilder->mIgnoreWrites)
  12599. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  12600. }
  12601. }
  12602. std::unordered_set<BfDeferredCallEntry*> handledSet;
  12603. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12604. while (deferredCallEntry != NULL)
  12605. {
  12606. BfDeferredCallEmitState deferredCallEmitState;
  12607. deferredCallEmitState.mCloseNode = deferCloseNode;
  12608. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  12609. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  12610. if (deferCloseNode != NULL)
  12611. {
  12612. UpdateSrcPos(deferCloseNode);
  12613. }
  12614. if (wantsNop)
  12615. EmitEnsureInstructionAt();
  12616. wantsNop = false;
  12617. if (deferredCallEntry->mDeferredBlock != NULL)
  12618. {
  12619. auto itr = handledSet.insert(deferredCallEntry);
  12620. if (!itr.second)
  12621. {
  12622. // Already handled, can happen if we defer again within the block
  12623. deferredCallEntry = deferredCallEntry->mNext;
  12624. continue;
  12625. }
  12626. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  12627. EmitDeferredCall(*deferredCallEntry, true);
  12628. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  12629. {
  12630. // The list changed, start over and ignore anything we've already handled
  12631. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12632. }
  12633. else
  12634. deferredCallEntry = deferredCallEntry->mNext;
  12635. }
  12636. else
  12637. {
  12638. EmitDeferredCall(*deferredCallEntry, true);
  12639. deferredCallEntry = deferredCallEntry->mNext;
  12640. }
  12641. }
  12642. if (checkScope->mSavedStack)
  12643. {
  12644. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  12645. if (mCurMethodState->mDynStackRevIdx)
  12646. {
  12647. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  12648. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  12649. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  12650. }
  12651. }
  12652. }
  12653. if (!checkScope->mIsScopeHead)
  12654. {
  12655. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  12656. if (!IsTargetingBeefBackend())
  12657. {
  12658. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12659. {
  12660. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12661. }
  12662. }
  12663. else
  12664. {
  12665. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12666. {
  12667. deferredLifetimeEnds.Add(lifetimeEnd);
  12668. }
  12669. }
  12670. }
  12671. if (checkScope == scopeData)
  12672. break;
  12673. checkScope = checkScope->mPrevScope;
  12674. }
  12675. if ((doneBlock) && (scopeJumpBlock == NULL))
  12676. {
  12677. mBfIRBuilder->CreateBr(doneBlock);
  12678. mBfIRBuilder->ClearDebugLocation_Last();
  12679. }
  12680. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  12681. // may have been created when other scope lifetimes were available
  12682. _FlushLifetimeEnds();
  12683. // Emit lifetimeEnds after the branch for Beef
  12684. /*if (IsTargetingBeefBackend())
  12685. {
  12686. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  12687. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12688. while (checkScope != NULL)
  12689. {
  12690. if (checkScope == scopeJumpBlock)
  12691. break;
  12692. if (!checkScope->mIsScopeHead)
  12693. {
  12694. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12695. {
  12696. if (needsEnsureInst)
  12697. {
  12698. needsEnsureInst = false;
  12699. }
  12700. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12701. }
  12702. }
  12703. if (checkScope == scopeData)
  12704. break;
  12705. checkScope = checkScope->mPrevScope;
  12706. }
  12707. }*/
  12708. }
  12709. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  12710. {
  12711. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12712. {
  12713. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  12714. while (deferredLocalAssignData != NULL)
  12715. {
  12716. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  12717. break;
  12718. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  12719. deferredLocalAssignData->mIsUnconditional = false;
  12720. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  12721. }
  12722. }
  12723. // When we leave a scope, mark those as assigned for deferred assignment purposes
  12724. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  12725. {
  12726. auto localDef = mCurMethodState->mLocals[localIdx];
  12727. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  12728. {
  12729. bool hadAssignment = false;
  12730. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12731. {
  12732. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  12733. if (entry.mLocalVar == localDef)
  12734. hadAssignment = true;
  12735. }
  12736. if (!hadAssignment)
  12737. {
  12738. localDef->mHadExitBeforeAssign = true;
  12739. mCurMethodState->LocalDefined(localDef);
  12740. }
  12741. }
  12742. }
  12743. }
  12744. void BfModule::CreateReturn(BfIRValue val)
  12745. {
  12746. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  12747. {
  12748. // Store to sret
  12749. BF_ASSERT(val);
  12750. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12751. mBfIRBuilder->CreateRetVoid();
  12752. return;
  12753. }
  12754. if (mCurMethodInstance->mReturnType->IsVar())
  12755. return;
  12756. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12757. {
  12758. mBfIRBuilder->CreateRetVoid();
  12759. return;
  12760. }
  12761. if (mCurMethodInstance->mReturnType->IsStruct())
  12762. {
  12763. BfTypeCode loweredReturnType = BfTypeCode_None;
  12764. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  12765. if (!mIsComptimeModule)
  12766. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  12767. if (loweredReturnType != BfTypeCode_None)
  12768. {
  12769. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  12770. mBfIRBuilder->CreateStore(val, retVal);
  12771. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  12772. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  12773. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  12774. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  12775. mBfIRBuilder->CreateRet(loadedReturnValue);
  12776. return;
  12777. }
  12778. }
  12779. BF_ASSERT(val);
  12780. mBfIRBuilder->CreateRet(val);
  12781. }
  12782. void BfModule::EmitReturn(const BfTypedValue& val)
  12783. {
  12784. if (mCurMethodState->mIRExitBlock)
  12785. {
  12786. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  12787. {
  12788. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  12789. {
  12790. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  12791. {
  12792. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  12793. if (!mCurMethodState->mRetVal)
  12794. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  12795. mBfIRBuilder->CreateStore(val.mValue, retVal);
  12796. }
  12797. else if (mIsComptimeModule)
  12798. {
  12799. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  12800. }
  12801. else
  12802. {
  12803. // Just ignore
  12804. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  12805. }
  12806. }
  12807. }
  12808. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12809. }
  12810. else
  12811. {
  12812. EmitDeferredScopeCalls(false, NULL);
  12813. if (val)
  12814. {
  12815. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12816. mBfIRBuilder->CreateRetVoid();
  12817. else
  12818. mBfIRBuilder->CreateRet(val.mValue);
  12819. }
  12820. }
  12821. mCurMethodState->SetHadReturn(true);
  12822. mCurMethodState->mLeftBlockUncond = true;
  12823. }
  12824. void BfModule::EmitDefaultReturn()
  12825. {
  12826. if (mCurMethodState->mInDeferredBlock)
  12827. return;
  12828. if (mCurMethodState->mIRExitBlock)
  12829. {
  12830. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12831. }
  12832. else
  12833. {
  12834. if (mCurMethodInstance->mReturnType->IsVar())
  12835. {
  12836. // Ignore
  12837. }
  12838. else if (mCurMethodInstance->mReturnType->IsVoid())
  12839. mBfIRBuilder->CreateRetVoid();
  12840. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  12841. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  12842. }
  12843. mCurMethodState->SetHadReturn(true);
  12844. mCurMethodState->mLeftBlockUncond = true;
  12845. }
  12846. void BfModule::AssertErrorState()
  12847. {
  12848. if (mIgnoreErrors)
  12849. return;
  12850. if (mHadBuildError)
  12851. return;
  12852. if (mCurTypeInstance != NULL)
  12853. {
  12854. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  12855. return;
  12856. }
  12857. if (mCurMethodInstance != NULL)
  12858. {
  12859. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  12860. return;
  12861. if (mCurMethodInstance->mHasFailed)
  12862. return;
  12863. }
  12864. // We want the module to be marked as failed even if it's just an error in the parser
  12865. if (mCurMethodInstance != NULL)
  12866. mCurMethodInstance->mHasFailed = true;
  12867. mHadBuildError = true;
  12868. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  12869. if (mCurTypeInstance != NULL)
  12870. {
  12871. if (mCurTypeInstance->mTypeFailed)
  12872. return;
  12873. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  12874. return;
  12875. }
  12876. if (mCurMethodInstance != NULL)
  12877. {
  12878. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12879. return;
  12880. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12881. return;
  12882. }
  12883. if (mCompiler->IsAutocomplete())
  12884. return;
  12885. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  12886. }
  12887. void BfModule::AssertParseErrorState()
  12888. {
  12889. if (mCompiler->mRevision == 1)
  12890. AssertErrorState();
  12891. }
  12892. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  12893. {
  12894. BF_ASSERT(delegateType->IsDelegate());
  12895. auto typeInst = delegateType->ToTypeInstance();
  12896. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12897. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  12898. return invokeMethodInstance->mReturnType;
  12899. }
  12900. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  12901. {
  12902. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  12903. }
  12904. void BfModule::CreateDelegateInvokeMethod()
  12905. {
  12906. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  12907. //mBfIRBuilder->ClearDebugLocation();
  12908. SetIllegalSrcPos();
  12909. auto typeInstance = mCurTypeInstance;
  12910. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  12911. SizedArray<BfIRType, 4> staticParamTypes;
  12912. SizedArray<BfIRValue, 4> staticFuncArgs;
  12913. SizedArray<BfIRValue, 4> memberFuncArgs;
  12914. auto multicastDelegateType = typeInstance->mBaseType;
  12915. if (multicastDelegateType->mFieldInstances.size() != 2)
  12916. {
  12917. AssertErrorState();
  12918. return;
  12919. }
  12920. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  12921. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  12922. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  12923. BfExprEvaluator exprEvaluator(this);
  12924. SizedArray<BfIRType, 8> origParamTypes;
  12925. BfIRType origReturnType;
  12926. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  12927. if (mCurMethodInstance->mReturnType->IsValueType())
  12928. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  12929. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  12930. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12931. int thisIdx = 0;
  12932. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  12933. {
  12934. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  12935. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12936. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12937. }
  12938. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  12939. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12940. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  12941. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  12942. {
  12943. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  12944. exprEvaluator.PushArg(localVal, staticFuncArgs);
  12945. exprEvaluator.PushArg(localVal, memberFuncArgs);
  12946. }
  12947. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  12948. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  12949. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  12950. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  12951. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  12952. auto doneBB = mBfIRBuilder->CreateBlock("done");
  12953. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  12954. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  12955. BfIRValue nonStaticResult;
  12956. BfIRValue staticResult;
  12957. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  12958. /// Non-static invocation
  12959. {
  12960. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12961. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  12962. mBfIRBuilder->SetInsertPoint(trueBB);
  12963. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  12964. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12965. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  12966. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12967. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  12968. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  12969. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  12970. if (callingConv != BfIRCallingConv_CDecl)
  12971. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  12972. mCurMethodState->SetHadReturn(false);
  12973. mCurMethodState->mLeftBlockUncond = false;
  12974. mCurMethodState->mLeftBlockCond = false;
  12975. mBfIRBuilder->CreateBr(doneBB);
  12976. }
  12977. // Static invocation
  12978. {
  12979. mBfIRBuilder->AddBlock(falseBB);
  12980. mBfIRBuilder->SetInsertPoint(falseBB);
  12981. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12982. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  12983. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12984. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  12985. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  12986. {
  12987. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  12988. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  12989. }
  12990. if (callingConv == BfIRCallingConv_ThisCall)
  12991. callingConv = BfIRCallingConv_CDecl;
  12992. if (callingConv != BfIRCallingConv_CDecl)
  12993. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  12994. mCurMethodState->SetHadReturn(false);
  12995. mCurMethodState->mLeftBlockUncond = false;
  12996. mCurMethodState->mLeftBlockCond = false;
  12997. mBfIRBuilder->CreateBr(doneBB);
  12998. }
  12999. mBfIRBuilder->AddBlock(doneBB);
  13000. mBfIRBuilder->SetInsertPoint(doneBB);
  13001. if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  13002. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  13003. {
  13004. mBfIRBuilder->CreateRetVoid();
  13005. }
  13006. else
  13007. {
  13008. BfIRType loweredIRReturnType;
  13009. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13010. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13011. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  13012. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  13013. else
  13014. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  13015. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  13016. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  13017. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  13018. mBfIRBuilder->CreateRet(phi);
  13019. }
  13020. }
  13021. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  13022. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  13023. {
  13024. auto typeDef = typeInstance->mTypeDef;
  13025. auto methodDeclaration = methodDef->mMethodDeclaration;
  13026. if (!mCompiler->mIsResolveOnly)
  13027. return true;
  13028. if (typeInstance->IsGenericTypeInstance())
  13029. {
  13030. // We only really want to process the unspecialized type for autocompletion
  13031. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  13032. return false;
  13033. }
  13034. BfAstNode* checkNode = methodDeclaration;
  13035. if (methodDeclaration == NULL)
  13036. checkNode = methodDef->mBody;
  13037. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  13038. {
  13039. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  13040. return true;
  13041. }
  13042. return false;
  13043. }
  13044. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  13045. {
  13046. methodInst->mAppendAllocAlign = 1;
  13047. }
  13048. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  13049. {
  13050. BP_ZONE("BfModule::TryConstCalcAppend");
  13051. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  13052. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  13053. return BfTypedValue();
  13054. // We want to regenerate all ctor calls when the method internals change
  13055. {
  13056. auto checkTypeInst = methodInst->GetOwner();
  13057. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  13058. {
  13059. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  13060. checkTypeInst = GetBaseType(checkTypeInst);
  13061. }
  13062. }
  13063. if (!methodInst->mMayBeConst)
  13064. return BfTypedValue();
  13065. // Do we need to iterate in order to resolve mAppendAllocAlign?
  13066. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  13067. bool wasAllConst = true;
  13068. int argIdx = 0;
  13069. int paramIdx = 0;
  13070. while (true)
  13071. {
  13072. if (argIdx >= (int)args.size())
  13073. break;
  13074. auto paramType = methodInst->GetParamType(paramIdx);
  13075. PopulateType(paramType);
  13076. int argCount = 0;
  13077. if (!paramType->IsValuelessType())
  13078. {
  13079. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  13080. argCount = paramType->GetSplatCount();
  13081. else
  13082. argCount = 1;
  13083. for (int argOfs = 0; argOfs < argCount; argOfs++)
  13084. {
  13085. auto arg = args[argIdx + argOfs];
  13086. if (!arg.IsConst())
  13087. {
  13088. wasAllConst = false;
  13089. if (!isFirstRun)
  13090. {
  13091. auto& param = methodInst->mParams[argIdx];
  13092. if (param.mReferencedInConstPass)
  13093. {
  13094. // If this param is required as part of the const calculation then
  13095. // we require that it be const...
  13096. return BfTypedValue();
  13097. }
  13098. }
  13099. }
  13100. }
  13101. }
  13102. paramIdx++;
  13103. argIdx += argCount;
  13104. }
  13105. auto methodDef = methodInst->mMethodDef;
  13106. auto methodDecl = methodDef->GetMethodDeclaration();
  13107. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  13108. if (methodDeclBlock == NULL)
  13109. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  13110. BfTypedValue constValue;
  13111. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13112. auto checkState = mCurMethodState->mConstResolveState;
  13113. while (checkState != NULL)
  13114. {
  13115. if (checkState->mMethodInstance == methodInst)
  13116. {
  13117. return BfTypedValue();
  13118. }
  13119. checkState = checkState->mPrevConstResolveState;
  13120. }
  13121. //auto accumValue = GetConstValue(0);
  13122. bool failed = false;
  13123. //
  13124. {
  13125. BfConstResolveState constResolveState;
  13126. constResolveState.mMethodInstance = methodInst;
  13127. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  13128. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  13129. BfMethodState methodState;
  13130. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  13131. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  13132. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13133. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  13134. methodState.mConstResolveState = &constResolveState;
  13135. int argIdx = 0;
  13136. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  13137. {
  13138. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  13139. continue;
  13140. auto paramType = methodInst->GetParamType(paramIdx);
  13141. // Fix this after we allow structs to be consts
  13142. //BF_ASSERT(!paramType->IsSplattable());
  13143. BfLocalVariable* localVar = new BfLocalVariable();
  13144. localVar->mName = methodInst->GetParamName(paramIdx);
  13145. localVar->mResolvedType = paramType;
  13146. localVar->mConstValue = args[argIdx];
  13147. localVar->mParamIdx = paramIdx;
  13148. AddLocalVariableDef(localVar);
  13149. argIdx++;
  13150. }
  13151. AppendAllocVisitor appendAllocVisitor;
  13152. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  13153. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  13154. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  13155. if (baseCtorAppendValue)
  13156. {
  13157. if (baseCtorAppendValue.mValue.IsFake())
  13158. appendAllocVisitor.mFailed = true;
  13159. else
  13160. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  13161. }
  13162. appendAllocVisitor.mModule = this;
  13163. appendAllocVisitor.VisitChild(methodDecl->mBody);
  13164. if (!appendAllocVisitor.mFailed)
  13165. constValue = appendAllocVisitor.mConstAccum;
  13166. if (isFirstRun)
  13167. {
  13168. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  13169. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  13170. mCurMethodInstance->mAppendAllocAlign = 1;
  13171. }
  13172. if (isFirstRun)
  13173. {
  13174. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  13175. {
  13176. auto localVar = mCurMethodState->mLocals[paramIdx];
  13177. if (localVar->mReadFromId != -1)
  13178. {
  13179. auto& param = methodInst->mParams[paramIdx];
  13180. param.mReferencedInConstPass = true;
  13181. }
  13182. }
  13183. }
  13184. }
  13185. mBfIRBuilder->SetInsertPoint(prevBlock);
  13186. if (!constValue)
  13187. {
  13188. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  13189. // all-const args
  13190. if (wasAllConst)
  13191. {
  13192. methodInst->mMayBeConst = false;
  13193. }
  13194. }
  13195. return constValue;
  13196. }
  13197. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  13198. {
  13199. // Any errors should only be shown in the actual CTOR call
  13200. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  13201. auto methodDef = mCurMethodInstance->mMethodDef;
  13202. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  13203. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  13204. BfCustomAttributes* customAttributes = NULL;
  13205. defer(delete customAttributes);
  13206. BfInvocationExpression* ctorInvocation = NULL;
  13207. if (ctorDeclaration != NULL)
  13208. {
  13209. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  13210. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  13211. {
  13212. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  13213. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  13214. }
  13215. }
  13216. BfTypeInstance* targetType = NULL;
  13217. if (ctorInvocation != NULL)
  13218. {
  13219. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  13220. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13221. }
  13222. else
  13223. targetType = mCurTypeInstance->mBaseType;
  13224. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  13225. return NULL;
  13226. auto targetRefNode = methodDef->GetRefNode();
  13227. BfType* targetThisType = targetType;
  13228. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  13229. BfExprEvaluator exprEvaluator(this);
  13230. BfResolvedArgs argValues;
  13231. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13232. {
  13233. argValues.Init(&ctorInvocation->mArguments);
  13234. }
  13235. //
  13236. {
  13237. }
  13238. BfFunctionBindResult bindResult;
  13239. bindResult.mSkipThis = true;
  13240. bindResult.mWantsArgs = true;
  13241. {
  13242. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  13243. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  13244. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  13245. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  13246. }
  13247. if (bindResult.mMethodInstance == NULL)
  13248. {
  13249. AssertErrorState();
  13250. return BfTypedValue();
  13251. }
  13252. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  13253. {
  13254. return BfTypedValue();
  13255. }
  13256. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  13257. bindResult.mIRArgs.RemoveAt(0);
  13258. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  13259. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  13260. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  13261. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  13262. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  13263. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  13264. if (appendSizeTypedValue)
  13265. return appendSizeTypedValue;
  13266. if (constOnly)
  13267. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  13268. bool needsRecalc = false;
  13269. for (auto irArg : bindResult.mIRArgs)
  13270. {
  13271. if (irArg.IsFake())
  13272. needsRecalc = true;
  13273. }
  13274. auto calcAppendArgs = bindResult.mIRArgs;
  13275. if (needsRecalc)
  13276. {
  13277. // Do it again, but without mIgnoreWrites set
  13278. BfResolvedArgs argValues;
  13279. argValues.Init(&ctorInvocation->mArguments);
  13280. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  13281. BfFunctionBindResult bindResult;
  13282. bindResult.mSkipThis = true;
  13283. bindResult.mWantsArgs = true;
  13284. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  13285. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  13286. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  13287. bindResult.mIRArgs.RemoveAt(0);
  13288. calcAppendArgs = bindResult.mIRArgs;
  13289. }
  13290. BF_ASSERT(calcAppendMethodModule.mFunc);
  13291. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  13292. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  13293. return appendSizeTypedValue;
  13294. }
  13295. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  13296. void BfModule::EmitCtorCalcAppend()
  13297. {
  13298. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  13299. return;
  13300. auto methodDef = mCurMethodInstance->mMethodDef;
  13301. auto methodDecl = methodDef->GetMethodDeclaration();
  13302. Array<BfAstNode*> deferredNodeList;
  13303. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  13304. if (methodDeclBlock == NULL)
  13305. return;
  13306. AppendAllocVisitor appendAllocVisitor;
  13307. auto baseCalcAppend = CallBaseCtorCalc(false);
  13308. if (baseCalcAppend)
  13309. {
  13310. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  13311. }
  13312. appendAllocVisitor.mModule = this;
  13313. appendAllocVisitor.VisitChild(methodDecl->mBody);
  13314. }
  13315. void BfModule::CreateStaticCtor()
  13316. {
  13317. auto typeDef = mCurTypeInstance->mTypeDef;
  13318. auto methodDef = mCurMethodInstance->mMethodDef;
  13319. BfIRBlock exitBB;
  13320. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  13321. {
  13322. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  13323. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  13324. mBfIRBuilder->MapType(boolType),
  13325. false,
  13326. BfIRLinkageType_Internal,
  13327. GetDefaultValue(boolType),
  13328. "didStaticInit");
  13329. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  13330. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  13331. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  13332. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  13333. mBfIRBuilder->SetInsertPoint(initBB);
  13334. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  13335. }
  13336. // Do DLL imports
  13337. if (!mDllImportEntries.empty())
  13338. {
  13339. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  13340. PopulateType(internalType);
  13341. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  13342. if (!getSharedProcAddressInstance)
  13343. {
  13344. if (!mCompiler->mPassInstance->HasFailed())
  13345. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  13346. }
  13347. }
  13348. // Fill in initializer values
  13349. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  13350. {
  13351. for (auto fieldDef : typeDef->mFields)
  13352. {
  13353. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  13354. {
  13355. // For extensions, only handle these fields in the appropriate extension
  13356. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13357. continue;
  13358. UpdateSrcPos(fieldDef->mInitializer);
  13359. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13360. if (!fieldInst->mFieldIncluded)
  13361. continue;
  13362. if (fieldInst->mResolvedType->IsVar())
  13363. {
  13364. continue;
  13365. }
  13366. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  13367. }
  13368. }
  13369. auto _CheckInitBlock = [&](BfAstNode* node)
  13370. {
  13371. };
  13372. EmitInitBlocks(_CheckInitBlock);
  13373. }
  13374. else
  13375. {
  13376. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13377. {
  13378. if (tempTypeDef->mFullName == typeDef->mFullName)
  13379. {
  13380. for (auto fieldDef : tempTypeDef->mFields)
  13381. {
  13382. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13383. {
  13384. if (fieldDef->mInitializer != NULL)
  13385. {
  13386. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  13387. {
  13388. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  13389. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  13390. }
  13391. BfType* wantType = NULL;
  13392. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  13393. {
  13394. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  13395. }
  13396. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  13397. }
  13398. }
  13399. }
  13400. }
  13401. }
  13402. }
  13403. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13404. CallChainedMethods(mCurMethodInstance, false);
  13405. }
  13406. void BfModule::EmitDtorBody()
  13407. {
  13408. if (mCurTypeInstance->IsClosure())
  13409. {
  13410. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  13411. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  13412. auto thisVal = GetThis();
  13413. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  13414. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  13415. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  13416. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  13417. SizedArray<BfIRValue, 1> args;
  13418. args.push_back(thisVal.mValue);
  13419. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  13420. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  13421. // Fall through to Object::~this call
  13422. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  13423. if (mIsComptimeModule)
  13424. mCompiler->mCEMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  13425. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  13426. SizedArray<BfIRValue, 1> vals = { basePtr };
  13427. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  13428. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  13429. mBfIRBuilder->SetTailCall(result);
  13430. return;
  13431. }
  13432. auto typeDef = mCurTypeInstance->mTypeDef;
  13433. auto methodDef = mCurMethodInstance->mMethodDef;
  13434. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13435. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13436. CallChainedMethods(mCurMethodInstance, true);
  13437. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  13438. {
  13439. VisitEmbeddedStatement(bodyBlock);
  13440. if (bodyBlock->mCloseBrace != NULL)
  13441. {
  13442. UpdateSrcPos(bodyBlock->mCloseBrace);
  13443. }
  13444. }
  13445. else
  13446. {
  13447. if (methodDeclaration != NULL)
  13448. UpdateSrcPos(methodDeclaration);
  13449. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  13450. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  13451. else if (typeDef->mTypeDeclaration != NULL)
  13452. UpdateSrcPos(typeDef->mTypeDeclaration);
  13453. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  13454. {
  13455. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  13456. }
  13457. }
  13458. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  13459. {
  13460. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  13461. {
  13462. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  13463. auto fieldDef = fieldInst->GetFieldDef();
  13464. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  13465. {
  13466. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  13467. {
  13468. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  13469. continue;
  13470. }
  13471. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  13472. {
  13473. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  13474. }
  13475. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13476. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  13477. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  13478. continue;
  13479. UpdateSrcPos(fieldDtor);
  13480. BfScopeData scopeData;
  13481. mCurMethodState->AddScope(&scopeData);
  13482. NewScopeState();
  13483. UpdateSrcPos(fieldDtor);
  13484. bool hasDbgInfo = (!fieldDef->mIsConst);
  13485. if (hasDbgInfo)
  13486. {
  13487. mBfIRBuilder->SaveDebugLocation();
  13488. mBfIRBuilder->ClearDebugLocation();
  13489. }
  13490. BfIRValue value;
  13491. if (fieldDef->mIsStatic)
  13492. {
  13493. value = ReferenceStaticField(fieldInst).mValue;
  13494. }
  13495. else
  13496. {
  13497. if (!mCurTypeInstance->IsValueType())
  13498. {
  13499. auto thisValue = GetThis();
  13500. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  13501. }
  13502. else
  13503. {
  13504. AssertErrorState();
  13505. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  13506. }
  13507. }
  13508. BfIRValue staticVal;
  13509. if (hasDbgInfo)
  13510. {
  13511. BfIRValue dbgShowValue = value;
  13512. BfLocalVariable* localDef = new BfLocalVariable();
  13513. localDef->mName = "_";
  13514. localDef->mResolvedType = fieldInst->mResolvedType;
  13515. localDef->mAddr = value;
  13516. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  13517. {
  13518. // Create another pointer indirection, a ref to the gep
  13519. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  13520. auto allocaInst = CreateAlloca(refFieldType);
  13521. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  13522. localDef->mResolvedType = refFieldType;
  13523. localDef->mAddr = allocaInst;
  13524. }
  13525. mBfIRBuilder->RestoreDebugLocation();
  13526. auto defLocalVar = AddLocalVariableDef(localDef, true);
  13527. // Put back so we actually modify the correct value*/
  13528. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  13529. defLocalVar->mAddr = value;
  13530. }
  13531. while (fieldDtor != NULL)
  13532. {
  13533. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13534. {
  13535. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  13536. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  13537. }
  13538. UpdateSrcPos(fieldDtor);
  13539. VisitEmbeddedStatement(fieldDtor->mBody);
  13540. fieldDtor = fieldDtor->mNextFieldDtor;
  13541. }
  13542. RestoreScopeState();
  13543. }
  13544. }
  13545. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  13546. {
  13547. auto checkBaseType = mCurTypeInstance->mBaseType;
  13548. while (checkBaseType != NULL)
  13549. {
  13550. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  13551. {
  13552. if (bodyBlock->mCloseBrace != NULL)
  13553. UpdateSrcPos(bodyBlock->mCloseBrace);
  13554. }
  13555. else
  13556. {
  13557. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  13558. }
  13559. checkBaseType->mTypeDef->PopulateMemberSets();
  13560. BfMemberSetEntry* entry = NULL;
  13561. BfMethodDef* dtorMethodDef = NULL;
  13562. checkBaseType->mTypeDef->mMethodSet.TryGetWith(String("~this"), &entry);
  13563. if (entry != NULL)
  13564. dtorMethodDef = (BfMethodDef*)entry->mMemberDef;
  13565. if (dtorMethodDef != NULL)
  13566. {
  13567. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  13568. if (IsSkippingExtraResolveChecks())
  13569. {
  13570. // Nothing
  13571. }
  13572. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  13573. {
  13574. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  13575. {
  13576. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  13577. SizedArray<BfIRValue, 1> vals = { basePtr };
  13578. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  13579. if (mIsComptimeModule)
  13580. mCompiler->mCEMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  13581. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  13582. }
  13583. }
  13584. else
  13585. {
  13586. // Invalid base dtor declaration
  13587. AssertErrorState();
  13588. }
  13589. break;
  13590. }
  13591. checkBaseType = checkBaseType->mBaseType;
  13592. }
  13593. }
  13594. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  13595. }
  13596. else
  13597. {
  13598. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  13599. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  13600. // resolve pass, NOT the autocomplete expression
  13601. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13602. {
  13603. if (tempTypeDef->mFullName == typeDef->mFullName)
  13604. {
  13605. for (auto fieldDef : tempTypeDef->mFields)
  13606. {
  13607. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  13608. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13609. {
  13610. BfType* fieldType = NULL;
  13611. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  13612. {
  13613. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  13614. auto curFieldDef = curFieldInstance->GetFieldDef();
  13615. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  13616. fieldType = curFieldInstance->GetResolvedType();
  13617. }
  13618. if (fieldType == NULL)
  13619. fieldType = GetPrimitiveType(BfTypeCode_Var);
  13620. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  13621. BfScopeData scopeData;
  13622. mCurMethodState->AddScope(&scopeData);
  13623. NewScopeState();
  13624. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  13625. if (fieldType != NULL)
  13626. {
  13627. BfLocalVariable* localDef = new BfLocalVariable();
  13628. localDef->mName = "_";
  13629. localDef->mResolvedType = fieldType;
  13630. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  13631. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13632. AddLocalVariableDef(localDef);
  13633. }
  13634. while (fieldDtor != NULL)
  13635. {
  13636. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  13637. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  13638. UpdateSrcPos(fieldDtor);
  13639. VisitEmbeddedStatement(fieldDtor->mBody);
  13640. fieldDtor = fieldDtor->mNextFieldDtor;
  13641. }
  13642. RestoreScopeState();
  13643. }
  13644. }
  13645. }
  13646. }
  13647. }
  13648. }
  13649. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  13650. {
  13651. auto typeInstance = methodInstance->GetOwner();
  13652. bool foundDllImportAttr = false;
  13653. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  13654. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  13655. {
  13656. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  13657. {
  13658. foundDllImportAttr = true;
  13659. }
  13660. }
  13661. if (!foundDllImportAttr)
  13662. {
  13663. AssertErrorState();
  13664. return BfIRValue();
  13665. }
  13666. String name = "bf_hs_preserve@";
  13667. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  13668. name += "__imp";
  13669. BfIRType returnType;
  13670. SizedArray<BfIRType, 8> paramTypes;
  13671. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  13672. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  13673. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  13674. BfIRValue initVal;
  13675. if (define)
  13676. {
  13677. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13678. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  13679. }
  13680. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  13681. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  13682. {
  13683. auto voidType = GetPrimitiveType(BfTypeCode_None);
  13684. auto ptrType = CreatePointerType(voidType);
  13685. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  13686. }
  13687. return globalVar;
  13688. }
  13689. void BfModule::CreateDllImportMethod()
  13690. {
  13691. if (mBfIRBuilder->mIgnoreWrites)
  13692. return;
  13693. auto globalVar = mFuncReferences[mCurMethodInstance];
  13694. if (!globalVar)
  13695. return;
  13696. bool allowTailCall = true;
  13697. mBfIRBuilder->ClearDebugLocation();
  13698. bool isHotCompile = mCompiler->IsHotCompile();
  13699. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  13700. if (isHotCompile)
  13701. {
  13702. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  13703. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  13704. }
  13705. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  13706. BfIRType returnType;
  13707. SizedArray<BfIRType, 8> paramTypes;
  13708. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13709. SizedArray<BfIRValue, 8> args;
  13710. for (int i = 0; i < (int)paramTypes.size(); i++)
  13711. args.push_back(mBfIRBuilder->GetArgument(i));
  13712. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13713. if (isHotCompile)
  13714. {
  13715. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  13716. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  13717. if (callingConvention == BfIRCallingConv_StdCall)
  13718. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  13719. else if (callingConvention == BfIRCallingConv_FastCall)
  13720. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  13721. else
  13722. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  13723. if (allowTailCall)
  13724. mBfIRBuilder->SetTailCall(result);
  13725. CreateReturn(result);
  13726. mCurMethodState->mHadReturn = true;
  13727. }
  13728. if (HasCompiledOutput())
  13729. {
  13730. BfDllImportEntry dllImportEntry;
  13731. dllImportEntry.mFuncVar = globalVar;
  13732. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13733. mDllImportEntries.push_back(dllImportEntry);
  13734. }
  13735. }
  13736. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  13737. {
  13738. auto methodDef = methodInstance->mMethodDef;
  13739. BfTypeInstance* owner = NULL;
  13740. if (!methodDef->mIsStatic)
  13741. owner = methodInstance->GetThisType()->ToTypeInstance();
  13742. if (owner == NULL)
  13743. owner = methodInstance->GetOwner();
  13744. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  13745. return BfIRCallingConv_CDecl;
  13746. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  13747. return BfIRCallingConv_StdCall;
  13748. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  13749. return BfIRCallingConv_FastCall;
  13750. if (!methodDef->mIsStatic)
  13751. {
  13752. if (owner->mIsCRepr)
  13753. return BfIRCallingConv_ThisCall;
  13754. if ((!owner->IsValuelessType()) &&
  13755. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  13756. return BfIRCallingConv_ThisCall;
  13757. }
  13758. return BfIRCallingConv_CDecl;
  13759. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  13760. }
  13761. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  13762. {
  13763. BfMethodDef* methodDef = NULL;
  13764. if (methodInstance != NULL)
  13765. methodDef = methodInstance->mMethodDef;
  13766. if (!func)
  13767. return;
  13768. if (mCompiler->mOptions.mNoFramePointerElim)
  13769. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  13770. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  13771. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  13772. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  13773. if (methodInstance == NULL)
  13774. return;
  13775. if (methodInstance->mReturnType->IsVar())
  13776. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  13777. if (methodDef->mImportKind == BfImportKind_Export)
  13778. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  13779. if (methodDef->mIsNoReturn)
  13780. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  13781. auto callingConv = GetIRCallingConvention(methodInstance);
  13782. if (callingConv != BfIRCallingConv_CDecl)
  13783. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  13784. if (isInlined)
  13785. {
  13786. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  13787. }
  13788. int argIdx = 0;
  13789. int paramIdx = 0;
  13790. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  13791. paramIdx = -1;
  13792. int argCount = methodInstance->GetIRFunctionParamCount(this);
  13793. while (argIdx < argCount)
  13794. {
  13795. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  13796. {
  13797. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  13798. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  13799. argIdx++;
  13800. continue;
  13801. }
  13802. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  13803. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  13804. paramIdx++;
  13805. BfType* resolvedTypeRef = NULL;
  13806. BfType* resolvedTypeRef2 = NULL;
  13807. String paramName;
  13808. bool isSplattable = false;
  13809. bool tryLowering = !mIsComptimeModule;
  13810. if (isThis)
  13811. {
  13812. paramName = "this";
  13813. if (methodInstance->mIsClosure)
  13814. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  13815. else
  13816. resolvedTypeRef = methodInstance->GetThisType();
  13817. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  13818. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  13819. }
  13820. else
  13821. {
  13822. paramName = methodInstance->GetParamName(paramIdx);
  13823. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  13824. if (resolvedTypeRef->IsMethodRef())
  13825. isSplattable = true;
  13826. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  13827. {
  13828. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  13829. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  13830. {
  13831. // crepr splat is always splattable
  13832. isSplattable = true;
  13833. }
  13834. else
  13835. {
  13836. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  13837. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  13838. isSplattable = true;
  13839. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  13840. isSplattable = true;
  13841. }
  13842. }
  13843. }
  13844. if (tryLowering)
  13845. {
  13846. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13847. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13848. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  13849. {
  13850. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  13851. argIdx++;
  13852. if (loweredTypeCode2 != BfTypeCode_None)
  13853. {
  13854. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  13855. argIdx++;
  13856. }
  13857. paramIdx++;
  13858. continue;
  13859. }
  13860. }
  13861. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  13862. {
  13863. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  13864. int addDeref = -1;
  13865. if (resolvedTypeRef->IsRef())
  13866. {
  13867. auto refType = (BfRefType*)resolvedTypeRef;
  13868. auto elementType = refType->mElementType;
  13869. PopulateType(elementType, BfPopulateType_Data);
  13870. addDeref = elementType->mSize;
  13871. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  13872. AssertErrorState();
  13873. }
  13874. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  13875. {
  13876. if (isThis)
  13877. {
  13878. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  13879. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  13880. addDeref = resolvedTypeRef->mSize;
  13881. }
  13882. else if ((methodInstance->WantsStructsAttribByVal()) && (!resolvedTypeRef->IsSizedArray()))
  13883. {
  13884. mBfIRBuilder->PopulateType(resolvedTypeRef);
  13885. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  13886. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  13887. }
  13888. }
  13889. else if (resolvedTypeRef->IsPrimitiveType())
  13890. {
  13891. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  13892. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  13893. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  13894. }
  13895. if (addDeref >= 0)
  13896. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  13897. argIdx++;
  13898. };
  13899. if (isSplattable)
  13900. {
  13901. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  13902. {
  13903. if (checkType->IsStruct())
  13904. {
  13905. auto checkTypeInstance = checkType->ToTypeInstance();
  13906. if (checkTypeInstance->mBaseType != NULL)
  13907. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  13908. if (checkTypeInstance->mIsUnion)
  13909. {
  13910. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  13911. checkTypeLambda(unionInnerType, curName + "_data");
  13912. }
  13913. else
  13914. {
  13915. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13916. {
  13917. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13918. auto fieldDef = fieldInstance->GetFieldDef();
  13919. if (fieldInstance->mDataIdx >= 0)
  13920. {
  13921. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  13922. }
  13923. }
  13924. }
  13925. if (checkTypeInstance->IsEnum())
  13926. {
  13927. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  13928. argIdx++;
  13929. }
  13930. }
  13931. else if (checkType->IsMethodRef())
  13932. {
  13933. auto methodRefType = (BfMethodRefType*)checkType;
  13934. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  13935. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  13936. {
  13937. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  13938. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  13939. {
  13940. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  13941. }
  13942. else
  13943. {
  13944. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  13945. }
  13946. }
  13947. }
  13948. else if (!checkType->IsValuelessType())
  13949. {
  13950. _SetupParam(curName, checkType);
  13951. }
  13952. };
  13953. checkTypeLambda(resolvedTypeRef, paramName);
  13954. paramIdx++;
  13955. continue;
  13956. }
  13957. _SetupParam(paramName, resolvedTypeRef);
  13958. if (resolvedTypeRef2 != NULL)
  13959. _SetupParam(paramName, resolvedTypeRef2);
  13960. paramIdx++;
  13961. }
  13962. }
  13963. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  13964. {
  13965. auto methodDef = mCurMethodInstance->mMethodDef;
  13966. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  13967. BfMemberSetEntry* entry = NULL;
  13968. BfMethodDef* initMethodDef = NULL;
  13969. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  13970. if (entry != NULL)
  13971. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  13972. SizedArray<BfAstNode*, 8> initBodies;
  13973. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  13974. {
  13975. if (initMethodDef->mDeclaringType != methodDef->mDeclaringType)
  13976. continue;
  13977. if (initMethodDef->mMethodType != BfMethodType_Init)
  13978. continue;
  13979. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  13980. continue;
  13981. initBodies.Insert(0, initMethodDef->mBody);
  13982. }
  13983. for (auto body : initBodies)
  13984. {
  13985. initBlockCallback(body);
  13986. VisitEmbeddedStatement(body);
  13987. }
  13988. }
  13989. void BfModule::EmitCtorBody(bool& skipBody)
  13990. {
  13991. auto methodInstance = mCurMethodInstance;
  13992. auto methodDef = methodInstance->mMethodDef;
  13993. auto methodDeclaration = methodDef->mMethodDeclaration;
  13994. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  13995. auto typeDef = mCurTypeInstance->mTypeDef;
  13996. BfCustomAttributes* customAttributes = NULL;
  13997. defer(delete customAttributes);
  13998. BfInvocationExpression* ctorInvocation = NULL;
  13999. BfAttributeState attributeState;
  14000. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  14001. if (ctorDeclaration != NULL)
  14002. {
  14003. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14004. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14005. {
  14006. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14007. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  14008. }
  14009. }
  14010. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  14011. // Prologue
  14012. mBfIRBuilder->ClearDebugLocation();
  14013. bool hadThisInitializer = false;
  14014. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14015. {
  14016. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14017. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14018. if (targetToken->GetToken() == BfToken_This)
  14019. {
  14020. hadThisInitializer = true;
  14021. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  14022. mCurMethodState->LocalDefined(GetThisVariable());
  14023. }
  14024. }
  14025. // Zero out memory for default ctor
  14026. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  14027. {
  14028. if (mCurTypeInstance->IsTypedPrimitive())
  14029. {
  14030. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  14031. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  14032. }
  14033. else if (mCurTypeInstance->mInstSize > 0)
  14034. {
  14035. BfIRValue fillValue = GetConstValue8(0);
  14036. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  14037. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  14038. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  14039. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  14040. }
  14041. }
  14042. BfAstNode* baseCtorNode = NULL;
  14043. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  14044. baseCtorNode = ctorInvocation->mTarget;
  14045. else if (methodDef->mBody != NULL)
  14046. baseCtorNode = methodDef->mBody;
  14047. else if (ctorDeclaration != NULL)
  14048. baseCtorNode = ctorDeclaration;
  14049. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14050. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  14051. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14052. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  14053. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  14054. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  14055. else
  14056. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  14057. bool calledCtorNoBody = false;
  14058. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  14059. {
  14060. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  14061. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  14062. {
  14063. BfMethodDef* defaultCtor = NULL;
  14064. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  14065. {
  14066. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  14067. {
  14068. defaultCtor = methodDef;
  14069. }
  14070. }
  14071. if (defaultCtor != NULL)
  14072. {
  14073. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  14074. SetIllegalSrcPos();
  14075. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  14076. BfExprEvaluator exprEvaluator(this);
  14077. SizedArray<BfIRValue, 1> irArgs;
  14078. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  14079. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  14080. if (mIsComptimeModule)
  14081. mCompiler->mCEMachine->QueueMethod(moduleMethodInstance);
  14082. calledCtorNoBody = true;
  14083. }
  14084. }
  14085. }
  14086. // Initialize fields (if applicable)
  14087. if (mCurTypeInstance->IsBoxed())
  14088. {
  14089. skipBody = true;
  14090. }
  14091. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  14092. {
  14093. // Field initializers occur in CtorNoBody methods for extensions
  14094. }
  14095. else if (!hadThisInitializer)
  14096. {
  14097. // If we had a 'this' initializer, that other ctor will have initialized our fields
  14098. //auto
  14099. if ((!mCompiler->mIsResolveOnly) ||
  14100. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  14101. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  14102. {
  14103. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  14104. // to properly set the assigned flags
  14105. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  14106. bool hadInlineInitBlock = false;
  14107. BfScopeData scopeData;
  14108. scopeData.mInInitBlock = true;
  14109. auto _CheckInitBlock = [&](BfAstNode* node)
  14110. {
  14111. if (!hadInlineInitBlock)
  14112. {
  14113. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  14114. {
  14115. UpdateSrcPos(baseCtorNode);
  14116. if (methodDef->mBody == NULL)
  14117. SetIllegalSrcPos();
  14118. // 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
  14119. EmitEnsureInstructionAt();
  14120. BfType* thisType = mCurTypeInstance;
  14121. if (thisType->IsValueType())
  14122. thisType = CreateRefType(thisType);
  14123. SizedArray<BfIRMDNode, 1> diParamTypes;
  14124. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  14125. mCurMethodState->AddScope(&scopeData);
  14126. NewScopeState();
  14127. int flags = 0;
  14128. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  14129. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  14130. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  14131. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  14132. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  14133. UpdateSrcPos(node);
  14134. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14135. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  14136. //
  14137. {
  14138. auto loadedThis = GetThis();
  14139. // LLVM can't handle two variables pointing to the same value
  14140. BfIRValue copiedThisPtr;
  14141. copiedThisPtr = CreateAlloca(thisType);
  14142. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  14143. mBfIRBuilder->ClearDebugLocation(storeInst);
  14144. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  14145. }
  14146. hadInlineInitBlock = true;
  14147. }
  14148. else
  14149. {
  14150. // Just do a simple one
  14151. mCurMethodState->AddScope(&scopeData);
  14152. NewScopeState();
  14153. hadInlineInitBlock = true;
  14154. }
  14155. }
  14156. UpdateSrcPos(node);
  14157. };
  14158. for (auto fieldDef : typeDef->mFields)
  14159. {
  14160. // For extensions, only handle these fields in the appropriate extension
  14161. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14162. continue;
  14163. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  14164. {
  14165. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14166. if (!fieldInst->mFieldIncluded)
  14167. continue;
  14168. if (fieldInst->mDataIdx < 0)
  14169. continue;
  14170. if (fieldDef->mInitializer == NULL)
  14171. {
  14172. continue;
  14173. // if (fieldDef->mProtection != BfProtection_Hidden)
  14174. // continue;
  14175. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  14176. // continue;
  14177. }
  14178. if (fieldInst->mResolvedType == NULL)
  14179. {
  14180. BF_ASSERT(mHadBuildError);
  14181. continue;
  14182. }
  14183. if (fieldDef->mInitializer != NULL)
  14184. {
  14185. _CheckInitBlock(fieldDef->mInitializer);
  14186. }
  14187. BfIRValue fieldAddr;
  14188. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  14189. {
  14190. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  14191. }
  14192. else
  14193. {
  14194. // Failed
  14195. }
  14196. auto assignValue = GetFieldInitializerValue(fieldInst);
  14197. if (mCurTypeInstance->IsUnion())
  14198. {
  14199. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  14200. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  14201. }
  14202. if ((fieldAddr) && (assignValue))
  14203. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  14204. }
  14205. }
  14206. EmitInitBlocks(_CheckInitBlock);
  14207. if (hadInlineInitBlock)
  14208. {
  14209. RestoreScopeState();
  14210. // This gets set to false because of AddScope but we actually are still in the head block
  14211. mCurMethodState->mInHeadScope = true;
  14212. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  14213. mCurMethodState->mHadReturn = false;
  14214. mCurMethodState->mLeftBlockUncond = false;
  14215. }
  14216. }
  14217. else // Autocomplete case
  14218. {
  14219. BfScopeData scopeData;
  14220. scopeData.mInInitBlock = true;
  14221. mCurMethodState->AddScope(&scopeData);
  14222. NewScopeState();
  14223. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  14224. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  14225. // resolve pass, NOT the autocomplete expression
  14226. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14227. {
  14228. if (tempTypeDef->mFullName == typeDef->mFullName)
  14229. {
  14230. for (auto fieldDef : tempTypeDef->mFields)
  14231. {
  14232. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  14233. {
  14234. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  14235. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  14236. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  14237. if ((wantType != NULL) &&
  14238. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  14239. wantType = NULL;
  14240. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  14241. }
  14242. }
  14243. tempTypeDef->PopulateMemberSets();
  14244. BfMemberSetEntry* entry = NULL;
  14245. BfMethodDef* initMethodDef = NULL;
  14246. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  14247. if (entry != NULL)
  14248. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  14249. SizedArray<BfAstNode*, 8> initBodies;
  14250. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  14251. {
  14252. if (initMethodDef->mMethodType != BfMethodType_Init)
  14253. continue;
  14254. initBodies.Insert(0, initMethodDef->mBody);
  14255. }
  14256. for (auto body : initBodies)
  14257. VisitEmbeddedStatement(body);
  14258. }
  14259. }
  14260. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  14261. for (auto fieldDef : typeDef->mFields)
  14262. {
  14263. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  14264. {
  14265. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14266. if (fieldDef->mInitializer != NULL)
  14267. MarkFieldInitialized(fieldInst);
  14268. }
  14269. }
  14270. RestoreScopeState();
  14271. }
  14272. }
  14273. if (!methodInstance->mIsAutocompleteMethod)
  14274. {
  14275. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  14276. {
  14277. BfExprEvaluator exprEvaluator(this);
  14278. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  14279. {
  14280. auto paramDef = methodDef->mParams[paramIdx];
  14281. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  14282. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  14283. if (fieldInstance.mDataIdx < 0)
  14284. continue;
  14285. if (paramDef->mParamKind != BfParamKind_Normal)
  14286. continue;
  14287. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  14288. BF_ASSERT(localVar->mName == paramDef->mName);
  14289. auto localVal = exprEvaluator.LoadLocal(localVar);
  14290. localVal = LoadOrAggregateValue(localVal);
  14291. auto thisVal = GetThis();
  14292. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  14293. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  14294. MarkFieldInitialized(&fieldInstance);
  14295. }
  14296. }
  14297. }
  14298. // Call base ctor (if applicable)
  14299. BfTypeInstance* targetType = NULL;
  14300. BfAstNode* targetRefNode = NULL;
  14301. if (ctorDeclaration != NULL)
  14302. targetRefNode = ctorDeclaration->mInitializer;
  14303. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  14304. targetRefNode = invocationExpr->mTarget;
  14305. if (baseCtorNode != NULL)
  14306. {
  14307. UpdateSrcPos(baseCtorNode);
  14308. if (methodDef->mBody == NULL)
  14309. SetIllegalSrcPos();
  14310. }
  14311. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14312. {
  14313. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14314. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14315. }
  14316. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  14317. {
  14318. auto baseType = mCurTypeInstance->mBaseType;
  14319. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  14320. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  14321. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  14322. {
  14323. // Try to find a ctor without any params first
  14324. BfMethodDef* matchedMethod = NULL;
  14325. bool hadCtorWithAllDefaults = false;
  14326. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  14327. for (int pass = 0; pass < 2; pass++)
  14328. {
  14329. baseType->mTypeDef->PopulateMemberSets();
  14330. BfMemberSetEntry* entry = NULL;
  14331. BfMethodDef* checkMethodDef = NULL;
  14332. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  14333. if (entry != NULL)
  14334. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  14335. while (checkMethodDef != NULL)
  14336. {
  14337. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  14338. if (isHiddenGenerated)
  14339. {
  14340. // Allow calling of the default base ctor if it is implicitly defined
  14341. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  14342. allowMethod = true;
  14343. }
  14344. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  14345. {
  14346. if (checkMethodDef->mParams.size() == 0)
  14347. {
  14348. matchedMethod = checkMethodDef;
  14349. }
  14350. else if (isHiddenGenerated)
  14351. {
  14352. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  14353. hadCtorWithAllDefaults = true;
  14354. }
  14355. }
  14356. checkMethodDef = checkMethodDef->mNextWithSameName;
  14357. }
  14358. if (matchedMethod != NULL)
  14359. break;
  14360. }
  14361. if ((HasCompiledOutput()) && (matchedMethod != NULL))
  14362. {
  14363. SizedArray<BfIRValue, 1> args;
  14364. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  14365. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  14366. {
  14367. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  14368. args.push_back(basePtr);
  14369. }
  14370. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  14371. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  14372. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  14373. if (callingConv != BfIRCallingConv_CDecl)
  14374. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  14375. if (mIsComptimeModule)
  14376. mCompiler->mCEMachine->QueueMethod(ctorBodyMethodInstance);
  14377. }
  14378. if (matchedMethod == NULL)
  14379. {
  14380. targetType = mCurTypeInstance->mBaseType;
  14381. if (ctorDeclaration != NULL)
  14382. targetRefNode = ctorDeclaration->mThisToken;
  14383. else if (typeDef->mTypeDeclaration != NULL)
  14384. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  14385. }
  14386. }
  14387. }
  14388. if (methodDef->mHasAppend)
  14389. {
  14390. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  14391. }
  14392. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  14393. {
  14394. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  14395. {
  14396. if (targetType == mCurTypeInstance)
  14397. {
  14398. auto thisVariable = GetThisVariable();
  14399. if (thisVariable != NULL)
  14400. {
  14401. thisVariable->mUnassignedFieldFlags = 0;
  14402. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14403. }
  14404. }
  14405. targetType = NULL;
  14406. }
  14407. }
  14408. if (targetType != NULL)
  14409. {
  14410. BfAstNode* refNode = methodDeclaration;
  14411. if (refNode == NULL)
  14412. refNode = typeDef->mTypeDeclaration;
  14413. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  14414. auto autoComplete = mCompiler->GetAutoComplete();
  14415. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  14416. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14417. {
  14418. auto invocationExpr = ctorInvocation;
  14419. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  14420. }
  14421. BfType* targetThisType = targetType;
  14422. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  14423. BfExprEvaluator exprEvaluator(this);
  14424. BfResolvedArgs argValues;
  14425. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14426. {
  14427. argValues.Init(&ctorInvocation->mArguments);
  14428. if (gDebugStuff)
  14429. {
  14430. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  14431. }
  14432. }
  14433. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14434. BfTypedValue appendIdxVal;
  14435. if (methodDef->mHasAppend)
  14436. {
  14437. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  14438. BF_ASSERT(localVar->mName == "appendIdx");
  14439. auto intRefType = localVar->mResolvedType;
  14440. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  14441. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  14442. }
  14443. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  14444. if (autoComplete != NULL)
  14445. {
  14446. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14447. {
  14448. if (autoComplete->mMethodMatchInfo != NULL)
  14449. autoComplete->mIsCapturingMethodMatchInfo = true;
  14450. else
  14451. autoComplete->mIsCapturingMethodMatchInfo = false;
  14452. }
  14453. else
  14454. autoComplete->mIsCapturingMethodMatchInfo = false;
  14455. }
  14456. }
  14457. }
  14458. void BfModule::EmitEnumToStringBody()
  14459. {
  14460. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  14461. auto strVal = CreateAlloca(stringType);
  14462. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  14463. BfExprEvaluator exprEvaluator(this);
  14464. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  14465. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  14466. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  14467. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  14468. BfType* discriminatorType = NULL;
  14469. BfTypedValue rawPayload;
  14470. BfIRValue enumVal;
  14471. if (mCurTypeInstance->IsPayloadEnum())
  14472. {
  14473. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  14474. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  14475. enumTypedValue = LoadValue(enumTypedValue);
  14476. enumVal = enumTypedValue.mValue;
  14477. rawPayload = ExtractValue(GetThis(), NULL, 1);
  14478. }
  14479. else
  14480. enumVal = mBfIRBuilder->GetArgument(0);
  14481. Array<BfType*> paramTypes;
  14482. paramTypes.Add(stringType);
  14483. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  14484. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  14485. HashSet<int64> handledCases;
  14486. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  14487. {
  14488. if (fieldInstance.mIsEnumPayloadCase)
  14489. {
  14490. int tagId = -fieldInstance.mDataIdx - 1;
  14491. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  14492. mBfIRBuilder->AddBlock(caseBlock);
  14493. mBfIRBuilder->SetInsertPoint(caseBlock);
  14494. BF_ASSERT(discriminatorType->IsPrimitiveType());
  14495. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  14496. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  14497. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  14498. auto stringDestVal = LoadValue(stringDestAddr);
  14499. SizedArray<BfIRValue, 2> args;
  14500. args.Add(stringDestVal.mValue);
  14501. args.Add(caseStr);
  14502. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  14503. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  14504. BF_ASSERT(payloadType->IsTuple());
  14505. if (payloadType->mFieldInstances.size() != 0)
  14506. {
  14507. auto payload = rawPayload;
  14508. if (payload.mType != payloadType)
  14509. {
  14510. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  14511. }
  14512. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  14513. SizedArray<BfIRValue, 2> irArgs;
  14514. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  14515. stringDestVal = LoadValue(stringDestAddr);
  14516. irArgs.Add(stringDestVal.mValue);
  14517. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  14518. }
  14519. mBfIRBuilder->CreateBr(endBlock);
  14520. continue;
  14521. }
  14522. if (fieldInstance.mConstIdx == -1)
  14523. continue;
  14524. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  14525. if (!handledCases.TryAdd(constant->mInt64, NULL))
  14526. {
  14527. // Duplicate
  14528. continue;
  14529. }
  14530. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  14531. mBfIRBuilder->AddBlock(caseBlock);
  14532. mBfIRBuilder->SetInsertPoint(caseBlock);
  14533. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  14534. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  14535. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  14536. mBfIRBuilder->CreateStore(caseStr, strVal);
  14537. mBfIRBuilder->CreateBr(appendBlock);
  14538. }
  14539. mBfIRBuilder->AddBlock(appendBlock);
  14540. mBfIRBuilder->SetInsertPoint(appendBlock);
  14541. SizedArray<BfIRValue, 2> args;
  14542. auto stringDestVal = LoadValue(stringDestAddr);
  14543. args.Add(stringDestVal.mValue);
  14544. args.Add(mBfIRBuilder->CreateLoad(strVal));
  14545. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  14546. mBfIRBuilder->CreateBr(endBlock);
  14547. mBfIRBuilder->AddBlock(noMatchBlock);
  14548. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  14549. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  14550. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  14551. args.clear();
  14552. args.Add(int64Val);
  14553. stringDestVal = LoadValue(stringDestAddr);
  14554. args.Add(stringDestVal.mValue);
  14555. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  14556. mBfIRBuilder->CreateBr(endBlock);
  14557. mBfIRBuilder->AddBlock(endBlock);
  14558. mBfIRBuilder->SetInsertPoint(endBlock);
  14559. }
  14560. void BfModule::EmitTupleToStringBody()
  14561. {
  14562. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  14563. BfExprEvaluator exprEvaluator(this);
  14564. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  14565. Array<BfType*> paramTypes;
  14566. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  14567. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  14568. paramTypes.Clear();
  14569. paramTypes.Add(stringType);
  14570. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  14571. auto _AppendChar = [&](char c)
  14572. {
  14573. SizedArray<BfIRValue, 2> args;
  14574. auto stringDestVal = LoadValue(stringDestRef);
  14575. args.Add(stringDestVal.mValue);
  14576. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  14577. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  14578. };
  14579. int fieldIdx = 0;
  14580. auto thisValue = GetThis();
  14581. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  14582. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  14583. BfIRValue commaStr;
  14584. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  14585. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  14586. _AppendChar('(');
  14587. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  14588. {
  14589. if (fieldInstance.mDataIdx == -1)
  14590. continue;
  14591. if (fieldIdx > 0)
  14592. {
  14593. if (!commaStr)
  14594. commaStr = GetStringObjectValue(", ");
  14595. SizedArray<BfIRValue, 2> args;
  14596. auto stringDestVal = LoadValue(stringDestRef);
  14597. args.Add(stringDestVal.mValue);
  14598. args.Add(commaStr);
  14599. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  14600. }
  14601. fieldIdx++;
  14602. if (fieldInstance.mResolvedType->IsValuelessType())
  14603. continue;
  14604. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  14605. if (fieldValue.mType->IsPrimitiveType())
  14606. {
  14607. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  14608. }
  14609. auto typeInstance = fieldValue.mType->ToTypeInstance();
  14610. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  14611. {
  14612. BfExprEvaluator exprEvaluator(this);
  14613. SizedArray<BfResolvedArg, 0> resolvedArgs;
  14614. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  14615. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  14616. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  14617. methodMatcher.TryDevirtualizeCall(fieldValue);
  14618. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  14619. BfResolvedArg resolvedArg;
  14620. auto stringDestVal = LoadValue(stringDestRef);
  14621. resolvedArg.mTypedValue = stringDestVal;
  14622. resolvedArg.mResolvedType = stringDestVal.mType;
  14623. resolvedArgs.Add(resolvedArg);
  14624. exprEvaluator.CreateCall(&methodMatcher, callVal);
  14625. continue;
  14626. }
  14627. if (fieldValue.mType->IsObjectOrInterface())
  14628. {
  14629. fieldValue = LoadValue(fieldValue);
  14630. BF_ASSERT(!fieldValue.IsAddr());
  14631. SizedArray<BfIRValue, 2> args;
  14632. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  14633. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  14634. stringDestVal = LoadValue(stringDestVal);
  14635. args.Add(stringDestVal.mValue);
  14636. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  14637. continue;
  14638. }
  14639. BfExprEvaluator exprEvaluator(this);
  14640. SizedArray<BfResolvedArg, 0> resolvedArgs;
  14641. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  14642. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  14643. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  14644. methodMatcher.TryDevirtualizeCall(fieldValue);
  14645. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  14646. {
  14647. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  14648. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  14649. // Just append the type name
  14650. String typeName = TypeToString(fieldInstance.mResolvedType);
  14651. auto strVal = GetStringObjectValue(typeName);
  14652. SizedArray<BfIRValue, 2> args;
  14653. auto stringDestVal = LoadValue(stringDestRef);
  14654. args.Add(stringDestVal.mValue);
  14655. args.Add(strVal);
  14656. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  14657. continue;
  14658. }
  14659. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  14660. BfResolvedArg resolvedArg;
  14661. auto stringDestVal = LoadValue(stringDestRef);
  14662. resolvedArg.mTypedValue = stringDestVal;
  14663. resolvedArg.mResolvedType = stringDestVal.mType;
  14664. resolvedArgs.Add(resolvedArg);
  14665. exprEvaluator.CreateCall(&methodMatcher, callVal);
  14666. }
  14667. _AppendChar(')');
  14668. }
  14669. void BfModule::EmitIteratorBlock(bool& skipBody)
  14670. {
  14671. auto methodInstance = mCurMethodInstance;
  14672. auto methodDef = methodInstance->mMethodDef;
  14673. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14674. auto typeDef = mCurTypeInstance->mTypeDef;
  14675. BfType* innerRetType = NULL;
  14676. BfTypeInstance* usingInterface = NULL;
  14677. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  14678. if (retTypeInst != NULL)
  14679. {
  14680. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  14681. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  14682. {
  14683. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  14684. }
  14685. }
  14686. if (innerRetType == NULL)
  14687. {
  14688. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  14689. return;
  14690. }
  14691. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  14692. if (blockBody == NULL)
  14693. return;
  14694. }
  14695. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  14696. {
  14697. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  14698. if (fieldTypeInst == NULL)
  14699. return;
  14700. if (!markVal.mType->IsComposite())
  14701. markVal = LoadValue(markVal);
  14702. BfExprEvaluator exprEvaluator(this);
  14703. PopulateType(markVal.mType, BfPopulateType_Data);
  14704. if (markVal.mType->IsObjectOrInterface())
  14705. {
  14706. BfIRValue val = markVal.mValue;
  14707. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14708. SizedArray<BfIRValue, 1> args;
  14709. args.push_back(val);
  14710. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  14711. }
  14712. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  14713. {
  14714. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  14715. if (markMemberMethodInstance)
  14716. {
  14717. SizedArray<BfIRValue, 1> args;
  14718. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  14719. if (markVal.mType != methodOwner)
  14720. markVal = Cast(NULL, markVal, methodOwner);
  14721. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  14722. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  14723. }
  14724. }
  14725. }
  14726. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  14727. {
  14728. Array<BfMethodInstance*> methodInstances;
  14729. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  14730. {
  14731. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  14732. auto chainedMethodInst = methodInstGroup.mDefault;
  14733. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  14734. {
  14735. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  14736. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  14737. {
  14738. methodInstances.push_back(chainedMethodInst);
  14739. }
  14740. }
  14741. }
  14742. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  14743. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  14744. {
  14745. bool isBetter;
  14746. bool isWorse;
  14747. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  14748. if (isBetter == isWorse)
  14749. {
  14750. return false;
  14751. }
  14752. return isWorse;
  14753. });
  14754. if (reverse)
  14755. std::reverse(methodInstances.begin(), methodInstances.end());
  14756. for (auto chainedMethodInst : methodInstances)
  14757. {
  14758. auto declModule = this;
  14759. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14760. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  14761. BfExprEvaluator exprEvaluator(this);
  14762. SizedArray<BfIRValue, 1> args;
  14763. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  14764. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  14765. }
  14766. }
  14767. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  14768. {
  14769. BF_ASSERT(mCurMethodInstance->mIsReified);
  14770. if (mCurTypeInstance->mHotTypeData == NULL)
  14771. {
  14772. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  14773. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  14774. }
  14775. auto hotMethod = mCurMethodInstance->mHotMethod;
  14776. for (auto depData : hotMethod->mReferences)
  14777. {
  14778. // Only virtual decls are allowed to already be there
  14779. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  14780. }
  14781. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  14782. int prevSize = (int)hotMethod->mReferences.size();
  14783. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  14784. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14785. refCount++;
  14786. hotMethod->mReferences.Reserve(refCount);
  14787. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14788. {
  14789. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  14790. hotThis->mRefCount++;
  14791. hotMethod->mReferences.Insert(0, hotThis);
  14792. prevSize++;
  14793. }
  14794. for (auto val : builder->mAllocatedData)
  14795. {
  14796. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  14797. hotMethod->mReferences.Add(hotAllocation);
  14798. }
  14799. for (auto val : builder->mUsedData)
  14800. hotMethod->mReferences.Add(val);
  14801. for (auto val : builder->mCalledMethods)
  14802. hotMethod->mReferences.Add(val);
  14803. for (auto val : builder->mDevirtualizedCalledMethods)
  14804. {
  14805. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  14806. hotMethod->mReferences.Add(devirtualizedMethod);
  14807. }
  14808. for (auto val : builder->mFunctionPtrs)
  14809. {
  14810. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  14811. hotMethod->mReferences.Add(funcRef);
  14812. }
  14813. for (auto val : builder->mInnerMethods)
  14814. {
  14815. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  14816. hotMethod->mReferences.Add(innerMethod);
  14817. }
  14818. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  14819. {
  14820. auto depData = hotMethod->mReferences[refIdx];
  14821. BF_ASSERT(depData != NULL);
  14822. depData->mRefCount++;
  14823. }
  14824. }
  14825. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  14826. {
  14827. auto methodDef = methodInstance->mMethodDef;
  14828. auto methodDeclaration = methodDef->mMethodDeclaration;
  14829. bool isThisStruct = false;
  14830. if (thisType != NULL)
  14831. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  14832. int argIdx = 0;
  14833. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  14834. argIdx++;
  14835. if (!methodDef->mIsStatic)
  14836. {
  14837. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14838. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14839. BfLocalVariable* paramVar = new BfLocalVariable();
  14840. paramVar->mResolvedType = thisType;
  14841. paramVar->mName = "this";
  14842. if (!thisType->IsValuelessType())
  14843. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14844. else
  14845. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14846. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  14847. {
  14848. if (!thisType->IsTypedPrimitive())
  14849. paramVar->mIsSplat = true;
  14850. }
  14851. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  14852. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14853. auto thisTypeInst = thisType->ToTypeInstance();
  14854. paramVar->mIsStruct = isThisStruct;
  14855. paramVar->mAddr = BfIRValue();
  14856. paramVar->mIsThis = true;
  14857. paramVar->mParamIdx = -1;
  14858. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  14859. {
  14860. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  14861. }
  14862. else
  14863. {
  14864. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14865. }
  14866. paramVar->mReadFromId = -1;
  14867. paramVar->Init();
  14868. if (methodDeclaration == NULL)
  14869. UseDefaultSrcPos();
  14870. AddLocalVariableDef(paramVar);
  14871. if (!thisType->IsValuelessType())
  14872. {
  14873. if (wantsDIData)
  14874. {
  14875. BfType* thisPtrType = thisType;
  14876. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  14877. if (!thisType->IsValueType())
  14878. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14879. else if (!paramVar->mIsSplat)
  14880. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  14881. diParams->push_back(diType);
  14882. }
  14883. if (paramVar->mIsSplat)
  14884. {
  14885. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14886. }
  14887. else
  14888. {
  14889. argIdx++;
  14890. if (loweredTypeCode2 != BfTypeCode_None)
  14891. argIdx++;
  14892. }
  14893. }
  14894. }
  14895. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  14896. argIdx++;
  14897. bool hadParams = false;
  14898. bool hasDefault = false;
  14899. int compositeVariableIdx = -1;
  14900. int paramIdx = 0;
  14901. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  14902. {
  14903. // We already issues a type error for this param if we had one in declaration processing
  14904. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  14905. BfLocalVariable* paramVar = new BfLocalVariable();
  14906. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14907. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14908. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  14909. auto resolvedType = methodInstance->GetParamType(paramIdx);
  14910. if (resolvedType == NULL)
  14911. {
  14912. AssertErrorState();
  14913. paramVar->mParamFailed = true;
  14914. }
  14915. prevIgnoreErrors.Restore();
  14916. PopulateType(resolvedType, BfPopulateType_Declaration);
  14917. paramVar->mResolvedType = resolvedType;
  14918. paramVar->mName = methodInstance->GetParamName(paramIdx);
  14919. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  14920. if (!isParamSkipped)
  14921. {
  14922. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14923. if (resolvedType->IsMethodRef())
  14924. {
  14925. paramVar->mIsSplat = true;
  14926. }
  14927. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  14928. {
  14929. if (methodInstance->AllowsSplatting(paramIdx))
  14930. {
  14931. auto resolveTypeInst = resolvedType->ToTypeInstance();
  14932. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  14933. paramVar->mIsSplat = true;
  14934. else
  14935. {
  14936. int splatCount = resolvedType->GetSplatCount();
  14937. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  14938. paramVar->mIsSplat = true;
  14939. }
  14940. }
  14941. }
  14942. }
  14943. else
  14944. {
  14945. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  14946. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14947. }
  14948. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14949. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  14950. paramVar->mParamIdx = paramIdx;
  14951. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  14952. paramVar->mReadFromId = 0;
  14953. if (resolvedType->IsRef())
  14954. {
  14955. auto refType = (BfRefType*)resolvedType;
  14956. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  14957. if (refType->mRefKind == BfRefType::RefKind_In)
  14958. {
  14959. paramVar->mIsReadOnly = true;
  14960. }
  14961. }
  14962. else
  14963. {
  14964. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14965. if (methodDef->mMethodType != BfMethodType_Mixin)
  14966. paramVar->mIsReadOnly = true;
  14967. }
  14968. if (paramVar->mResolvedType->IsGenericParam())
  14969. {
  14970. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  14971. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  14972. {
  14973. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  14974. paramVar->mResolvedType = typedVal.mType;
  14975. paramVar->mConstValue = typedVal.mValue;
  14976. }
  14977. }
  14978. if (paramVar->mResolvedType->IsConstExprValue())
  14979. {
  14980. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  14981. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  14982. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  14983. BF_ASSERT(unspecParamType->IsGenericParam());
  14984. if (unspecParamType->IsGenericParam())
  14985. {
  14986. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  14987. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  14988. {
  14989. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  14990. if (genericParamInst->mTypeConstraint != NULL)
  14991. {
  14992. BfExprEvaluator exprEvaluator(this);
  14993. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  14994. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  14995. auto checkType = genericParamInst->mTypeConstraint;
  14996. if (checkType->IsTypedPrimitive())
  14997. checkType = checkType->GetUnderlyingType();
  14998. if (exprEvaluator.mResult.mType == checkType)
  14999. {
  15000. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  15001. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  15002. BF_ASSERT(paramVar->mConstValue.IsConst());
  15003. }
  15004. else
  15005. {
  15006. AssertErrorState();
  15007. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  15008. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  15009. }
  15010. }
  15011. }
  15012. }
  15013. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  15014. if (paramVar->mResolvedType->IsConstExprValue())
  15015. {
  15016. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  15017. //AssertErrorState();
  15018. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  15019. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  15020. }
  15021. }
  15022. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  15023. {
  15024. if (compositeVariableIdx == -1)
  15025. {
  15026. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  15027. BfLocalVariable* localVar = new BfLocalVariable();
  15028. auto paramInst = &methodInstance->mParams[paramIdx];
  15029. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  15030. localVar->mName = paramDef->mName;
  15031. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  15032. localVar->mCompositeCount = 0;
  15033. DoAddLocalVariable(localVar);
  15034. }
  15035. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  15036. }
  15037. CheckVariableDef(paramVar);
  15038. paramVar->Init();
  15039. AddLocalVariableDef(paramVar);
  15040. if (!isParamSkipped)
  15041. {
  15042. if (wantsDIData)
  15043. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  15044. if (paramVar->mIsSplat)
  15045. {
  15046. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15047. }
  15048. else
  15049. {
  15050. argIdx++;
  15051. }
  15052. if (loweredTypeCode2 != BfTypeCode_None)
  15053. argIdx++;
  15054. }
  15055. }
  15056. // Try to find an ending delegate params composite
  15057. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  15058. {
  15059. auto paramDef = methodDef->mParams.back();
  15060. if (paramDef->mParamKind == BfParamKind_Params)
  15061. {
  15062. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  15063. if (paramsType == NULL)
  15064. {
  15065. AssertErrorState();
  15066. }
  15067. else if (paramsType->IsGenericParam())
  15068. {
  15069. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  15070. if (genericParamInstance->mTypeConstraint != NULL)
  15071. {
  15072. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  15073. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  15074. ((typeInstConstraint != NULL) &&
  15075. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  15076. {
  15077. BfLocalVariable* localVar = new BfLocalVariable();
  15078. localVar->mName = paramDef->mName;
  15079. localVar->mResolvedType = paramsType;
  15080. localVar->mCompositeCount = 0;
  15081. DoAddLocalVariable(localVar);
  15082. }
  15083. }
  15084. }
  15085. else if (paramsType->IsDelegate())
  15086. {
  15087. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  15088. if (invokeMethodInstance != NULL)
  15089. {
  15090. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  15091. // and wasn't cleared by the preceding loop
  15092. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  15093. BfLocalVariable* localVar = new BfLocalVariable();
  15094. localVar->mName = paramDef->mName;
  15095. localVar->mResolvedType = paramsType;
  15096. localVar->mCompositeCount = 0;
  15097. DoAddLocalVariable(localVar);
  15098. }
  15099. }
  15100. }
  15101. }
  15102. }
  15103. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  15104. {
  15105. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  15106. // return;
  15107. auto _ClearState = [&]()
  15108. {
  15109. mCurMethodState->mLocalMethods.Clear();
  15110. for (auto& local : mCurMethodState->mLocals)
  15111. delete local;
  15112. mCurMethodState->mLocals.Clear();
  15113. mCurMethodState->mLocalVarSet.Clear();
  15114. };
  15115. // 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
  15116. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  15117. // however (compiler bug), so this is the safest way
  15118. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  15119. {
  15120. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  15121. {
  15122. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  15123. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  15124. if (!mHadBuildError)
  15125. {
  15126. // Process as a closure - that allows us to look back and see the const locals and stuff
  15127. BfClosureState closureState;
  15128. mCurMethodState->mClosureState = &closureState;
  15129. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  15130. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  15131. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  15132. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  15133. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  15134. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15135. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  15136. _ClearState();
  15137. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  15138. {
  15139. auto localVar = new BfLocalVariable();
  15140. *localVar = constLocal;
  15141. DoAddLocalVariable(localVar);
  15142. }
  15143. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  15144. bool doProcess = !mCompiler->mCanceling;
  15145. if (doProcess)
  15146. {
  15147. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  15148. ProcessMethod(deferredLocalMethod->mMethodInstance);
  15149. }
  15150. }
  15151. delete deferredLocalMethod;
  15152. mContext->CheckLockYield();
  15153. }
  15154. }
  15155. for (auto& kv : mCurMethodState->mLocalMethodCache)
  15156. {
  15157. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  15158. }
  15159. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  15160. {
  15161. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  15162. {
  15163. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  15164. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  15165. BfClosureState closureState;
  15166. mCurMethodState->mClosureState = &closureState;
  15167. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  15168. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  15169. if (lambdaInstance->mClosureTypeInstance != NULL)
  15170. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  15171. else
  15172. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  15173. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15174. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  15175. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  15176. _ClearState();
  15177. for (auto& constLocal : lambdaInstance->mConstLocals)
  15178. {
  15179. //if (constLocal.mIsThis)
  15180. {
  15181. // Valueless 'this'
  15182. closureState.mConstLocals.Add(constLocal);
  15183. }
  15184. /*else
  15185. {
  15186. auto localVar = new BfLocalVariable();
  15187. *localVar = constLocal;
  15188. DoAddLocalVariable(localVar);
  15189. }*/
  15190. }
  15191. BfMethodInstanceGroup methodInstanceGroup;
  15192. methodInstanceGroup.mOwner = mCurTypeInstance;
  15193. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15194. bool doProcess = !mCompiler->mCanceling;
  15195. if (doProcess)
  15196. {
  15197. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  15198. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  15199. ProcessMethod(lambdaInstance->mMethodInstance);
  15200. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  15201. if (lambdaInstance->mDtorMethodInstance != NULL)
  15202. {
  15203. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  15204. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  15205. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  15206. }
  15207. }
  15208. }
  15209. mContext->CheckLockYield();
  15210. }
  15211. }
  15212. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  15213. {
  15214. if (checkType->IsComposite())
  15215. PopulateType(checkType, BfPopulateType_Data);
  15216. if (!checkType->WantsGCMarking())
  15217. return;
  15218. auto typeInstance = checkType->ToTypeInstance();
  15219. bool callMarkMethod = false;
  15220. // Call the actual marking method
  15221. if (memberDepth == 0)
  15222. {
  15223. // Don't call marking method on self
  15224. }
  15225. else if (checkType->IsObjectOrInterface())
  15226. {
  15227. if (!objectOffsets.Add(curOffset))
  15228. {
  15229. return;
  15230. }
  15231. callMarkMethod = true;
  15232. }
  15233. else if (checkType->IsSizedArray())
  15234. {
  15235. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  15236. if (sizedArrayType->mElementType->WantsGCMarking())
  15237. {
  15238. BfTypedValue arrayValue = thisValue;
  15239. if (thisValue.mType != checkType)
  15240. {
  15241. BfIRValue srcValue = thisValue.mValue;
  15242. if (curOffset != 0)
  15243. {
  15244. if (!thisValue.mType->IsPointer())
  15245. {
  15246. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  15247. auto int8PtrType = CreatePointerType(int8Type);
  15248. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  15249. }
  15250. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  15251. }
  15252. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  15253. }
  15254. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  15255. {
  15256. if (sizedArrayType->mElementType->IsSizeAligned())
  15257. {
  15258. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  15259. auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  15260. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  15261. return BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  15262. }
  15263. else
  15264. {
  15265. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  15266. return BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  15267. }
  15268. };
  15269. if (sizedArrayType->mElementCount > 6)
  15270. {
  15271. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  15272. auto itr = CreateAlloca(intPtrType);
  15273. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  15274. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  15275. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  15276. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  15277. mBfIRBuilder->CreateBr(loopBB);
  15278. mBfIRBuilder->SetInsertPoint(loopBB);
  15279. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  15280. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  15281. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  15282. mBfIRBuilder->SetInsertPoint(bodyBB);
  15283. BfTypedValue value = _SizedIndex(arrayValue.mValue, loadedItr);
  15284. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  15285. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  15286. mBfIRBuilder->CreateStore(incValue, itr);
  15287. mBfIRBuilder->CreateBr(loopBB);
  15288. mBfIRBuilder->SetInsertPoint(doneBB);
  15289. }
  15290. else
  15291. {
  15292. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  15293. {
  15294. BfTypedValue value = _SizedIndex(arrayValue.mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  15295. HashSet<int> objectOffsets;
  15296. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  15297. }
  15298. }
  15299. }
  15300. }
  15301. else if (typeInstance != NULL)
  15302. {
  15303. typeInstance->mTypeDef->PopulateMemberSets();
  15304. BfMemberSetEntry* entry = NULL;
  15305. BfMethodDef* methodDef = NULL;
  15306. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  15307. {
  15308. methodDef = (BfMethodDef*)entry->mMemberDef;
  15309. if (methodDef->HasBody())
  15310. {
  15311. callMarkMethod = true;
  15312. }
  15313. }
  15314. }
  15315. if (callMarkMethod)
  15316. {
  15317. BfTypedValue markValue;
  15318. auto memberType = checkType;
  15319. if (memberType->IsObjectOrInterface())
  15320. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  15321. auto memberPtrType = CreatePointerType(memberType);
  15322. if (curOffset == 0)
  15323. {
  15324. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  15325. }
  15326. else
  15327. {
  15328. if (!thisValue.mType->IsPointer())
  15329. {
  15330. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  15331. auto int8PtrType = CreatePointerType(int8Type);
  15332. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  15333. }
  15334. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  15335. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  15336. }
  15337. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  15338. return;
  15339. }
  15340. auto methodDef = mCurMethodInstance->mMethodDef;
  15341. if (checkType->IsPayloadEnum())
  15342. {
  15343. for (auto& fieldInst : typeInstance->mFieldInstances)
  15344. {
  15345. if (!fieldInst.mIsEnumPayloadCase)
  15346. continue;
  15347. auto fieldDef = fieldInst.GetFieldDef();
  15348. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  15349. }
  15350. return;
  15351. }
  15352. if (typeInstance == NULL)
  15353. return;
  15354. for (auto& fieldInst : typeInstance->mFieldInstances)
  15355. {
  15356. auto fieldDef = fieldInst.GetFieldDef();
  15357. if (fieldDef == NULL)
  15358. continue;
  15359. if (fieldDef->mIsStatic)
  15360. continue;
  15361. if (typeInstance == mCurTypeInstance)
  15362. {
  15363. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  15364. // we may be marking member values that can never contain a value anyway, but this is benign
  15365. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15366. continue;
  15367. }
  15368. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  15369. }
  15370. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  15371. {
  15372. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  15373. }
  15374. }
  15375. void BfModule::EmitGCMarkMembers()
  15376. {
  15377. auto methodDef = mCurMethodInstance->mMethodDef;
  15378. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  15379. BfModuleMethodInstance markFromGCThreadMethodInstance;
  15380. if (gcType != NULL)
  15381. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  15382. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  15383. {
  15384. if (mCurTypeInstance->IsBoxed())
  15385. {
  15386. // This already gets filled in by the normal boxed forwarding
  15387. }
  15388. else
  15389. {
  15390. auto thisValue = GetThis();
  15391. if (thisValue.IsSplat())
  15392. {
  15393. BfIRFunction func = mCurMethodInstance->mIRFunction;
  15394. int argIdx = 0;
  15395. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  15396. {
  15397. if (checkType->IsStruct())
  15398. {
  15399. auto checkTypeInstance = checkType->ToTypeInstance();
  15400. if (checkTypeInstance->mBaseType != NULL)
  15401. checkTypeLambda(checkTypeInstance->mBaseType);
  15402. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15403. {
  15404. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15405. if (fieldInstance->mDataIdx >= 0)
  15406. checkTypeLambda(fieldInstance->GetResolvedType());
  15407. }
  15408. }
  15409. else if (checkType->IsMethodRef())
  15410. {
  15411. BFMODULE_FATAL(this, "Not handled");
  15412. }
  15413. else if (checkType->WantsGCMarking())
  15414. {
  15415. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  15416. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  15417. argIdx++;
  15418. }
  15419. };
  15420. checkTypeLambda(thisValue.mType);
  15421. }
  15422. else if (!methodDef->mIsStatic)
  15423. {
  15424. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  15425. {
  15426. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  15427. if (moduleMethodInst)
  15428. {
  15429. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  15430. if (methodBaseType != mContext->mBfObjectType)
  15431. {
  15432. auto thisValue = GetThis();
  15433. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  15434. SizedArray<BfIRValue, 1> args;
  15435. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  15436. {
  15437. BfExprEvaluator exprEvaluator(this);
  15438. exprEvaluator.SplatArgs(baseValue, args);
  15439. }
  15440. else
  15441. {
  15442. args.push_back(baseValue.mValue);
  15443. }
  15444. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  15445. }
  15446. }
  15447. }
  15448. }
  15449. if (!methodDef->mIsStatic)
  15450. {
  15451. HashSet<int> objectOffsets;
  15452. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  15453. }
  15454. else
  15455. {
  15456. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  15457. {
  15458. if (thisValue.IsSplat())
  15459. break;
  15460. auto fieldDef = fieldInst.GetFieldDef();
  15461. if (fieldDef == NULL)
  15462. continue;
  15463. if (fieldInst.mIsThreadLocal)
  15464. continue;
  15465. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  15466. {
  15467. // For extensions, only handle these fields in the appropriate extension
  15468. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15469. continue;
  15470. if (!fieldInst.mFieldIncluded)
  15471. continue;
  15472. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  15473. if (fieldTypeInst != NULL)
  15474. {
  15475. auto fieldDef = fieldInst.GetFieldDef();
  15476. BfTypedValue markVal;
  15477. if (fieldDef->mIsConst)
  15478. continue;
  15479. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  15480. continue;
  15481. mBfIRBuilder->PopulateType(fieldTypeInst);
  15482. if (fieldTypeInst->IsValuelessType())
  15483. continue;
  15484. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  15485. {
  15486. StringT<128> staticVarName;
  15487. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  15488. if (staticVarName.StartsWith('#'))
  15489. continue;
  15490. markVal = ReferenceStaticField(&fieldInst);
  15491. }
  15492. else if (!fieldDef->mIsStatic)
  15493. {
  15494. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  15495. }
  15496. if (markVal)
  15497. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  15498. }
  15499. }
  15500. }
  15501. }
  15502. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15503. CallChainedMethods(mCurMethodInstance, false);
  15504. }
  15505. }
  15506. }
  15507. void BfModule::EmitGCFindTLSMembers()
  15508. {
  15509. auto methodDef = mCurMethodInstance->mMethodDef;
  15510. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  15511. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  15512. BF_ASSERT(reportTLSMark);
  15513. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  15514. {
  15515. auto fieldDef = fieldInst.GetFieldDef();
  15516. if (fieldDef == NULL)
  15517. continue;
  15518. if (!fieldInst.mIsThreadLocal)
  15519. continue;
  15520. // For extensions, only handle these fields in the appropriate extension
  15521. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15522. continue;
  15523. if (!fieldInst.mFieldIncluded)
  15524. continue;
  15525. if (fieldDef->mIsConst)
  15526. continue;
  15527. auto fieldType = fieldInst.mResolvedType;
  15528. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  15529. continue;
  15530. if (fieldType->IsValuelessType())
  15531. continue;
  15532. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  15533. if (markVal)
  15534. {
  15535. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  15536. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  15537. SizedArray<BfIRValue, 2> llvmArgs;
  15538. llvmArgs.push_back(fieldRefPtr);
  15539. llvmArgs.push_back(markFuncPtr);
  15540. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  15541. }
  15542. }
  15543. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  15544. CallChainedMethods(mCurMethodInstance, false);
  15545. }
  15546. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  15547. {
  15548. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  15549. if (mAwaitingInitFinish)
  15550. FinishInit();
  15551. if (!methodInstance->mIsReified)
  15552. BF_ASSERT(!mIsReified);
  15553. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedTypeVariation());
  15554. if (methodInstance->mMethodInfoEx != NULL)
  15555. {
  15556. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  15557. {
  15558. if (methodGenericArg->IsMethodRef())
  15559. {
  15560. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  15561. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  15562. }
  15563. }
  15564. }
  15565. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  15566. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  15567. {
  15568. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  15569. }
  15570. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  15571. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  15572. (mCompiler->mResolvePassData != NULL))
  15573. {
  15574. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  15575. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  15576. }
  15577. if (methodInstance->mHasBeenProcessed)
  15578. {
  15579. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  15580. return;
  15581. }
  15582. if (methodInstance->mFailedConstraints)
  15583. {
  15584. // The only way this should be able to happen is if we fail our generic param check
  15585. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  15586. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  15587. methodInstance->mHasBeenProcessed = true;
  15588. return;
  15589. }
  15590. if (HasCompiledOutput())
  15591. {
  15592. BF_ASSERT(mIsModuleMutable);
  15593. }
  15594. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  15595. if (!mIsComptimeModule)
  15596. {
  15597. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  15598. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  15599. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  15600. {
  15601. auto owningModule = methodInstance->GetOwner()->mModule;
  15602. if (owningModule->mIsScratchModule)
  15603. {
  15604. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  15605. }
  15606. else
  15607. {
  15608. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  15609. if (owningModule->mOnDemandMethodCount > 0)
  15610. owningModule->mOnDemandMethodCount--;
  15611. }
  15612. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  15613. VerifyOnDemandMethods();
  15614. }
  15615. }
  15616. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  15617. // self-referencing append allocations in ctor@calcAppend
  15618. methodInstance->mHasBeenProcessed = true;
  15619. mIncompleteMethodCount--;
  15620. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  15621. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  15622. auto methodDef = methodInstance->mMethodDef;
  15623. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15624. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  15625. mBfIRBuilder->mIgnoreWrites = true;
  15626. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  15627. {
  15628. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  15629. // so we get the new vdata for it
  15630. methodInstance->GetOwner()->mDirty = true;
  15631. }
  15632. int dependentGenericStartIdx = 0;
  15633. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  15634. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  15635. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15636. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  15637. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  15638. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  15639. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  15640. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  15641. if ((methodInstance->mIsReified) &&
  15642. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  15643. {
  15644. mCurTypeInstance->mHasBeenInstantiated = true;
  15645. }
  15646. // Warnings are shown in the capture phase
  15647. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  15648. mIgnoreWarnings = true;
  15649. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  15650. UseDefaultSrcPos();
  15651. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  15652. {
  15653. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  15654. }
  15655. else
  15656. {
  15657. // We may not actually be populated in relatively rare autocompelte cases
  15658. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  15659. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  15660. }
  15661. BfAstNode* nameNode = NULL;
  15662. if (methodDeclaration != NULL)
  15663. {
  15664. nameNode = methodDeclaration->mNameNode;
  15665. if (nameNode == NULL)
  15666. {
  15667. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  15668. nameNode = ctorDeclaration->mThisToken;
  15669. }
  15670. }
  15671. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  15672. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  15673. {
  15674. if (methodInstance->GetExplicitInterface() == NULL)
  15675. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  15676. else
  15677. {
  15678. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  15679. {
  15680. auto ifaceInst = ifaceEntry.mInterfaceType;
  15681. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  15682. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  15683. if (methodInstance->GetExplicitInterface() != ifaceInst)
  15684. continue;
  15685. ifaceInst->mTypeDef->PopulateMemberSets();
  15686. BfMethodDef* nextMethod = NULL;
  15687. BfMemberSetEntry* entry = NULL;
  15688. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  15689. nextMethod = (BfMethodDef*)entry->mMemberDef;
  15690. while (nextMethod != NULL)
  15691. {
  15692. auto checkMethod = nextMethod;
  15693. nextMethod = nextMethod->mNextWithSameName;
  15694. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  15695. if (implMethodInst == methodInstance)
  15696. {
  15697. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  15698. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  15699. }
  15700. }
  15701. }
  15702. }
  15703. if (methodDef->mIsOverride)
  15704. {
  15705. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  15706. {
  15707. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  15708. if (ventry.mDeclaringMethod.mMethodNum == -1)
  15709. continue;
  15710. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  15711. if (virtMethod != NULL)
  15712. {
  15713. if (virtMethod == methodInstance)
  15714. {
  15715. // Is matching method
  15716. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  15717. {
  15718. auto baseType = mCurTypeInstance->mBaseType;
  15719. if (baseType != NULL)
  15720. {
  15721. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  15722. baseType = baseType->mBaseType;
  15723. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  15724. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  15725. }
  15726. }
  15727. break;
  15728. }
  15729. }
  15730. }
  15731. }
  15732. }
  15733. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  15734. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15735. {
  15736. if (mBfIRBuilder->mIgnoreWrites)
  15737. return;
  15738. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  15739. if (!methodInstance->mIRFunction)
  15740. {
  15741. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  15742. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  15743. BF_ASSERT(dllImportGlobalVar);
  15744. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  15745. }
  15746. if (HasCompiledOutput())
  15747. {
  15748. BfDllImportEntry dllImportEntry;
  15749. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  15750. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15751. mDllImportEntries.push_back(dllImportEntry);
  15752. }
  15753. return;
  15754. }
  15755. StringT<128> mangledName;
  15756. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15757. if (!methodInstance->mIRFunction)
  15758. {
  15759. bool isIntrinsic = false;
  15760. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  15761. }
  15762. if (methodInstance->mIsIntrinsic)
  15763. return;
  15764. if (mCurTypeInstance->IsFunction())
  15765. return;
  15766. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15767. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  15768. if (methodDef->mBody != NULL)
  15769. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15770. else if (methodDeclaration != NULL)
  15771. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15772. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15773. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  15774. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15775. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15776. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  15777. {
  15778. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  15779. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  15780. {
  15781. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  15782. }
  15783. }
  15784. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  15785. BfMethodState methodState;
  15786. if (mCurMethodState != NULL)
  15787. methodState.mClosureState = mCurMethodState->mClosureState;
  15788. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  15789. {
  15790. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  15791. if (methodInstance->mHotMethod == NULL)
  15792. CheckHotMethod(methodInstance, mangledName);
  15793. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  15794. }
  15795. methodState.mPrevMethodState = mCurMethodState;
  15796. methodState.mMethodInstance = methodInstance;
  15797. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15798. if (methodInstance->GetCustomAttributes() != NULL)
  15799. {
  15800. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  15801. if (typeOptionsIdx != -1)
  15802. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  15803. }
  15804. BfTypeState typeState(mCurTypeInstance);
  15805. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  15806. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  15807. BfMethodInstance* unspecializedMethodInstance = NULL;
  15808. if ((prevMethodState.mPrevVal != NULL) &&
  15809. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  15810. {
  15811. // This is 'inner' (probably a closure) - use binding from outer function
  15812. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  15813. }
  15814. else if ((methodInstance->mIsUnspecialized) ||
  15815. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  15816. {
  15817. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15818. }
  15819. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  15820. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation) && (!methodInstance->mMethodDef->mIsLocalMethod))))
  15821. {
  15822. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  15823. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  15824. {
  15825. // This will have already been populated by CeMachine
  15826. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15827. }
  15828. else
  15829. {
  15830. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  15831. if (!unspecializedMethodInstance->mHasBeenProcessed)
  15832. {
  15833. // Make sure the unspecialized method is processed so we can take its bindings
  15834. // Clear mCurMethodState so we don't think we're in a local method
  15835. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  15836. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  15837. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  15838. mContext->ProcessMethod(unspecializedMethodInstance);
  15839. }
  15840. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15841. }
  15842. }
  15843. if (methodDef->mMethodType == BfMethodType_Operator)
  15844. {
  15845. auto operatorDef = (BfOperatorDef*) methodDef;
  15846. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  15847. auto paramErrorRefNode = refNode;
  15848. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  15849. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  15850. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  15851. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  15852. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  15853. {
  15854. if (methodDef->mParams.size() != 2)
  15855. {
  15856. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  15857. }
  15858. else
  15859. {
  15860. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  15861. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  15862. checkParam0 = checkParam0->GetUnderlyingType();
  15863. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  15864. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  15865. checkParam1 = checkParam1->GetUnderlyingType();
  15866. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  15867. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  15868. {
  15869. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  15870. }
  15871. }
  15872. BfType* wantType = NULL;
  15873. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  15874. {
  15875. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  15876. }
  15877. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  15878. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  15879. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  15880. }
  15881. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  15882. {
  15883. if (methodDef->mIsStatic)
  15884. {
  15885. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  15886. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  15887. checkParam0 = checkParam0->GetUnderlyingType();
  15888. if (methodDef->mParams.size() != 1)
  15889. {
  15890. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  15891. }
  15892. else if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  15893. {
  15894. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  15895. }
  15896. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  15897. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  15898. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  15899. {
  15900. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  15901. }
  15902. }
  15903. else
  15904. {
  15905. if (methodDef->mParams.size() != 0)
  15906. {
  15907. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  15908. }
  15909. if (!mCurMethodInstance->mReturnType->IsVoid())
  15910. {
  15911. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15912. }
  15913. }
  15914. }
  15915. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  15916. {
  15917. if (methodDef->mParams.size() != 1)
  15918. {
  15919. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  15920. }
  15921. if (!mCurMethodInstance->mReturnType->IsVoid())
  15922. {
  15923. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15924. }
  15925. }
  15926. else // Conversion
  15927. {
  15928. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  15929. {
  15930. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  15931. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  15932. }
  15933. if (methodDef->mParams.size() != 1)
  15934. {
  15935. auto refNode = paramErrorRefNode;
  15936. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  15937. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  15938. Fail("Conversion operators must declare one parameter", refNode);
  15939. }
  15940. else
  15941. {
  15942. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  15943. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  15944. checkParam0 = checkParam0->GetUnderlyingType();
  15945. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  15946. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  15947. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  15948. if (checkParam0 == mCurMethodInstance->mReturnType)
  15949. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  15950. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  15951. // happened here
  15952. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  15953. {
  15954. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  15955. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  15956. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  15957. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  15958. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  15959. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  15960. }
  15961. }
  15962. }
  15963. }
  15964. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  15965. if (methodDef->mMethodType == BfMethodType_Mixin)
  15966. wantsDIData = false;
  15967. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  15968. wantsDIData = false;
  15969. bool wantsDIVariables = wantsDIData;
  15970. if (methodDef->mIsExtern)
  15971. wantsDIVariables = false;
  15972. SizedArray<BfIRMDNode, 8> diParams;
  15973. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  15974. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  15975. BfType* thisType = NULL;
  15976. if (!methodDef->mIsStatic)
  15977. {
  15978. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  15979. thisType = methodState.mClosureState->mClosureType;
  15980. else
  15981. thisType = mCurTypeInstance;
  15982. }
  15983. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  15984. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  15985. //////////////////////////////////////////////////////////////////////////
  15986. //
  15987. {
  15988. if (methodDeclaration != NULL)
  15989. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15990. else if (methodDef->mBody != NULL)
  15991. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15992. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15993. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  15994. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15995. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15996. }
  15997. BfIRMDNode diFunction;
  15998. if (wantsDIData)
  15999. {
  16000. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  16001. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  16002. int defLine = mCurFilePosition.mCurLine;
  16003. if (mDICompileUnit)
  16004. {
  16005. int flags = 0;
  16006. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  16007. if (methodDef->mProtection == BfProtection_Public)
  16008. flags = llvm::DINode::FlagPublic;
  16009. else if (methodDef->mProtection == BfProtection_Protected)
  16010. flags = llvm::DINode::FlagProtected;
  16011. else
  16012. flags = llvm::DINode::FlagPrivate;
  16013. if (methodDef->mIsOverride)
  16014. {
  16015. //flags |= llvm::DINode::FlagVirtual;
  16016. }
  16017. else if (methodDef->mIsVirtual)
  16018. flags |= llvm::DINode::FlagIntroducedVirtual;
  16019. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  16020. flags |= llvm::DINode::FlagStaticMember;
  16021. else
  16022. {
  16023. if ((mCurTypeInstance->IsValuelessType()) ||
  16024. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  16025. flags |= llvm::DINode::FlagStaticMember;
  16026. }
  16027. flags |= llvm::DINode::FlagPrototyped;
  16028. if (methodDef->mMethodType == BfMethodType_Ctor)
  16029. {
  16030. flags |= llvm::DINode::FlagArtificial;
  16031. }
  16032. auto llvmFunction = methodInstance->mIRFunction;
  16033. SizedArray<BfIRMDNode, 1> genericArgs;
  16034. SizedArray<BfIRValue, 1> genericConstValueArgs;
  16035. String methodName;
  16036. if (methodInstance->GetForeignType() != NULL)
  16037. {
  16038. methodName += TypeToString(methodInstance->GetForeignType());
  16039. methodName += ".";
  16040. }
  16041. if (methodInstance->GetExplicitInterface() != NULL)
  16042. {
  16043. methodName += TypeToString(methodInstance->GetExplicitInterface());
  16044. methodName += ".";
  16045. }
  16046. methodName += methodDef->mName;
  16047. if (methodInstance->GetNumGenericArguments() != 0)
  16048. {
  16049. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  16050. {
  16051. if (genericArg->IsConstExprValue())
  16052. {
  16053. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  16054. while (genericConstValueArgs.size() < genericArgs.size())
  16055. genericConstValueArgs.push_back(BfIRValue());
  16056. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  16057. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  16058. }
  16059. else
  16060. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  16061. }
  16062. methodName += "<";
  16063. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  16064. {
  16065. if (i > 0)
  16066. methodName += ", ";
  16067. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  16068. methodName += TypeToString(type);
  16069. }
  16070. methodName += ">";
  16071. }
  16072. if ((methodName.empty()) && (methodDeclaration != NULL))
  16073. {
  16074. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16075. {
  16076. methodName += "operator";
  16077. if (operatorDecl->mIsConvOperator)
  16078. {
  16079. methodName += " ";
  16080. methodName += TypeToString(methodInstance->mReturnType);
  16081. }
  16082. else if (operatorDecl->mOpTypeToken != NULL)
  16083. methodName += operatorDecl->mOpTypeToken->ToString();
  16084. }
  16085. }
  16086. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  16087. methodName += "$CHK";
  16088. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  16089. methodName += "$UCHK";
  16090. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  16091. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  16092. // defLine + 1, diFuncType, false, true,
  16093. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  16094. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  16095. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  16096. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  16097. defLine + 1, diFuncType, false, true,
  16098. llvm::dwarf::DW_VIRTUALITY_none,
  16099. 0,
  16100. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  16101. }
  16102. else
  16103. {
  16104. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  16105. }
  16106. }
  16107. //////////////////////////////////////////////////////////////////////////
  16108. // Head and Init get rolled into Entry afterwards.
  16109. methodState.mIRFunction = methodInstance->mIRFunction;
  16110. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  16111. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  16112. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  16113. methodState.mCurScope->mDIScope = diFunction;
  16114. auto llvmEntryBlock = methodState.mIREntryBlock;
  16115. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  16116. if (methodDef->mName == "__MALFORMED")
  16117. {
  16118. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  16119. mBfIRBuilder->SetInsertPoint(newBlock);
  16120. }
  16121. if (methodDef->mBody != NULL)
  16122. {
  16123. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  16124. }
  16125. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  16126. {
  16127. // We want to be able to step into delegate invokes -- we actually step over them
  16128. if (methodDef->mName != "Invoke")
  16129. {
  16130. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  16131. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  16132. }
  16133. }
  16134. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  16135. mBfIRBuilder->ClearDebugLocation();
  16136. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  16137. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  16138. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  16139. {
  16140. int localIdx = 0;
  16141. int argIdx = 0;
  16142. Array<BfIRValue> splatAddrValues;
  16143. for ( ; argIdx < irParamCount; localIdx++)
  16144. {
  16145. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  16146. if ((isThis) && (thisType->IsValuelessType()))
  16147. isThis = false;
  16148. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  16149. {
  16150. argIdx++;
  16151. if (argIdx == irParamCount)
  16152. break;
  16153. }
  16154. BfLocalVariable* paramVar = NULL;
  16155. while (true)
  16156. {
  16157. BF_ASSERT(localIdx < methodState.mLocals.size());
  16158. paramVar = methodState.mLocals[localIdx];
  16159. if ((paramVar->mCompositeCount == -1) &&
  16160. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  16161. break;
  16162. localIdx++;
  16163. }
  16164. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  16165. {
  16166. paramVar->mIsReadOnly = true;
  16167. }
  16168. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  16169. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  16170. if (paramVar->mResolvedType->IsMethodRef())
  16171. wantsAddr = false;
  16172. // if ((methodDef->mHasAppend) && (argIdx == 1))
  16173. // {
  16174. // BF_ASSERT(paramVar->mName == "appendIdx");
  16175. // wantsAddr = true;
  16176. // }
  16177. if (paramVar->mIsSplat)
  16178. {
  16179. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  16180. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  16181. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16182. {
  16183. BfIRType splatIRType;
  16184. if (checkType->IsComposite())
  16185. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  16186. else
  16187. splatIRType = mBfIRBuilder->MapType(checkType);
  16188. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  16189. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  16190. if (!paramVar->mAddr)
  16191. paramVar->mAddr = allocaInst;
  16192. if (WantsLifetimes())
  16193. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  16194. splatAddrValues.push_back(allocaInst);
  16195. }, paramVar->mResolvedType);
  16196. mBfIRBuilder->SetInsertPoint(prevInsert);
  16197. }
  16198. else if (isThis)
  16199. {
  16200. if (wantsAddr)
  16201. {
  16202. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  16203. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  16204. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  16205. if (paramVar->mIsSplat)
  16206. {
  16207. //
  16208. }
  16209. else
  16210. {
  16211. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  16212. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  16213. wantPtr = true;
  16214. if (wantPtr)
  16215. {
  16216. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  16217. }
  16218. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  16219. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  16220. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  16221. paramVar->mAddr = allocaInst;
  16222. if (WantsLifetimes())
  16223. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  16224. }
  16225. mBfIRBuilder->SetInsertPoint(prevInsert);
  16226. }
  16227. }
  16228. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  16229. {
  16230. // Address doesn't change so we don't have to alloca it
  16231. BfIRType allocType;
  16232. int alignSize = mSystem->mPtrSize;
  16233. if (paramVar->mResolvedType->IsRef())
  16234. {
  16235. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  16236. }
  16237. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  16238. {
  16239. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  16240. alignSize = paramVar->mResolvedType->mAlign;
  16241. }
  16242. else
  16243. {
  16244. paramVar->mHasLocalStructBacking = true;
  16245. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  16246. if (typeInst != NULL)
  16247. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  16248. else
  16249. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  16250. }
  16251. if (wantsAddr)
  16252. {
  16253. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  16254. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  16255. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  16256. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  16257. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  16258. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  16259. paramVar->mAddr = allocaInst;
  16260. mBfIRBuilder->SetInsertPoint(prevInsert);
  16261. if (WantsLifetimes())
  16262. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  16263. }
  16264. }
  16265. else if (wantsAddr)
  16266. {
  16267. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  16268. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  16269. paramVar->mAddr = allocaInst;
  16270. }
  16271. if (paramVar->mIsSplat)
  16272. {
  16273. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16274. }
  16275. else if (paramVar->mIsLowered)
  16276. {
  16277. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16278. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16279. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  16280. argIdx++;
  16281. if (loweredTypeCode2 != BfTypeCode_None)
  16282. argIdx++;
  16283. }
  16284. else
  16285. {
  16286. argIdx++;
  16287. }
  16288. }
  16289. if (methodDef->mBody != NULL)
  16290. UpdateSrcPos(methodDef->mBody);
  16291. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  16292. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  16293. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  16294. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  16295. localIdx = 0;
  16296. argIdx = 0;
  16297. int splatAddrIdx = 0;
  16298. while (localIdx < (int)methodState.mLocals.size())
  16299. {
  16300. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16301. argIdx++;
  16302. int curLocalIdx = localIdx++;
  16303. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  16304. if (!paramVar->IsParam())
  16305. continue;
  16306. if (paramVar->mCompositeCount != -1)
  16307. continue;
  16308. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  16309. if ((isThis) && (thisType->IsValuelessType()))
  16310. isThis = false;
  16311. if (paramVar->mValue.IsArg())
  16312. BF_ASSERT(paramVar->mValue.mId == argIdx);
  16313. BfIRMDNode diVariable;
  16314. if (wantsDIData)
  16315. {
  16316. String paramName = paramVar->mName;
  16317. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  16318. if (isThis)
  16319. {
  16320. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  16321. paramName = "__closure";
  16322. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  16323. {
  16324. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  16325. bool wantRef = paramVar->mResolvedType->IsComposite();
  16326. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  16327. wantRef = true;
  16328. if (wantRef)
  16329. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  16330. }
  16331. else if (!paramVar->mResolvedType->IsValueType())
  16332. {
  16333. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16334. }
  16335. }
  16336. else
  16337. {
  16338. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  16339. {
  16340. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  16341. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  16342. diType = mBfIRBuilder->DbgCreateConstType(diType);
  16343. }
  16344. }
  16345. if (!paramVar->mIsSplat)
  16346. {
  16347. if (paramVar->mResolvedType->IsValuelessType())
  16348. {
  16349. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  16350. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  16351. }
  16352. else if (paramVar->mIsImplicitParam)
  16353. {
  16354. // Annotate this specially?
  16355. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  16356. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  16357. }
  16358. else
  16359. {
  16360. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  16361. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  16362. }
  16363. paramVar->mDbgVarInst = diVariable;
  16364. }
  16365. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  16366. {
  16367. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  16368. // {
  16369. // // Only add this placeholder if we don't have any values
  16370. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16371. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  16372. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  16373. // }
  16374. }
  16375. }
  16376. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  16377. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  16378. {
  16379. // Write our argument value into the .addr
  16380. mBfIRBuilder->ClearDebugLocation();
  16381. if (paramVar->mIsSplat)
  16382. {
  16383. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  16384. //
  16385. }
  16386. else
  16387. {
  16388. bool handled = false;
  16389. if (paramVar->mIsLowered)
  16390. {
  16391. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16392. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16393. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  16394. {
  16395. // We have a lowered type coming in, so we have to cast the .addr before storing
  16396. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  16397. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  16398. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  16399. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  16400. if (loweredTypeCode2 != BfTypeCode_None)
  16401. {
  16402. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  16403. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  16404. BfIRValue primPtrVal2;
  16405. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  16406. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  16407. else
  16408. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  16409. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  16410. }
  16411. // We don't want to allow directly using value
  16412. paramVar->mValue = BfIRValue();
  16413. handled = true;
  16414. }
  16415. else
  16416. {
  16417. BF_ASSERT("Expected lowered");
  16418. }
  16419. }
  16420. if (!handled)
  16421. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  16422. }
  16423. }
  16424. if (methodDef->mBody != NULL)
  16425. UpdateSrcPos(methodDef->mBody);
  16426. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  16427. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  16428. else if (methodDeclaration == NULL)
  16429. UseDefaultSrcPos();
  16430. // Write our argument value into the .addr
  16431. if (paramVar->mIsSplat)
  16432. {
  16433. int splatComponentIdx = 0;
  16434. auto curArgIdx = argIdx;
  16435. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  16436. {
  16437. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  16438. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  16439. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  16440. mBfIRBuilder->ClearDebugLocation(storeInst);
  16441. if (wantsDIData)
  16442. {
  16443. BfIRMDNode diType;
  16444. if (checkType->IsComposite())
  16445. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  16446. else
  16447. diType = mBfIRBuilder->DbgGetType(checkType);
  16448. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  16449. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  16450. if (wantsDIVariables)
  16451. {
  16452. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  16453. }
  16454. }
  16455. curArgIdx++;
  16456. splatComponentIdx++;
  16457. };
  16458. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  16459. {
  16460. if (checkType->IsStruct())
  16461. {
  16462. auto checkTypeInstance = checkType->ToTypeInstance();
  16463. if (checkTypeInstance->mBaseType != NULL)
  16464. {
  16465. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  16466. }
  16467. if (checkTypeInstance->mIsUnion)
  16468. {
  16469. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  16470. if (!unionInnerType->IsValuelessType())
  16471. {
  16472. _FinishSplatsIterate(unionInnerType, name + "$u");
  16473. }
  16474. if (checkTypeInstance->IsEnum())
  16475. {
  16476. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  16477. _FinishSplatsIterate(dscrType, name + "$d");
  16478. }
  16479. }
  16480. else
  16481. {
  16482. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16483. {
  16484. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16485. auto fieldDef = fieldInstance->GetFieldDef();
  16486. if (fieldInstance->mDataIdx >= 0)
  16487. {
  16488. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  16489. }
  16490. }
  16491. }
  16492. }
  16493. else if (checkType->IsMethodRef())
  16494. {
  16495. auto methodRefType = (BfMethodRefType*)checkType;
  16496. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  16497. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  16498. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  16499. // {
  16500. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  16501. // if (!paramType->IsValuelessType())
  16502. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  16503. // }
  16504. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  16505. {
  16506. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  16507. String paramName = methodInstance->GetParamName(paramIdx);
  16508. if (paramName == "this")
  16509. paramName = "__this";
  16510. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  16511. {
  16512. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  16513. }
  16514. else
  16515. {
  16516. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  16517. }
  16518. }
  16519. }
  16520. else if (!checkType->IsValuelessType())
  16521. {
  16522. _FinishSplats(checkType, name);
  16523. }
  16524. };
  16525. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  16526. if (!paramVar->mConstValue)
  16527. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  16528. }
  16529. BfIRValue declareCall;
  16530. if (diVariable)
  16531. {
  16532. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  16533. {
  16534. if (!paramVar->mAddr)
  16535. {
  16536. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  16537. {
  16538. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  16539. {
  16540. // We don't need to set the location for this
  16541. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  16542. }
  16543. }
  16544. else
  16545. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  16546. }
  16547. else
  16548. {
  16549. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  16550. }
  16551. }
  16552. }
  16553. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  16554. {
  16555. // We don't allow actually assignment to "this", so we just do a single load
  16556. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  16557. // we need to store it in the stack frame for debugging purposes
  16558. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  16559. mBfIRBuilder->ClearDebugLocation(loadedThis);
  16560. paramVar->mValue = loadedThis;
  16561. }
  16562. if ((wantsDIData) && (declareCall))
  16563. mBfIRBuilder->UpdateDebugLocation(declareCall);
  16564. if (paramVar->mIsSplat)
  16565. {
  16566. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16567. }
  16568. else if (paramVar->mIsLowered)
  16569. {
  16570. argIdx++;
  16571. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16572. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16573. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  16574. if (loweredTypeCode2 != BfTypeCode_None)
  16575. argIdx++;
  16576. }
  16577. else if (!paramVar->mResolvedType->IsValuelessType())
  16578. {
  16579. argIdx++;
  16580. }
  16581. }
  16582. if (wantsDIData)
  16583. {
  16584. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  16585. }
  16586. }
  16587. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  16588. {
  16589. auto paramVar = mCurMethodState->mLocals[varIdx];
  16590. // 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
  16591. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  16592. // if (paramVar->mIsSplat)
  16593. // {
  16594. // if (wantsDIVariables)
  16595. // {
  16596. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  16597. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  16598. // }
  16599. // }
  16600. if (paramVar->mResolvedType->IsValuelessType())
  16601. {
  16602. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  16603. {
  16604. // Only add this placeholder if we don't have any values
  16605. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  16606. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  16607. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  16608. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  16609. }
  16610. }
  16611. }
  16612. if (IsTargetingBeefBackend())
  16613. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  16614. if (methodState.mClosureState != NULL)
  16615. {
  16616. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  16617. {
  16618. BfLocalVariable* localVar = new BfLocalVariable();
  16619. *localVar = constLocal;
  16620. AddLocalVariableDef(localVar, true);
  16621. }
  16622. }
  16623. bool wantsRemoveBody = false;
  16624. bool skipBody = false;
  16625. bool skipUpdateSrcPos = false;
  16626. bool skipEndChecks = false;
  16627. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  16628. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16629. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  16630. hasExternSpecifier = true;
  16631. // Allocate, clear, set classVData
  16632. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  16633. {
  16634. CreateStaticCtor();
  16635. }
  16636. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  16637. {
  16638. skipBody = true;
  16639. skipEndChecks = true;
  16640. if ((HasCompiledOutput()) || (mIsComptimeModule))
  16641. {
  16642. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  16643. mBfIRBuilder->ClearDebugLocation();
  16644. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  16645. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  16646. PopulateType(innerType, BfPopulateType_DataAndMethods);
  16647. mBfIRBuilder->PopulateType(mCurTypeInstance);
  16648. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16649. if (methodInstance->mIsForeignMethodDef)
  16650. {
  16651. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  16652. }
  16653. BfTypeVector methodGenericArguments;
  16654. if (methodInstance->mMethodInfoEx != NULL)
  16655. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  16656. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  16657. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  16658. {
  16659. if (!methodInstance->mReturnType->IsValuelessType())
  16660. {
  16661. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  16662. CreateReturn(retVal);
  16663. }
  16664. else
  16665. mBfIRBuilder->CreateRetVoid();
  16666. }
  16667. else
  16668. {
  16669. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  16670. SizedArray<BfIRValue, 8> innerParams;
  16671. BfExprEvaluator exprEvaluator(this);
  16672. if (!innerType->IsValuelessType())
  16673. {
  16674. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  16675. BfTypedValue innerVal(thisValue, innerType, true);
  16676. if (boxedType->IsBoxedStructPtr())
  16677. {
  16678. innerVal = LoadValue(innerVal);
  16679. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  16680. }
  16681. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  16682. }
  16683. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  16684. {
  16685. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  16686. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  16687. exprEvaluator.PushArg(localVal, innerParams);
  16688. }
  16689. if (!innerMethodInstance.mFunc)
  16690. {
  16691. BF_ASSERT(innerType->IsUnspecializedType());
  16692. }
  16693. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  16694. {
  16695. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  16696. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  16697. exprEvaluator.mReceivingValue = &returnType;
  16698. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  16699. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  16700. mBfIRBuilder->CreateRetVoid();
  16701. }
  16702. else
  16703. {
  16704. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  16705. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  16706. if (mCurMethodInstance->mReturnType->IsValueType())
  16707. retVal = LoadValue(retVal);
  16708. CreateReturn(retVal.mValue);
  16709. }
  16710. }
  16711. }
  16712. mCurMethodState->SetHadReturn(true);
  16713. mCurMethodState->mLeftBlockUncond = true;
  16714. }
  16715. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  16716. {
  16717. SetIllegalSrcPos();
  16718. mBfIRBuilder->ClearDebugLocation();
  16719. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  16720. auto thisVal = GetThis();
  16721. int prevSize = mContext->mBfObjectType->mInstSize;
  16722. int curSize = mCurTypeInstance->mInstSize;
  16723. if (curSize > prevSize)
  16724. {
  16725. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  16726. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  16727. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  16728. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  16729. }
  16730. skipUpdateSrcPos = true;
  16731. }
  16732. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  16733. {
  16734. EmitCtorBody(skipBody);
  16735. }
  16736. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  16737. {
  16738. EmitDtorBody();
  16739. skipBody = true;
  16740. }
  16741. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  16742. {
  16743. EmitIteratorBlock(skipBody);
  16744. }
  16745. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  16746. {
  16747. // We need to be able to mark deleted objects
  16748. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16749. }
  16750. auto customAttributes = methodInstance->GetCustomAttributes();
  16751. if (customAttributes != NULL)
  16752. {
  16753. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  16754. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16755. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  16756. mCurMethodState->mDisableChecks = true;
  16757. }
  16758. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  16759. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  16760. {
  16761. // We chain even non-default ctors to the default ctors
  16762. auto defaultCtor = methodInstance;
  16763. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  16764. CallChainedMethods(defaultCtor, false);
  16765. }
  16766. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  16767. if (methodDef->mBody == NULL)
  16768. {
  16769. if (methodDeclaration != NULL)
  16770. {
  16771. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16772. {
  16773. if (operatorDeclaration->mIsConvOperator)
  16774. wantsRemoveBody = true;
  16775. }
  16776. }
  16777. bool isDllImport = false;
  16778. if (methodInstance->GetImportKind() == BfImportKind_Import_Static)
  16779. {
  16780. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  16781. {
  16782. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  16783. {
  16784. if (customAttr.mCtorArgs.size() == 1)
  16785. {
  16786. auto fileNameArg = customAttr.mCtorArgs[0];
  16787. int strNum = 0;
  16788. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  16789. if (constant != NULL)
  16790. {
  16791. if (constant->IsNull())
  16792. continue; // Invalid
  16793. strNum = constant->mInt32;
  16794. }
  16795. else
  16796. {
  16797. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  16798. }
  16799. if (!mImportFileNames.Contains(strNum))
  16800. mImportFileNames.Add(strNum);
  16801. }
  16802. }
  16803. }
  16804. //mImportFileNames
  16805. }
  16806. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  16807. {
  16808. CreateDllImportMethod();
  16809. }
  16810. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  16811. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  16812. {
  16813. if (mCurTypeInstance->mTypeDef->mIsFunction)
  16814. {
  16815. // Emit nothing
  16816. }
  16817. else
  16818. {
  16819. CreateDelegateInvokeMethod();
  16820. mCurMethodState->SetHadReturn(true);
  16821. mCurMethodState->mLeftBlockUncond = true;
  16822. }
  16823. }
  16824. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  16825. {
  16826. if (mCurTypeInstance->IsObject())
  16827. {
  16828. CreateDynamicCastMethod();
  16829. }
  16830. else
  16831. {
  16832. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  16833. mCurMethodState->mHadReturn = true;
  16834. }
  16835. }
  16836. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16837. {
  16838. BfIRValue ret;
  16839. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  16840. {
  16841. // This can happen if we provide an invalid name
  16842. AssertErrorState();
  16843. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  16844. }
  16845. else
  16846. {
  16847. // Unfortunate DebugLoc shenanigans-
  16848. // 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,
  16849. // so we only set the loc on the CreateRet which gets inlined out
  16850. mBfIRBuilder->SaveDebugLocation();
  16851. mBfIRBuilder->ClearDebugLocation();
  16852. BfIRValue fromBool;
  16853. if (!mCurTypeInstance->IsTypedPrimitive())
  16854. {
  16855. fromBool = GetDefaultValue(methodInstance->mReturnType);
  16856. }
  16857. else
  16858. {
  16859. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  16860. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  16861. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  16862. }
  16863. mBfIRBuilder->RestoreDebugLocation();
  16864. ret = mBfIRBuilder->CreateRet(fromBool);
  16865. //ExtendLocalLifetimes(0);
  16866. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16867. }
  16868. mCurMethodState->SetHadReturn(true);
  16869. mCurMethodState->mLeftBlockUncond = true;
  16870. }
  16871. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  16872. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16873. {
  16874. BfIRValue ret;
  16875. // Unfortunate DebugLoc shenanigans-
  16876. // 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,
  16877. // so we only set the loc on the CreateRet which gets inlined out
  16878. mBfIRBuilder->SaveDebugLocation();
  16879. mBfIRBuilder->ClearDebugLocation();
  16880. BfIRValue fromBool;
  16881. mBfIRBuilder->RestoreDebugLocation();
  16882. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  16883. //ExtendLocalLifetimes(0);
  16884. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16885. mCurMethodState->SetHadReturn(true);
  16886. mCurMethodState->mLeftBlockUncond = true;
  16887. }
  16888. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16889. {
  16890. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16891. if ((HasCompiledOutput()) || (mIsComptimeModule))
  16892. {
  16893. EmitEnumToStringBody();
  16894. }
  16895. mBfIRBuilder->CreateRetVoid();
  16896. mCurMethodState->SetHadReturn(true);
  16897. mCurMethodState->mLeftBlockUncond = true;
  16898. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16899. }
  16900. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16901. {
  16902. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16903. if ((HasCompiledOutput()) || (mIsComptimeModule))
  16904. {
  16905. EmitTupleToStringBody();
  16906. }
  16907. mBfIRBuilder->CreateRetVoid();
  16908. mCurMethodState->SetHadReturn(true);
  16909. mCurMethodState->mLeftBlockUncond = true;
  16910. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16911. }
  16912. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  16913. {
  16914. CreateValueTypeEqualsMethod(false);
  16915. skipBody = true;
  16916. skipEndChecks = true;
  16917. }
  16918. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  16919. {
  16920. CreateValueTypeEqualsMethod(true);
  16921. skipBody = true;
  16922. skipEndChecks = true;
  16923. }
  16924. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  16925. {
  16926. CreateValueTypeEqualsMethod(false);
  16927. skipBody = true;
  16928. skipEndChecks = true;
  16929. }
  16930. else
  16931. {
  16932. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16933. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  16934. {
  16935. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  16936. Fail("Body expected", methodDef->mBody);
  16937. }
  16938. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16939. {
  16940. if (methodInstance->mReturnType->IsValuelessType())
  16941. {
  16942. mBfIRBuilder->CreateRetVoid();
  16943. }
  16944. else if ((HasCompiledOutput()) || (mIsComptimeModule))
  16945. {
  16946. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16947. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16948. BfFieldDef* fieldDef = NULL;
  16949. if (fieldInstance != NULL)
  16950. fieldDef = fieldInstance->GetFieldDef();
  16951. BfType* retType = methodInstance->mReturnType;
  16952. if (retType->IsRef())
  16953. retType = retType->GetUnderlyingType();
  16954. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  16955. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16956. {
  16957. BfTypedValue lookupValue;
  16958. if (fieldDef->IsNonConstStatic())
  16959. lookupValue = ReferenceStaticField(fieldInstance);
  16960. else if (mCurTypeInstance->IsObject())
  16961. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  16962. else
  16963. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  16964. if (!methodInstance->mReturnType->IsRef())
  16965. lookupValue = LoadOrAggregateValue(lookupValue);
  16966. CreateReturn(lookupValue.mValue);
  16967. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16968. }
  16969. else
  16970. {
  16971. // This can happen if we have two properties with the same name but different types
  16972. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16973. EmitDefaultReturn();
  16974. }
  16975. }
  16976. else
  16977. {
  16978. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16979. EmitDefaultReturn();
  16980. }
  16981. mCurMethodState->SetHadReturn(true);
  16982. }
  16983. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  16984. {
  16985. if ((!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  16986. {
  16987. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  16988. }
  16989. else if (!mCompiler->IsAutocomplete())
  16990. {
  16991. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16992. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16993. auto fieldDef = fieldInstance->GetFieldDef();
  16994. auto& lastParam = mCurMethodState->mLocals.back();
  16995. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  16996. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16997. {
  16998. BfIRValue lookupAddr;
  16999. if (fieldDef->IsNonConstStatic())
  17000. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  17001. else
  17002. {
  17003. auto thisValue = GetThis();
  17004. if (thisValue.IsSplat())
  17005. {
  17006. BFMODULE_FATAL(this, "Should not happen");
  17007. }
  17008. if (mCurTypeInstance->IsObject())
  17009. thisValue = LoadValue(thisValue);
  17010. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  17011. }
  17012. BfExprEvaluator exprEvaluator(this);
  17013. auto localVal = exprEvaluator.LoadLocal(lastParam);
  17014. localVal = LoadOrAggregateValue(localVal);
  17015. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  17016. }
  17017. else if (!fieldInstance->mResolvedType->IsValuelessType())
  17018. {
  17019. // This can happen if we have two properties with the same name but different types
  17020. AssertErrorState();
  17021. }
  17022. }
  17023. }
  17024. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  17025. {
  17026. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  17027. {
  17028. if (HasCompiledOutput())
  17029. EmitGCMarkMembers();
  17030. }
  17031. else if (!mCurTypeInstance->IsObject())
  17032. {
  17033. }
  17034. }
  17035. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  17036. {
  17037. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  17038. {
  17039. if (HasCompiledOutput())
  17040. EmitGCFindTLSMembers();
  17041. }
  17042. }
  17043. }
  17044. }
  17045. else if (!skipBody)
  17046. {
  17047. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  17048. bool wantsRetVal = true;
  17049. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  17050. wantsRetVal = false;
  17051. else if (mCurMethodInstance->mReturnType->IsVar())
  17052. wantsRetVal = false;
  17053. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  17054. {
  17055. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  17056. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  17057. {
  17058. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  17059. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  17060. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  17061. mBfIRBuilder->ClearDebugLocation(storeInst);
  17062. mCurMethodState->mRetValAddr = allocaInst;
  17063. }
  17064. else if (wantsRetVal)
  17065. {
  17066. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  17067. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  17068. }
  17069. }
  17070. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  17071. {
  17072. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  17073. BfGetSymbolReferenceKind prevSymbolKind;
  17074. BfAutoComplete* prevAutoComplete;
  17075. if (mCompiler->mResolvePassData != NULL)
  17076. {
  17077. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  17078. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17079. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  17080. }
  17081. EmitCtorCalcAppend();
  17082. if (mCompiler->mResolvePassData != NULL)
  17083. {
  17084. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  17085. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  17086. }
  17087. }
  17088. else if (!isEmptyBodied)
  17089. {
  17090. if (!mCurMethodState->mIRExitBlock)
  17091. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  17092. bool isExpressionBody = false;
  17093. if (methodDeclaration != NULL)
  17094. {
  17095. if (methodDeclaration->mFatArrowToken != NULL)
  17096. isExpressionBody = true;
  17097. }
  17098. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17099. {
  17100. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17101. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  17102. isExpressionBody = true;
  17103. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  17104. {
  17105. isExpressionBody = true;
  17106. }
  17107. }
  17108. else
  17109. {
  17110. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  17111. {
  17112. if (!block->mChildArr.IsEmpty())
  17113. {
  17114. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  17115. {
  17116. if (exprStmt->mTrailingSemicolon == NULL)
  17117. isExpressionBody = true;
  17118. }
  17119. }
  17120. }
  17121. else
  17122. isExpressionBody = true;
  17123. }
  17124. DoCEEmit(methodInstance);
  17125. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  17126. {
  17127. while (fieldDtorBody != NULL)
  17128. {
  17129. VisitEmbeddedStatement(fieldDtorBody->mBody);
  17130. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  17131. }
  17132. }
  17133. else if (!isExpressionBody)
  17134. {
  17135. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  17136. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  17137. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  17138. VisitCodeBlock(bodyBlock);
  17139. }
  17140. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  17141. {
  17142. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  17143. // {
  17144. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  17145. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  17146. // }
  17147. auto expectingType = mCurMethodInstance->mReturnType;
  17148. // What was this error for?
  17149. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  17150. // {
  17151. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  17152. // }
  17153. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_AllowRefExpr;
  17154. if (expectingType->IsVoid())
  17155. {
  17156. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  17157. bool wasReturnGenericParam = false;
  17158. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  17159. {
  17160. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  17161. }
  17162. else
  17163. {
  17164. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  17165. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  17166. wasReturnGenericParam = true;
  17167. }
  17168. // If we the void return was from a generic specialization, allow us to return a void result,
  17169. // otherwise treat expression as though it must be a statement
  17170. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  17171. if (isStatement)
  17172. expectingType = NULL;
  17173. }
  17174. UpdateSrcPos(expressionBody);
  17175. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  17176. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  17177. {
  17178. mCurMethodState->mHadReturn = true;
  17179. retVal = LoadOrAggregateValue(retVal);
  17180. EmitReturn(retVal);
  17181. }
  17182. }
  17183. }
  17184. }
  17185. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  17186. if (skipUpdateSrcPos)
  17187. {
  17188. // Skip
  17189. }
  17190. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  17191. UpdateSrcPos(bodyBlock->mCloseBrace);
  17192. else if (methodDef->mBody != NULL)
  17193. UpdateSrcPos(methodDef->mBody);
  17194. else if (methodDeclaration != NULL)
  17195. UpdateSrcPos(methodDeclaration);
  17196. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  17197. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  17198. else
  17199. UseDefaultSrcPos();
  17200. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  17201. {
  17202. if (mCurMethodState->mRetVal)
  17203. {
  17204. mCurMethodState->SetHadReturn(true);
  17205. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  17206. mBfIRBuilder->CreateRet(retVal);
  17207. }
  17208. else
  17209. AssertErrorState();
  17210. }
  17211. if (!mCurMethodState->mHadReturn)
  17212. {
  17213. // Clear off the stackallocs that have occurred after a scopeData break
  17214. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  17215. }
  17216. if (mCurMethodState->mIRExitBlock)
  17217. {
  17218. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  17219. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  17220. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  17221. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  17222. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  17223. CreateDIRetVal();
  17224. }
  17225. for (auto localVar : mCurMethodState->mLocals)
  17226. {
  17227. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  17228. {
  17229. //
  17230. }
  17231. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  17232. break;
  17233. LocalVariableDone(localVar, true);
  17234. }
  17235. if (mCurMethodState->mIRExitBlock)
  17236. {
  17237. if ((mCurMethodState->mRetVal) &&
  17238. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  17239. {
  17240. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  17241. CreateReturn(loadedVal);
  17242. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17243. if (mCurMethodState->mDIRetVal)
  17244. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  17245. }
  17246. else
  17247. {
  17248. // Have something on the last line to step onto
  17249. if (mHasFullDebugInfo)
  17250. {
  17251. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  17252. UpdateSrcPos(bodyBlock->mCloseBrace);
  17253. EmitEnsureInstructionAt();
  17254. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  17255. {
  17256. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  17257. mBfIRBuilder->EnsureFunctionPatchable();
  17258. }
  17259. }
  17260. mBfIRBuilder->CreateRetVoid();
  17261. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  17262. if (mCurMethodState->mDIRetVal)
  17263. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  17264. }
  17265. }
  17266. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  17267. {
  17268. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  17269. {
  17270. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  17271. {
  17272. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  17273. mBfIRBuilder->EnsureFunctionPatchable();
  17274. }
  17275. mBfIRBuilder->CreateRetVoid();
  17276. }
  17277. }
  17278. else
  17279. {
  17280. if (!mCurMethodState->mHadReturn)
  17281. {
  17282. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  17283. if (bodyBlock != NULL)
  17284. {
  17285. if (bodyBlock->mCloseBrace != NULL)
  17286. {
  17287. BfAstNode* target = bodyBlock->mCloseBrace;
  17288. Fail("Method must return value", target);
  17289. }
  17290. else
  17291. {
  17292. // It's possible to not have a closing brace if the method ends in an EOF
  17293. AssertErrorState();
  17294. }
  17295. }
  17296. }
  17297. }
  17298. // Move 'init' into 'entry'
  17299. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  17300. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  17301. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  17302. {
  17303. // Don't keep instructions for unspecialized types
  17304. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  17305. }
  17306. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  17307. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17308. wantsRemoveBody = true;*/
  17309. if ((hasExternSpecifier) && (!skipBody))
  17310. {
  17311. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  17312. // incase it gets called later by some hot-loaded coded
  17313. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  17314. {
  17315. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  17316. CreateFakeCallerMethod(mangledName);
  17317. }
  17318. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  17319. }
  17320. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  17321. {
  17322. // We only need the DLL stub when we may be hot swapping
  17323. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  17324. }
  17325. else if (wantsRemoveBody)
  17326. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  17327. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  17328. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  17329. // unspecialized types
  17330. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  17331. {
  17332. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  17333. methodInstance->mIRFunction = BfIRFunction();
  17334. }
  17335. CheckAddFailType();
  17336. if (mHadBuildError)
  17337. prevHadBuildError.CancelRestore();
  17338. if (mHadBuildWarning)
  17339. prevHadWarning.CancelRestore();
  17340. if (!methodDef->mIsLocalMethod)
  17341. ProcessMethod_ProcessDeferredLocals();
  17342. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  17343. if (methodState.mHotDataReferenceBuilder != NULL)
  17344. {
  17345. AddHotDataReferences(&hotDataReferenceBuilder);
  17346. }
  17347. else
  17348. {
  17349. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  17350. {
  17351. // Remove the hot method data
  17352. auto hotMethod = methodInstance->mHotMethod;
  17353. auto prevMethod = hotMethod->mPrevVersion;
  17354. if (prevMethod != NULL)
  17355. {
  17356. // If there's a prev method then pull its data into the main HotMethod.
  17357. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  17358. // over to the main HotMethod definition to keep the HotMethod address
  17359. // invariant
  17360. for (auto ref : hotMethod->mReferences)
  17361. ref->Deref();
  17362. hotMethod->mReferences.Clear();
  17363. BF_ASSERT(prevMethod->mRefCount == 1);
  17364. hotMethod->mReferences = prevMethod->mReferences;
  17365. if (hotMethod->mSrcTypeVersion != NULL)
  17366. hotMethod->mSrcTypeVersion->Deref();
  17367. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  17368. prevMethod->mSrcTypeVersion = NULL;
  17369. prevMethod->mReferences.Clear();
  17370. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  17371. prevMethod->mPrevVersion = NULL;
  17372. prevMethod->Deref();
  17373. }
  17374. hotMethod->Deref();
  17375. methodInstance->mHotMethod = NULL;
  17376. }
  17377. }
  17378. }
  17379. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  17380. {
  17381. String name;
  17382. bool found = false;
  17383. auto checkMethodState = mCurMethodState;
  17384. while (checkMethodState != NULL)
  17385. {
  17386. if (checkMethodState->mClosureState == NULL)
  17387. break;
  17388. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  17389. {
  17390. found = true;
  17391. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  17392. break;
  17393. }
  17394. checkMethodState = checkMethodState->mPrevMethodState;
  17395. }
  17396. if (!found)
  17397. name += mCurMethodInstance->mMethodDef->mName;
  17398. int prevSepPos = (int)name.LastIndexOf('$');
  17399. if (prevSepPos != -1)
  17400. {
  17401. name.RemoveToEnd(prevSepPos);
  17402. }
  17403. name += "@";
  17404. name += baseName;
  17405. HashContext hashCtx;
  17406. if (anchorNode != NULL)
  17407. {
  17408. hashCtx.Mixin(anchorNode->GetStartCharId());
  17409. }
  17410. //
  17411. {
  17412. auto checkMethodState = declMethodState;
  17413. auto checkMixinState = declMixinState;
  17414. while (checkMethodState != NULL)
  17415. {
  17416. if (checkMixinState != NULL)
  17417. {
  17418. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  17419. }
  17420. checkMethodState = checkMethodState->mPrevMethodState;
  17421. if (checkMethodState != NULL)
  17422. checkMixinState = checkMethodState->mMixinState;
  17423. }
  17424. }
  17425. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17426. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  17427. {
  17428. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  17429. {
  17430. StringT<128> genericTypeName;
  17431. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  17432. hashCtx.MixinStr(genericTypeName);
  17433. }
  17434. }
  17435. uint64 hashVal = hashCtx.Finish64();
  17436. name += "$";
  17437. name += BfTypeUtils::HashEncode64(hashVal);
  17438. return name;
  17439. }
  17440. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  17441. {
  17442. if (localMethod->mMethodDef != NULL)
  17443. return localMethod->mMethodDef;
  17444. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17445. auto declMethodState = localMethod->mDeclMethodState;
  17446. auto declMixinState = localMethod->mDeclMixinState;
  17447. auto typeInst = mCurTypeInstance;
  17448. BfAstNode* body = NULL;
  17449. BfAstNode* anchorNode = NULL;
  17450. auto _AllocDirectTypeRef = [&](BfType* type)
  17451. {
  17452. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  17453. directTypeRef->Init(type);
  17454. return directTypeRef;
  17455. };
  17456. auto methodDeclaration = localMethod->mMethodDeclaration;
  17457. if (methodDeclaration != NULL)
  17458. {
  17459. body = methodDeclaration->mBody;
  17460. anchorNode = methodDeclaration->mOpenParen;
  17461. }
  17462. else
  17463. {
  17464. body = localMethod->mLambdaBindExpr->mBody;
  17465. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  17466. }
  17467. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  17468. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  17469. BfMethodDef* methodDef;
  17470. BfMethodDef* outerMethodDef = NULL;
  17471. if (localMethod->mOuterLocalMethod != NULL)
  17472. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  17473. else
  17474. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  17475. if (methodDeclaration != NULL)
  17476. {
  17477. BfDefBuilder defBuilder(mCompiler->mSystem);
  17478. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  17479. defBuilder.mPassInstance = mCompiler->mPassInstance;
  17480. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  17481. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  17482. }
  17483. else
  17484. {
  17485. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  17486. methodDef = new BfMethodDef();
  17487. methodDef->mName = localMethod->mMethodName;
  17488. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  17489. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  17490. methodDef->mBody = body;
  17491. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  17492. {
  17493. auto paramType = invokeMethod->GetParamType(paramIdx);
  17494. String paramName;
  17495. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  17496. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  17497. else
  17498. paramName = invokeMethod->GetParamName(paramIdx);
  17499. auto paramDef = new BfParameterDef();
  17500. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  17501. paramDef->mName = paramName;
  17502. methodDef->mParams.Add(paramDef);
  17503. }
  17504. if (outerMethodDef != NULL)
  17505. {
  17506. for (auto genericParam : outerMethodDef->mGenericParams)
  17507. {
  17508. auto* copiedGenericParamDef = new BfGenericParamDef();
  17509. *copiedGenericParamDef = *genericParam;
  17510. methodDef->mGenericParams.Add(copiedGenericParamDef);
  17511. }
  17512. }
  17513. }
  17514. methodDef->mIdx = ~methodLocalIdx;
  17515. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  17516. methodDef->mName = localMethod->mExpectedFullName;
  17517. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  17518. //
  17519. // if (!localMethod->mExpectedFullName.IsEmpty())
  17520. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  17521. methodDef->mIsStatic = true;
  17522. methodDef->mIsLocalMethod = true;
  17523. methodDef->mIsVirtual = false;
  17524. localMethod->mMethodDef = methodDef;
  17525. auto methodInstanceGroup = new BfMethodInstanceGroup();
  17526. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  17527. methodInstanceGroup->mMethodIdx = -1;
  17528. methodInstanceGroup->mOwner = mCurTypeInstance;
  17529. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  17530. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  17531. {
  17532. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  17533. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  17534. }
  17535. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  17536. {
  17537. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  17538. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17539. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  17540. {
  17541. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  17542. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  17543. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  17544. autoComplete->mDefType = typeInst->mTypeDef;
  17545. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  17546. autoComplete->mReplaceLocalId = methodLocalIdx;
  17547. }
  17548. }
  17549. return localMethod->mMethodDef;
  17550. }
  17551. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  17552. {
  17553. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  17554. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  17555. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17556. auto declMethodState = localMethod->mDeclMethodState;
  17557. auto declMixinState = localMethod->mDeclMixinState;
  17558. auto callerMethodState = mCurMethodState;
  17559. auto typeInst = mCurTypeInstance;
  17560. if (mCurMethodState->mMixinState != NULL)
  17561. {
  17562. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  17563. }
  17564. auto methodDef = GetLocalMethodDef(localMethod);
  17565. BfAstNode* body = NULL;
  17566. auto methodDeclaration = localMethod->mMethodDeclaration;
  17567. if (methodDeclaration != NULL)
  17568. {
  17569. body = methodDeclaration->mBody;
  17570. }
  17571. else
  17572. {
  17573. body = localMethod->mLambdaBindExpr->mBody;
  17574. }
  17575. bool hadConcreteInterfaceGenericArgument = false;
  17576. BfTypeVector sanitizedMethodGenericArguments;
  17577. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  17578. // version of this method for this pass through the outermost method
  17579. int dependentGenericStartIdx = 0;
  17580. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  17581. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  17582. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  17583. if (methodGenericArguments.size() == 0)
  17584. {
  17585. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  17586. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  17587. }
  17588. else
  17589. {
  17590. int genericArgIdx = 0;
  17591. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  17592. // {
  17593. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  17594. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  17595. // }
  17596. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  17597. {
  17598. auto genericArgType = methodGenericArguments[genericArgIdx];
  17599. BF_ASSERT(!genericArgType->IsRef());
  17600. if (genericArgType->IsConcreteInterfaceType())
  17601. {
  17602. hadConcreteInterfaceGenericArgument = true;
  17603. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  17604. genericArgType = concreteInterfaceType->mInterface;
  17605. }
  17606. sanitizedMethodGenericArguments.push_back(genericArgType);
  17607. }
  17608. }
  17609. bool wantPrematureMethodInstance = false;
  17610. if (!force)
  17611. {
  17612. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  17613. }
  17614. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  17615. bool isDefaultPass = true;
  17616. BfTypeVector lookupMethodGenericArguments;
  17617. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  17618. {
  17619. auto genericArgType = methodGenericArguments[genericArgIdx];
  17620. BF_ASSERT(!genericArgType->IsRef());
  17621. lookupMethodGenericArguments.Add(genericArgType);
  17622. if (genericArgType->IsGenericParam())
  17623. {
  17624. auto genericParam = (BfGenericParamType*)genericArgType;
  17625. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  17626. isDefaultPass = false;
  17627. }
  17628. else
  17629. {
  17630. isDefaultPass = false;
  17631. }
  17632. }
  17633. bool hadExistingMethodInstance = false;
  17634. if (methodInstance != NULL)
  17635. {
  17636. hadExistingMethodInstance = true;
  17637. }
  17638. else
  17639. {
  17640. if (isDefaultPass)
  17641. {
  17642. methodInstance = methodInstGroup->mDefault;
  17643. if (methodInstance != NULL)
  17644. {
  17645. hadExistingMethodInstance = true;
  17646. }
  17647. else
  17648. {
  17649. methodInstance = new BfMethodInstance();
  17650. methodInstGroup->mDefault = methodInstance;
  17651. }
  17652. }
  17653. else
  17654. {
  17655. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  17656. if (methodInstGroup->mMethodSpecializationMap == NULL)
  17657. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  17658. BfMethodInstance** methodInstancePtr = NULL;
  17659. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  17660. {
  17661. methodInstance = *methodInstancePtr;
  17662. hadExistingMethodInstance = true;
  17663. }
  17664. else
  17665. {
  17666. methodInstance = new BfMethodInstance();
  17667. *methodInstancePtr = methodInstance;
  17668. }
  17669. }
  17670. }
  17671. if (hadExistingMethodInstance)
  17672. {
  17673. if ((!methodInstance->mDisallowCalling) ||
  17674. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  17675. return BfModuleMethodInstance(methodInstance);
  17676. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  17677. }
  17678. else
  17679. {
  17680. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  17681. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  17682. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  17683. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  17684. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  17685. methodInstance->mMethodDef = methodDef;
  17686. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  17687. if (hadConcreteInterfaceGenericArgument)
  17688. methodInstance->mIgnoreBody = true;
  17689. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  17690. for (auto genericArg : sanitizedMethodGenericArguments)
  17691. {
  17692. if (genericArg->IsPrimitiveType())
  17693. genericArg = GetWrappedStructType(genericArg);
  17694. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  17695. }
  17696. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  17697. {
  17698. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  17699. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  17700. }
  17701. SetupMethodIdHash(methodInstance);
  17702. }
  17703. auto _SetupMethodInstance = [&]()
  17704. {
  17705. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  17706. // Generic constraints
  17707. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  17708. {
  17709. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  17710. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  17711. }
  17712. };
  17713. //////////////////////////////////////////////////////////////////////////
  17714. auto _VisitLambdaBody = [&]()
  17715. {
  17716. if (localMethod->mDeclOnly)
  17717. return;
  17718. if (mCompiler->mCanceling)
  17719. return;
  17720. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  17721. {
  17722. VisitCodeBlock(blockBody);
  17723. }
  17724. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  17725. {
  17726. BfType* expectType = NULL;
  17727. if (!methodInstance->mReturnType->IsVoid())
  17728. expectType = methodInstance->mReturnType;
  17729. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  17730. }
  17731. };
  17732. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  17733. {
  17734. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  17735. auto result = ResolveTypeRef(typeRef);
  17736. if (result == NULL)
  17737. result = mContext->mBfObjectType;
  17738. return result;
  17739. };
  17740. BfTypeInstance* outerClosure = NULL;
  17741. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  17742. outerClosure = declMethodState->mClosureState->mClosureType;
  17743. BfMethodState methodState;
  17744. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  17745. BfIRFunctionType funcType;
  17746. auto voidType = GetPrimitiveType(BfTypeCode_None);
  17747. SizedArray<BfIRType, 0> paramTypes;
  17748. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  17749. mBfIRBuilder->SaveDebugLocation();
  17750. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  17751. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17752. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  17753. BfDeferredLocalAssignData deferredLocalAssignData;
  17754. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  17755. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  17756. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  17757. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17758. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17759. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17760. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17761. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  17762. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  17763. methodState.mIRFunction = declMethodState->mIRFunction;
  17764. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  17765. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  17766. {
  17767. methodState.mCurScope->mAstBlock = blockBody;
  17768. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  17769. }
  17770. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  17771. BfClosureState closureState;
  17772. if (methodDef->mMethodType == BfMethodType_Mixin)
  17773. {
  17774. if (declMethodState != NULL)
  17775. {
  17776. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  17777. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  17778. else if (declMethodState->mMethodInstance != NULL)
  17779. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  17780. }
  17781. }
  17782. if (closureState.mReturnType == NULL)
  17783. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  17784. closureState.mCapturing = true;
  17785. closureState.mLocalMethod = localMethod;
  17786. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17787. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  17788. methodState.mClosureState = &closureState;
  17789. closureState.mClosureType = outerClosure;
  17790. int outerLocalsCount = (int)methodState.mLocals.size();
  17791. if (!hadExistingMethodInstance)
  17792. {
  17793. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  17794. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  17795. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17796. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  17797. auto declareModule = this;
  17798. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  17799. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  17800. BF_ASSERT(declareModule != NULL);
  17801. methodInstance->mDeclModule = declareModule;
  17802. _SetupMethodInstance();
  17803. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  17804. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  17805. }
  17806. if (wantPrematureMethodInstance)
  17807. {
  17808. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  17809. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  17810. // its true method instance
  17811. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  17812. //BF_ASSERT(moduleMethodInstance);
  17813. return BfModuleMethodInstance(methodInstance);
  17814. }
  17815. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  17816. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  17817. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  17818. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  17819. closureState.mClosureMethodDef = methodDef;
  17820. bool wantsVisitBody = true;
  17821. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  17822. wantsVisitBody = false;
  17823. if (methodInstance->IsOrInUnspecializedVariation())
  17824. wantsVisitBody = false;
  17825. if (wantsVisitBody)
  17826. {
  17827. BP_ZONE("VisitLambdaBody");
  17828. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  17829. // this capture stage for each of those times
  17830. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  17831. /*
  17832. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  17833. // that will not occur during the actual lambda method generation, for example: returning a value
  17834. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  17835. // our AST nodes will still be visited
  17836. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  17837. */
  17838. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17839. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  17840. mBfIRBuilder->SaveDebugLocation();
  17841. closureState.mCaptureVisitingBody = true;
  17842. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  17843. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  17844. methodState.mMethodInstance = methodInstance;
  17845. NewScopeState();
  17846. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  17847. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  17848. {
  17849. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  17850. for (auto localDef : methodState.mLocals)
  17851. {
  17852. if (localDef->mResolvedType->IsVar())
  17853. continue;
  17854. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  17855. }
  17856. }
  17857. // Keep outs for being marked as assigned
  17858. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17859. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  17860. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  17861. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  17862. if (!mIgnoreErrors)
  17863. localMethod->mDidBodyErrorPass = true;
  17864. _VisitLambdaBody();
  17865. RestoreScopeState();
  17866. closureState.mCaptureVisitingBody = false;
  17867. mBfIRBuilder->RestoreDebugLocation();
  17868. }
  17869. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  17870. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  17871. {
  17872. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  17873. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  17874. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  17875. }
  17876. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  17877. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  17878. closureState.mClosureMethodDef = NULL;
  17879. for (auto methodInstance : closureState.mLocalMethodRefs)
  17880. {
  17881. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  17882. }
  17883. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  17884. prevIgnoreWrites.Restore();
  17885. std::multiset<BfClosureCapturedEntry> capturedEntries;
  17886. //
  17887. {
  17888. auto varMethodState = declMethodState;
  17889. while (varMethodState != NULL)
  17890. {
  17891. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  17892. {
  17893. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  17894. methodDef->mIsStatic = false;
  17895. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17896. methodDef->mIsMutating = true;
  17897. }
  17898. bool copyOuterCaptures = false;
  17899. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  17900. {
  17901. auto localVar = varMethodState->mLocals[localIdx];
  17902. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17903. {
  17904. if (localVar->mIsThis)
  17905. {
  17906. // We can only set mutating if our owning type is mutating
  17907. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  17908. {
  17909. if (typeInst->IsValueType())
  17910. {
  17911. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17912. methodDef->mIsMutating = true;
  17913. }
  17914. }
  17915. methodDef->mIsStatic = false;
  17916. continue;
  17917. }
  17918. if ((localVar->mIsThis) && (outerClosure != NULL))
  17919. {
  17920. continue;
  17921. }
  17922. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  17923. {
  17924. closureState.mConstLocals.push_back(*localVar);
  17925. continue;
  17926. }
  17927. BfClosureCapturedEntry capturedEntry;
  17928. auto capturedType = localVar->mResolvedType;
  17929. bool captureByRef = false;
  17930. if (!capturedType->IsRef())
  17931. {
  17932. if (localVar->mIsThis)
  17933. {
  17934. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  17935. captureByRef = true;
  17936. }
  17937. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17938. captureByRef = true;
  17939. }
  17940. else
  17941. {
  17942. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  17943. {
  17944. capturedType = ((BfRefType*)capturedType)->mElementType;
  17945. }
  17946. }
  17947. if (captureByRef)
  17948. {
  17949. //capturedEntry.mIsByReference = true;
  17950. capturedType = CreateRefType(capturedType);
  17951. }
  17952. else
  17953. {
  17954. //capturedEntry.mIsByReference = false;
  17955. }
  17956. capturedEntry.mNameNode = localVar->mNameNode;
  17957. capturedEntry.mType = capturedType;
  17958. capturedEntry.mName = localVar->mName;
  17959. //capturedEntry.mLocalVarDef = localVar;
  17960. capturedEntries.insert(capturedEntry);
  17961. }
  17962. }
  17963. varMethodState = varMethodState->mPrevMethodState;
  17964. if ((varMethodState == NULL) ||
  17965. (varMethodState->mMixinState != NULL) ||
  17966. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  17967. break;
  17968. }
  17969. }
  17970. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  17971. {
  17972. auto fieldDef = copyField->GetFieldDef();
  17973. BfClosureCapturedEntry capturedEntry;
  17974. capturedEntry.mName = copyField->GetFieldDef()->mName;
  17975. capturedEntry.mType = copyField->mResolvedType;
  17976. if (capturedEntry.mType->IsRef())
  17977. {
  17978. // Keep by ref
  17979. }
  17980. else if (!fieldDef->mIsReadOnly)
  17981. {
  17982. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  17983. }
  17984. capturedEntries.insert(capturedEntry);
  17985. }
  17986. int captureIdx = 0;
  17987. for (auto& capturedEntry : capturedEntries)
  17988. {
  17989. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  17990. }
  17991. /*if (isDefaultPass)
  17992. {
  17993. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  17994. int captureIdx = 0;
  17995. for (auto& capturedEntry : capturedEntries)
  17996. {
  17997. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  17998. BfParameterDef* paramDef = new BfParameterDef();
  17999. paramDef->mName = capturedEntry.mName;
  18000. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  18001. directTypeRef->mType = capturedEntry.mType;
  18002. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  18003. paramDef->mTypeRef = directTypeRef;
  18004. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  18005. methodDef->mParams.Insert(captureIdx, paramDef);
  18006. captureIdx++;
  18007. }
  18008. }
  18009. else
  18010. {
  18011. auto defaultMethodInstance = methodInstGroup->mDefault;
  18012. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  18013. }*/
  18014. methodState.Reset();
  18015. closureState.mCapturing = false;
  18016. //////////////////////////////////////////////////////////////////////////
  18017. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  18018. if (methodInstance->mReturnType != NULL)
  18019. {
  18020. BF_ASSERT(methodInstance->mDisallowCalling);
  18021. // We did a premature declaration (without captures)
  18022. methodInstance->UndoDeclaration();
  18023. methodInstance->mDisallowCalling = false;
  18024. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  18025. }
  18026. auto declareModule = this;
  18027. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  18028. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  18029. BF_ASSERT(declareModule != NULL);
  18030. methodInstance->mDeclModule = declareModule;
  18031. _SetupMethodInstance();
  18032. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  18033. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  18034. closureState.mReturnType = methodInstance->mReturnType;
  18035. mCompiler->mStats.mMethodsQueued++;
  18036. mCompiler->UpdateCompletion();
  18037. declareModule->mIncompleteMethodCount++;
  18038. mCompiler->mStats.mMethodsProcessed++;
  18039. if (!methodInstance->mIsReified)
  18040. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  18041. auto deferMethodState = rootMethodState;
  18042. // 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)
  18043. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  18044. (methodDef->mMethodType != BfMethodType_Mixin) &&
  18045. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)))
  18046. {
  18047. BP_ZONE("BfDeferredLocalMethod:create");
  18048. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  18049. deferredLocalMethod->mLocalMethod = localMethod;
  18050. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  18051. deferredLocalMethod->mMethodInstance = methodInstance;
  18052. auto checkMethodState = declMethodState;
  18053. while (checkMethodState != NULL)
  18054. {
  18055. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  18056. {
  18057. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  18058. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  18059. }
  18060. if (checkMethodState->mMixinState != NULL)
  18061. {
  18062. BfMixinRecord mixinRecord;
  18063. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  18064. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  18065. }
  18066. checkMethodState = checkMethodState->mPrevMethodState;
  18067. }
  18068. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  18069. }
  18070. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  18071. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  18072. mBfIRBuilder->RestoreDebugLocation();
  18073. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  18074. {
  18075. auto checkMethodState = mCurMethodState;
  18076. while (checkMethodState != NULL)
  18077. {
  18078. BfLocalMethod* nextLocalMethod = NULL;
  18079. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  18080. {
  18081. while (nextLocalMethod != NULL)
  18082. {
  18083. auto checkLocalMethod = nextLocalMethod;
  18084. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  18085. if (checkLocalMethod == localMethod)
  18086. continue;
  18087. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  18088. continue;
  18089. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  18090. if (checkMethodInstance == NULL)
  18091. continue; // Not generated yet
  18092. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  18093. {
  18094. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  18095. if (bfError != NULL)
  18096. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  18097. }
  18098. }
  18099. }
  18100. checkMethodState = checkMethodState->mPrevMethodState;
  18101. }
  18102. }
  18103. return BfModuleMethodInstance(methodInstance);
  18104. }
  18105. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  18106. {
  18107. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  18108. return 0;
  18109. auto rootMethodState = mCurMethodState->GetRootMethodState();
  18110. int rootMethodGenericParamCount = 0;
  18111. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  18112. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  18113. if (mCurMethodInstance == NULL)
  18114. return rootMethodGenericParamCount;
  18115. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  18116. return rootMethodGenericParamCount;
  18117. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  18118. if (callerLocalMethod == NULL)
  18119. return rootMethodGenericParamCount;
  18120. BfLocalMethod* calledLocalMethod = NULL;
  18121. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  18122. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  18123. {
  18124. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  18125. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  18126. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  18127. }
  18128. return rootMethodGenericParamCount;
  18129. }
  18130. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  18131. {
  18132. auto methodDef = methodInstance->mMethodDef;
  18133. auto customAttributes = methodInstance->GetCustomAttributes();
  18134. if (customAttributes != NULL)
  18135. return;
  18136. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18137. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18138. auto typeInstance = methodInstance->GetOwner();
  18139. BfTypeState typeState(typeInstance);
  18140. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  18141. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  18142. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  18143. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  18144. BfAttributeDirective* attributeDirective = NULL;
  18145. if (methodDeclaration != NULL)
  18146. attributeDirective = methodDeclaration->mAttributes;
  18147. else if (propertyMethodDeclaration != NULL)
  18148. {
  18149. attributeDirective = propertyMethodDeclaration->mAttributes;
  18150. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  18151. {
  18152. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  18153. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  18154. }
  18155. }
  18156. if (attributeDirective != NULL)
  18157. {
  18158. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  18159. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  18160. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  18161. }
  18162. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  18163. {
  18164. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  18165. {
  18166. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  18167. }
  18168. else
  18169. {
  18170. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  18171. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  18172. }
  18173. }
  18174. customAttributes = methodInstance->GetCustomAttributes();
  18175. if (customAttributes == NULL)
  18176. {
  18177. auto owner = methodInstance->GetOwner();
  18178. if ((owner->IsDelegate()) || (owner->IsFunction()))
  18179. customAttributes = owner->mCustomAttributes;
  18180. }
  18181. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  18182. if (customAttributes != NULL)
  18183. {
  18184. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  18185. if (linkNameAttr != NULL)
  18186. {
  18187. if (linkNameAttr->mCtorArgs.size() == 1)
  18188. {
  18189. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  18190. if (constant != NULL)
  18191. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  18192. }
  18193. }
  18194. if (methodDef->mHasComptime)
  18195. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  18196. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  18197. if (comptimeAttr != NULL)
  18198. {
  18199. for (auto setProp : comptimeAttr->mSetProperties)
  18200. {
  18201. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  18202. if (propertyDef->mName == "OnlyFromComptime")
  18203. {
  18204. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  18205. if ((constant != NULL) && (constant->mBool))
  18206. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  18207. }
  18208. else if (propertyDef->mName == "ConstEval")
  18209. {
  18210. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  18211. if ((constant != NULL) && (constant->mBool))
  18212. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  18213. }
  18214. }
  18215. }
  18216. }
  18217. }
  18218. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  18219. {
  18220. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  18221. {
  18222. // Don't create a func
  18223. return;
  18224. }
  18225. auto typeInstance = methodInstance->GetOwner();
  18226. auto methodDef = methodInstance->mMethodDef;
  18227. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  18228. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  18229. if (mCompiler->mResolvePassData == NULL)
  18230. {
  18231. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18232. {
  18233. typeInstance->mHasStaticInitMethod = true;
  18234. }
  18235. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  18236. {
  18237. typeInstance->mHasStaticDtorMethod = true;
  18238. }
  18239. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  18240. {
  18241. typeInstance->mHasStaticMarkMethod = true;
  18242. }
  18243. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  18244. {
  18245. typeInstance->mHasTLSFindMethod = true;
  18246. }
  18247. }
  18248. if (isTemporaryFunc)
  18249. {
  18250. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  18251. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  18252. mangledName = "autocomplete_tmp";
  18253. }
  18254. if (!mBfIRBuilder->mIgnoreWrites)
  18255. {
  18256. BfIRFunction prevFunc;
  18257. // Remove old version (if we have one)
  18258. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  18259. if (prevFunc)
  18260. {
  18261. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  18262. {
  18263. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  18264. BfMethodDef* nextMethod = NULL;
  18265. BfMemberSetEntry* entry = NULL;
  18266. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18267. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18268. while (nextMethod != NULL)
  18269. {
  18270. auto checkMethod = nextMethod;
  18271. nextMethod = nextMethod->mNextWithSameName;
  18272. if (checkMethod == methodDef)
  18273. continue;
  18274. if (!checkMethod->mIsExtern)
  18275. continue;
  18276. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  18277. if (checkMethodInstance == NULL)
  18278. continue;
  18279. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  18280. continue;
  18281. // Take over function
  18282. mCurMethodInstance->mIRFunction = prevFunc;
  18283. }
  18284. if (!mCurMethodInstance->mIRFunction)
  18285. {
  18286. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  18287. if (!mIsComptimeModule)
  18288. mBfIRBuilder->Func_SafeRename(prevFunc);
  18289. }
  18290. }
  18291. else if (methodDef->mIsExtern)
  18292. {
  18293. // Allow this
  18294. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  18295. }
  18296. else if (typeInstance->IsIRFuncUsed(prevFunc))
  18297. {
  18298. // We can have a collision of names when we have generic methods that differ only in
  18299. // their constraints, but they should only collide in their unspecialized form
  18300. // since only one will be chosen for a given concrete type
  18301. if (!mIsComptimeModule)
  18302. mCurMethodInstance->mMangleWithIdx = true;
  18303. mangledName.Clear();
  18304. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18305. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  18306. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  18307. }
  18308. else
  18309. {
  18310. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  18311. if (!mIsComptimeModule)
  18312. mBfIRBuilder->Func_SafeRename(prevFunc);
  18313. }
  18314. }
  18315. }
  18316. if (typeInstance != mContext->mBfObjectType)
  18317. {
  18318. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  18319. GetMethodCustomAttributes(methodInstance);
  18320. }
  18321. // if (prevFunc)
  18322. // {
  18323. // if (methodDef->mIsExtern)
  18324. // {
  18325. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  18326. // methodInstance->mIRFunction = prevFunc;
  18327. // }
  18328. // else
  18329. // {
  18330. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  18331. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  18332. // {
  18333. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  18334. // BfLogSysM("Ignoring function name collision\n");
  18335. // }
  18336. // else
  18337. // {
  18338. // if (methodDef->mMethodDeclaration == NULL)
  18339. // {
  18340. // AssertErrorState();
  18341. // }
  18342. // else
  18343. // {
  18344. // BF_ASSERT(mIsSpecialModule);
  18345. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  18346. // {
  18347. // // We shouldn't have name collisions on the first run!
  18348. // AssertErrorState();
  18349. // }
  18350. // }
  18351. // }
  18352. // BfLogSysM("Before erase\n");
  18353. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  18354. // }
  18355. // }
  18356. bool isIntrinsic = false;
  18357. if (!methodInstance->mIRFunction)
  18358. {
  18359. BfIRFunction func;
  18360. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  18361. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  18362. {
  18363. if (!mIsReified)
  18364. wantsLLVMFunc = false;
  18365. }*/
  18366. if (wantsLLVMFunc)
  18367. {
  18368. func = GetIntrinsic(methodInstance, true);
  18369. if (func)
  18370. {
  18371. isIntrinsic = true;
  18372. }
  18373. else
  18374. {
  18375. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  18376. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  18377. if (methodInstance->mAlwaysInline)
  18378. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  18379. // if (prevFunc)
  18380. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  18381. }
  18382. methodInstance->mIRFunction = func;
  18383. //if (!ignoreWrites)
  18384. //BF_ASSERT(!func.IsFake());
  18385. }
  18386. }
  18387. if (outIsIntrinsic != NULL)
  18388. *outIsIntrinsic = isIntrinsic;
  18389. if (!isIntrinsic)
  18390. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  18391. }
  18392. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  18393. {
  18394. if (methodInstance->mHotMethod != NULL)
  18395. return;
  18396. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  18397. {
  18398. auto srcTypeInst = methodInstance->GetOwner();
  18399. StringT<128> mangledName = inMangledName;
  18400. if (mangledName.IsEmpty())
  18401. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  18402. // We always keep the current primary method at the same address
  18403. BfHotMethod* hotMethod;
  18404. BfHotMethod** hotMethodPtr;
  18405. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  18406. {
  18407. hotMethod = new BfHotMethod();
  18408. *hotMethodPtr = hotMethod;
  18409. hotMethod->mRefCount = 1;
  18410. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  18411. #ifdef BF_DBG_HOTMETHOD_IDX
  18412. static int sMethodIdx = 0;
  18413. hotMethod->mMethodIdx = sMethodIdx++;
  18414. #endif
  18415. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  18416. }
  18417. else
  18418. {
  18419. hotMethod = *hotMethodPtr;
  18420. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  18421. {
  18422. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  18423. auto prevHotMethod = *hotMethodPtr;
  18424. hotMethod = new BfHotMethod();
  18425. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  18426. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  18427. hotDupMethod->mRefCount++;
  18428. prevHotMethod->mReferences.Add(hotDupMethod);
  18429. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  18430. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  18431. }
  18432. else if (mCompiler->IsHotCompile())
  18433. {
  18434. // Link the previous version into the mPrevVersion
  18435. BfHotMethod* prevMethod = new BfHotMethod();
  18436. prevMethod->mRefCount = 1;
  18437. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  18438. hotMethod->mPrevVersion = prevMethod;
  18439. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  18440. hotMethod->mSrcTypeVersion = NULL;
  18441. prevMethod->mFlags = hotMethod->mFlags;
  18442. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  18443. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  18444. #ifdef BF_DBG_HOTMETHOD_NAME
  18445. prevMethod->mMangledName = hotMethod->mMangledName;
  18446. #endif
  18447. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  18448. }
  18449. else
  18450. {
  18451. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  18452. hotMethod->Clear(true);
  18453. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  18454. }
  18455. }
  18456. if (methodInstance->mIsClosure)
  18457. {
  18458. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  18459. }
  18460. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  18461. hotMethod->mSrcTypeVersion->mRefCount++;
  18462. hotMethod->mRefCount++;
  18463. #ifdef BF_DBG_HOTMETHOD_NAME
  18464. hotMethod->mMangledName = mangledName;
  18465. #endif
  18466. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!mCompiler->IsHotCompile()))
  18467. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  18468. methodInstance->mHotMethod = hotMethod;
  18469. }
  18470. }
  18471. static void StackOverflow()
  18472. {
  18473. int i = 0;
  18474. if (i == 0)
  18475. StackOverflow();
  18476. }
  18477. // methodDeclaration is NULL for default constructors
  18478. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  18479. {
  18480. BP_ZONE("BfModule::BfMethodDeclaration");
  18481. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  18482. // to effectively make mIgnoreWrites method-scoped
  18483. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  18484. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  18485. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  18486. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  18487. if (mCompiler->IsAutocomplete())
  18488. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  18489. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  18490. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  18491. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  18492. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  18493. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  18494. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  18495. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  18496. // {
  18497. // BF_ASSERT(mContext->mResolvingVarField);
  18498. // isTemporaryFunc = true;
  18499. // }
  18500. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  18501. FinishInit();
  18502. auto typeInstance = mCurTypeInstance;
  18503. auto typeDef = typeInstance->mTypeDef;
  18504. auto methodDef = mCurMethodInstance->mMethodDef;
  18505. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  18506. if (methodDef->mName == "__FATALERRORNAME")
  18507. BFMODULE_FATAL(this, "__FATALERRORNAME");
  18508. if (methodDef->mName == "__STACKOVERFLOW")
  18509. StackOverflow();
  18510. if (typeInstance->IsClosure())
  18511. {
  18512. if (methodDef->mName == "Invoke")
  18513. return;
  18514. }
  18515. auto methodInstance = mCurMethodInstance;
  18516. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  18517. addToWorkList = false;
  18518. bool hasNonGenericParams = false;
  18519. bool hasGenericParams = false;
  18520. int dependentGenericStartIdx = 0;
  18521. if (methodDef->mIsLocalMethod)
  18522. {
  18523. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  18524. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  18525. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  18526. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  18527. // over the local method each time
  18528. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  18529. dependentGenericStartIdx = 0;
  18530. if (rootMethodInstance->mMethodInfoEx != NULL)
  18531. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  18532. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  18533. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  18534. }
  18535. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  18536. {
  18537. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  18538. if (genericArgType->IsGenericParam())
  18539. {
  18540. hasGenericParams = true;
  18541. auto genericParam = (BfGenericParamType*)genericArgType;
  18542. methodInstance->mIsUnspecialized = true;
  18543. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  18544. methodInstance->mIsUnspecializedVariation = true;
  18545. }
  18546. else
  18547. {
  18548. hasNonGenericParams = true;
  18549. if (genericArgType->IsUnspecializedType())
  18550. {
  18551. methodInstance->mIsUnspecialized = true;
  18552. methodInstance->mIsUnspecializedVariation = true;
  18553. }
  18554. }
  18555. }
  18556. if ((hasGenericParams) && (hasNonGenericParams))
  18557. {
  18558. methodInstance->mIsUnspecializedVariation = true;
  18559. }
  18560. if (typeInstance->IsUnspecializedType())
  18561. {
  18562. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  18563. // actually want to do method processing on it
  18564. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  18565. methodInstance->mIsUnspecializedVariation = true;
  18566. methodInstance->mIsUnspecialized = true;
  18567. }
  18568. //methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  18569. for (auto genericParamDef : methodDef->mGenericParams)
  18570. {
  18571. if (mCompiler->IsAutocomplete())
  18572. {
  18573. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18574. //autoComplete->CheckTypeRef()
  18575. }
  18576. }
  18577. if (methodInstance->mIsUnspecializedVariation)
  18578. {
  18579. }
  18580. if (methodInstance->mIsUnspecializedVariation)
  18581. BF_ASSERT(methodInstance->mIsUnspecialized);
  18582. if (methodDef->mMethodType == BfMethodType_Mixin)
  18583. methodInstance->mIsUnspecialized = true;
  18584. if (methodInstance->mIsUnspecialized)
  18585. {
  18586. //BF_ASSERT(methodInstance->mDeclModule == methodInstance->GetOwner()->mModule);
  18587. }
  18588. BfAutoComplete* bfAutocomplete = NULL;
  18589. if (mCompiler->mResolvePassData != NULL)
  18590. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  18591. if (methodInstance->mMethodInfoEx != NULL)
  18592. {
  18593. BfTypeInstance* unspecializedTypeInstance = NULL;
  18594. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  18595. {
  18596. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  18597. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  18598. {
  18599. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  18600. }
  18601. else
  18602. {
  18603. auto externConstraintDef = genericParam->GetExternConstraintDef();
  18604. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  18605. auto autoComplete = mCompiler->GetAutoComplete();
  18606. if (autoComplete != NULL)
  18607. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  18608. if (genericParam->mExternType != NULL)
  18609. {
  18610. //
  18611. }
  18612. else
  18613. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  18614. }
  18615. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  18616. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  18617. {
  18618. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  18619. if (bfAutocomplete != NULL)
  18620. {
  18621. for (auto nameNode : genericParamDef->mNameNodes)
  18622. {
  18623. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  18624. }
  18625. }
  18626. }
  18627. }
  18628. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  18629. {
  18630. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  18631. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  18632. if (genericParam->mTypeConstraint != NULL)
  18633. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  18634. }
  18635. }
  18636. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  18637. {
  18638. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18639. BfAstNode* nameNode = methodDeclaration->mNameNode;
  18640. if (nameNode == NULL)
  18641. {
  18642. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  18643. nameNode = ctorDeclaration->mThisToken;
  18644. }
  18645. if (autoComplete->IsAutocompleteNode(nameNode))
  18646. {
  18647. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  18648. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  18649. autoComplete->mDefType = typeDef;
  18650. autoComplete->mDefMethod = methodDef;
  18651. autoComplete->SetDefinitionLocation(nameNode);
  18652. if (methodDef->mIsOverride)
  18653. {
  18654. bool found = false;
  18655. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  18656. {
  18657. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  18658. if (ventry.mDeclaringMethod.mMethodNum == -1)
  18659. continue;
  18660. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  18661. if (virtMethod != NULL)
  18662. {
  18663. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  18664. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  18665. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  18666. {
  18667. // Is matching method
  18668. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  18669. {
  18670. auto baseType = typeInstance->mBaseType;
  18671. if (baseType != NULL)
  18672. {
  18673. found = true;
  18674. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  18675. baseType = baseType->mBaseType;
  18676. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  18677. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  18678. autoComplete->mDefType = baseType->mTypeDef;
  18679. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  18680. }
  18681. }
  18682. break;
  18683. }
  18684. }
  18685. }
  18686. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  18687. {
  18688. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  18689. {
  18690. auto defaultMethod = methodGroup.mDefault;
  18691. if (defaultMethod == NULL)
  18692. continue;
  18693. if (!defaultMethod->mMethodDef->mIsExtern)
  18694. continue;
  18695. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  18696. continue;
  18697. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  18698. autoComplete->mDefType = typeInstance->mTypeDef;
  18699. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  18700. }
  18701. }
  18702. }
  18703. }
  18704. }
  18705. bool reportErrors = true;
  18706. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  18707. reportErrors = true;
  18708. // Only the defining contexts needs to report errors here
  18709. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  18710. if (methodDef->mMethodType == BfMethodType_Dtor)
  18711. {
  18712. if (methodDef->mIsStatic)
  18713. {
  18714. }
  18715. else
  18716. {
  18717. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  18718. {
  18719. BfAstNode* refNode = methodDeclaration;
  18720. if (refNode == NULL)
  18721. {
  18722. // Whatever caused this ctor to be generated should have caused another failure
  18723. // But that failure might not be generated until the ctor is generated
  18724. }
  18725. else
  18726. {
  18727. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  18728. if (dtorDecl != NULL)
  18729. refNode = dtorDecl->mThisToken;
  18730. Fail("Structs cannot have destructors", refNode);
  18731. }
  18732. }
  18733. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18734. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  18735. (mCurTypeInstance != mContext->mBfObjectType))
  18736. {
  18737. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  18738. }
  18739. }
  18740. }
  18741. BfType* resolvedReturnType = NULL;
  18742. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  18743. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  18744. (methodDef->mReturnTypeRef != NULL))
  18745. {
  18746. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  18747. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric);
  18748. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  18749. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  18750. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  18751. else
  18752. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  18753. if (resolvedReturnType == NULL)
  18754. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  18755. }
  18756. else
  18757. {
  18758. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  18759. }
  18760. BF_ASSERT(resolvedReturnType != NULL);
  18761. mCurMethodInstance->mReturnType = resolvedReturnType;
  18762. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  18763. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  18764. //if (!methodInstance->IsSpecializedGenericMethod())
  18765. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18766. if (methodDef->mExplicitInterface != NULL)
  18767. {
  18768. auto autoComplete = mCompiler->GetAutoComplete();
  18769. if (autoComplete != NULL)
  18770. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  18771. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  18772. BfTypeInstance* explicitInterface = NULL;
  18773. if (explicitType != NULL)
  18774. explicitInterface = explicitType->ToTypeInstance();
  18775. if (explicitInterface != NULL)
  18776. {
  18777. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  18778. if (autoComplete != NULL)
  18779. {
  18780. BfTokenNode* dotToken = NULL;
  18781. BfAstNode* nameNode = NULL;
  18782. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  18783. {
  18784. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  18785. nameNode = methodDeclaration->mNameNode;
  18786. }
  18787. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  18788. }
  18789. }
  18790. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  18791. {
  18792. bool interfaceFound = false;
  18793. for (auto ifaceInst : typeInstance->mInterfaces)
  18794. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  18795. if (!interfaceFound)
  18796. {
  18797. if (methodDef->mMethodDeclaration != NULL)
  18798. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  18799. else
  18800. {
  18801. // For property decls, we should have already given the error during type population
  18802. if (mCompiler->mRevision == 1)
  18803. AssertErrorState();
  18804. }
  18805. }
  18806. }
  18807. }
  18808. bool isThisStruct = mCurTypeInstance->IsStruct();
  18809. BfType* thisType = NULL;
  18810. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  18811. {
  18812. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  18813. {
  18814. thisType = mCurTypeInstance;
  18815. if (thisType == NULL)
  18816. return;
  18817. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  18818. {
  18819. BfTypeUtils::SplatIterate([&](BfType* checkType)
  18820. {
  18821. PopulateType(checkType, BfPopulateType_Data);
  18822. }, thisType);
  18823. }
  18824. }
  18825. else
  18826. {
  18827. thisType = mCurTypeInstance;
  18828. PopulateType(thisType, BfPopulateType_Declaration);
  18829. }
  18830. }
  18831. int implicitParamCount = 0;
  18832. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  18833. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  18834. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  18835. bool hadDelegateParams = false;
  18836. bool hadParams = false;
  18837. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  18838. {
  18839. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  18840. BfParameterDef* paramDef = NULL;
  18841. int paramDefIdx = -1;
  18842. if (paramIdx < implicitParamCount)
  18843. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  18844. else
  18845. {
  18846. paramDefIdx = paramIdx - implicitParamCount;
  18847. paramDef = methodDef->mParams[paramDefIdx];
  18848. }
  18849. if (hadParams)
  18850. break;
  18851. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  18852. continue;
  18853. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  18854. (paramDef->mParamKind != BfParamKind_AppendIdx))
  18855. {
  18856. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  18857. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  18858. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  18859. }
  18860. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  18861. {
  18862. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  18863. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  18864. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  18865. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  18866. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  18867. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  18868. }
  18869. BfType* resolvedParamType = NULL;
  18870. if (closureCaptureEntry != NULL)
  18871. resolvedParamType = closureCaptureEntry->mType;
  18872. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  18873. {
  18874. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  18875. resolvedParamType = mContext->mBfObjectType;
  18876. }
  18877. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  18878. {
  18879. if (methodDef->mMethodType != BfMethodType_Mixin)
  18880. {
  18881. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  18882. resolvedParamType = mContext->mBfObjectType;
  18883. }
  18884. else
  18885. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18886. }
  18887. BfType* unresolvedParamType = resolvedParamType;
  18888. bool wasGenericParam = false;
  18889. if (resolvedParamType == NULL)
  18890. {
  18891. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  18892. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  18893. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  18894. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  18895. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  18896. resolvedParamType = resolvedParamType->GetUnderlyingType();
  18897. }
  18898. if (resolvedParamType == NULL)
  18899. {
  18900. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18901. unresolvedParamType = resolvedParamType;
  18902. if (mCurTypeInstance->IsBoxed())
  18903. {
  18904. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  18905. // If we failed a lookup here then we better have also failed it in the original type
  18906. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  18907. }
  18908. }
  18909. if (!methodInstance->IsSpecializedGenericMethod())
  18910. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18911. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  18912. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  18913. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  18914. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  18915. {
  18916. if (paramDef->mParamKind == BfParamKind_Params)
  18917. {
  18918. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  18919. if (refNode != NULL)
  18920. refNode = paramDef->mParamDeclaration->mModToken;
  18921. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  18922. }
  18923. BfMethodState methodState;
  18924. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18925. methodState.mTempKind = BfMethodState::TempKind_Static;
  18926. BfTypedValue defaultValue;
  18927. if (resolvedParamType->IsConstExprValue())
  18928. {
  18929. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  18930. BfExprEvaluator exprEvaluator(this);
  18931. exprEvaluator.mExpectingType = constExprType->mType;
  18932. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  18933. defaultValue = exprEvaluator.GetResult();
  18934. }
  18935. else
  18936. {
  18937. BfConstResolver constResolver(this);
  18938. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  18939. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  18940. {
  18941. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  18942. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  18943. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  18944. {
  18945. defaultValue = castedDefaultValue; // Good!
  18946. }
  18947. else if (!CanCast(defaultValue, resolvedParamType))
  18948. {
  18949. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  18950. // a conversion operator.
  18951. // This should throw an error
  18952. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  18953. AssertErrorState();
  18954. if (!defaultValue.mValue.IsConst())
  18955. defaultValue = BfTypedValue();
  18956. }
  18957. }
  18958. }
  18959. if (!defaultValue)
  18960. {
  18961. defaultValue = GetDefaultTypedValue(resolvedParamType);
  18962. if (!defaultValue.mValue.IsConst())
  18963. defaultValue = BfTypedValue();
  18964. }
  18965. if (defaultValue)
  18966. {
  18967. if (defaultValue.mType->IsVar())
  18968. {
  18969. AssertErrorState();
  18970. }
  18971. else
  18972. {
  18973. BF_ASSERT(defaultValue.mValue.IsConst());
  18974. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  18975. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  18976. CurrentAddToConstHolder(defaultValue.mValue);
  18977. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  18978. }
  18979. }
  18980. }
  18981. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  18982. {
  18983. bool addParams = true;
  18984. bool isValid = false;
  18985. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  18986. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  18987. {
  18988. // Span<T>
  18989. isValid = true;
  18990. }
  18991. else if (resolvedParamType->IsArray())
  18992. {
  18993. // Array is the 'normal' params type
  18994. isValid = true;
  18995. }
  18996. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  18997. {
  18998. hadDelegateParams = true;
  18999. // This means we copy the params from a delegate
  19000. BfMethodParam methodParam;
  19001. methodParam.mResolvedType = resolvedParamType;
  19002. methodParam.mParamDefIdx = paramDefIdx;
  19003. methodParam.mDelegateParamIdx = 0;
  19004. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  19005. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  19006. {
  19007. methodParam.mDelegateParamIdx = delegateParamIdx;
  19008. mCurMethodInstance->mParams.Add(methodParam);
  19009. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  19010. if (!methodInstance->IsSpecializedGenericMethod())
  19011. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  19012. }
  19013. isValid = true;
  19014. addParams = false;
  19015. }
  19016. else if (resolvedParamType->IsGenericParam())
  19017. {
  19018. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  19019. if (genericParamInstance->mTypeConstraint != NULL)
  19020. {
  19021. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  19022. if (genericParamInstance->mTypeConstraint->IsArray())
  19023. {
  19024. BfMethodParam methodParam;
  19025. methodParam.mResolvedType = resolvedParamType;
  19026. methodParam.mParamDefIdx = paramDefIdx;
  19027. mCurMethodInstance->mParams.Add(methodParam);
  19028. isValid = true;
  19029. }
  19030. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  19031. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  19032. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  19033. {
  19034. mCurMethodInstance->mHadGenericDelegateParams = true;
  19035. isValid = true;
  19036. addParams = false;
  19037. }
  19038. }
  19039. }
  19040. else
  19041. {
  19042. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  19043. if ((paramTypeInst != NULL) &&
  19044. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  19045. {
  19046. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  19047. isValid = true;
  19048. addParams = false;
  19049. }
  19050. }
  19051. if (!isValid)
  19052. {
  19053. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  19054. // Failure case, make it an Object[]
  19055. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  19056. }
  19057. if (addParams)
  19058. {
  19059. BfMethodParam methodParam;
  19060. methodParam.mResolvedType = resolvedParamType;
  19061. methodParam.mParamDefIdx = paramDefIdx;
  19062. mCurMethodInstance->mParams.push_back(methodParam);
  19063. }
  19064. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  19065. {
  19066. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  19067. }
  19068. }
  19069. else
  19070. {
  19071. BfMethodParam methodParam;
  19072. methodParam.mResolvedType = resolvedParamType;
  19073. methodParam.mParamDefIdx = paramDefIdx;
  19074. mCurMethodInstance->mParams.Add(methodParam);
  19075. }
  19076. }
  19077. if (hadDelegateParams)
  19078. {
  19079. HashSet<String> usedNames;
  19080. Dictionary<int, int> usedParamDefIdx;
  19081. for (auto methodParam : methodDef->mParams)
  19082. {
  19083. usedNames.Add(methodParam->mName);
  19084. }
  19085. for (auto& methodParam : mCurMethodInstance->mParams)
  19086. {
  19087. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  19088. {
  19089. int* refCount = NULL;
  19090. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  19091. (*refCount)++;
  19092. }
  19093. }
  19094. for (auto& methodParam : mCurMethodInstance->mParams)
  19095. {
  19096. if (methodParam.mDelegateParamIdx != -1)
  19097. {
  19098. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  19099. methodParam.mDelegateParamNameCombine = true;
  19100. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  19101. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  19102. if (usedNames.Contains(paramName))
  19103. methodParam.mDelegateParamNameCombine = true;
  19104. }
  19105. }
  19106. }
  19107. int argIdx = 0;
  19108. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  19109. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  19110. {
  19111. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  19112. auto thisType = methodInstance->GetOwner();
  19113. if (methodInstance->GetParamIsSplat(thisIdx))
  19114. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  19115. else if (!thisType->IsValuelessType())
  19116. {
  19117. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19118. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19119. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  19120. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19121. argIdx++;
  19122. if (loweredTypeCode2 != BfTypeCode_None)
  19123. argIdx++;
  19124. }
  19125. }
  19126. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  19127. argIdx++;
  19128. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  19129. {
  19130. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  19131. BfType* checkType = methodParam.mResolvedType;
  19132. int checkArgIdx = argIdx;
  19133. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  19134. {
  19135. checkArgIdx = 0;
  19136. checkType = methodInstance->GetThisType();
  19137. }
  19138. if (checkType->IsMethodRef())
  19139. {
  19140. methodParam.mIsSplat = true;
  19141. }
  19142. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  19143. {
  19144. PopulateType(checkType, BfPopulateType_Data);
  19145. if (checkType->IsSplattable())
  19146. {
  19147. bool isSplat = false;
  19148. auto checkTypeInstance = checkType->ToTypeInstance();
  19149. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  19150. isSplat = true;
  19151. int splatCount = checkType->GetSplatCount();
  19152. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  19153. isSplat = true;
  19154. if (isSplat)
  19155. {
  19156. methodParam.mIsSplat = true;
  19157. argIdx += splatCount;
  19158. continue;
  19159. }
  19160. }
  19161. else if (!checkType->IsValuelessType())
  19162. {
  19163. BfTypeCode loweredTypeCode = BfTypeCode_None;
  19164. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  19165. if (!mIsComptimeModule)
  19166. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  19167. argIdx++;
  19168. if (loweredTypeCode2 != BfTypeCode_None)
  19169. argIdx++;
  19170. continue;
  19171. }
  19172. }
  19173. argIdx++;
  19174. }
  19175. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  19176. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  19177. {
  19178. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  19179. }
  19180. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  19181. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  19182. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  19183. (!methodDef->mIsSkipCall))
  19184. {
  19185. if (methodDeclaration->mEndSemicolon == NULL)
  19186. {
  19187. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  19188. {
  19189. //
  19190. }
  19191. else
  19192. AssertParseErrorState();
  19193. }
  19194. else
  19195. {
  19196. bool isError = true;
  19197. if (typeInstance->IsTypedPrimitive())
  19198. {
  19199. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  19200. {
  19201. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  19202. {
  19203. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  19204. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  19205. {
  19206. isError = false;
  19207. }
  19208. }
  19209. }
  19210. }
  19211. if (isError)
  19212. {
  19213. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  19214. MethodToString(methodInstance).c_str()),
  19215. methodDef->GetRefNode());
  19216. }
  19217. }
  19218. }
  19219. if (methodDef->IsEmptyPartial())
  19220. hasExternSpecifier = true;
  19221. if (!methodInstance->IsAutocompleteMethod())
  19222. {
  19223. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  19224. int implicitParamCount = methodInstance->GetImplicitParamCount();
  19225. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  19226. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  19227. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  19228. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  19229. int paramIdx = 0;
  19230. int defaultParamIdx = 0;
  19231. while (true)
  19232. {
  19233. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  19234. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  19235. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  19236. {
  19237. paramIdx++;
  19238. continue;
  19239. }
  19240. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  19241. {
  19242. defaultParamIdx++;
  19243. continue;
  19244. }
  19245. if ((isDone) || (isDefaultDone))
  19246. {
  19247. // 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
  19248. // to cause us to throw an assertion in the declaration here
  19249. if (!defaultMethodInstance->mHadGenericDelegateParams)
  19250. BF_ASSERT((isDone) && (isDefaultDone));
  19251. break;
  19252. }
  19253. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  19254. if (paramType->IsRef())
  19255. paramType = paramType->GetUnderlyingType();
  19256. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  19257. paramIdx++;
  19258. defaultParamIdx++;
  19259. }
  19260. }
  19261. StringT<128> mangledName;
  19262. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  19263. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  19264. {
  19265. auto paramType = methodInstance->GetParamType(paramIdx);
  19266. if (paramType->IsComposite())
  19267. PopulateType(paramType, BfPopulateType_Data);
  19268. if (!methodInstance->IsParamSkipped(paramIdx))
  19269. {
  19270. if (paramType->IsStruct())
  19271. {
  19272. //
  19273. }
  19274. else
  19275. {
  19276. PopulateType(paramType, BfPopulateType_Declaration);
  19277. }
  19278. }
  19279. }
  19280. // Only process method in default unspecialized mode, not in variations
  19281. if (methodInstance->mIsUnspecializedVariation)
  19282. return;
  19283. PopulateType(resolvedReturnType, BfPopulateType_Data);
  19284. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  19285. if (resolvedReturnType->IsValuelessType())
  19286. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  19287. if (!mBfIRBuilder->mIgnoreWrites)
  19288. {
  19289. bool isIntrinsic = false;
  19290. if (!methodInstance->mIRFunction)
  19291. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  19292. if (isIntrinsic)
  19293. {
  19294. addToWorkList = false;
  19295. }
  19296. }
  19297. auto func = methodInstance->mIRFunction;
  19298. // if (methodInstance->mIsReified)
  19299. // CheckHotMethod(methodInstance, mangledName);
  19300. 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);
  19301. SizedArray<BfIRMDNode, 8> diParams;
  19302. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  19303. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  19304. {
  19305. //CS0708
  19306. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  19307. }
  19308. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  19309. {
  19310. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  19311. methodDef->mIsVirtual = false;
  19312. }
  19313. BfAstNode* mutSpecifier = NULL;
  19314. if (methodDeclaration != NULL)
  19315. mutSpecifier = methodDeclaration->mMutSpecifier;
  19316. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  19317. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  19318. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  19319. {
  19320. if (methodDef->mIsStatic)
  19321. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  19322. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  19323. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  19324. else if (methodDef->mMethodType == BfMethodType_Ctor)
  19325. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  19326. else if (methodDef->mMethodType == BfMethodType_Dtor)
  19327. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  19328. }
  19329. if (isTemporaryFunc)
  19330. {
  19331. // This handles temporary methods for autocomplete types
  19332. //BF_ASSERT(mIsScratchModule);
  19333. //BF_ASSERT(mCompiler->IsAutocomplete());
  19334. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  19335. return; // Bail out early for autocomplete pass
  19336. }
  19337. if ((methodInstance->GetImportCallKind() != BfImportCallKind_None) && (!mBfIRBuilder->mIgnoreWrites) && (!methodInstance->mIRFunction))
  19338. {
  19339. BfLogSysM("DllImportGlobalVar DoMethodDeclaration processing %p\n", methodInstance);
  19340. // If this is in an extension then we did create the global variable already in the original obj
  19341. bool doDefine = mExtensionCount == 0;
  19342. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, doDefine);
  19343. func = mBfIRBuilder->GetFakeVal();
  19344. methodInstance->mIRFunction = func;
  19345. BF_ASSERT(dllImportGlobalVar);
  19346. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  19347. }
  19348. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  19349. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  19350. // autocompleter. Why did we have this check anyway?
  19351. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  19352. {
  19353. AddMethodReference(methodInstance);
  19354. mFuncReferences[methodInstance] = func;
  19355. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  19356. }*/
  19357. if (mParentModule != NULL)
  19358. {
  19359. // For extension modules we need to keep track of our own methods so we can know which methods
  19360. // we have defined ourselves and which are from the parent module or other extensions
  19361. if (!func.IsFake())
  19362. {
  19363. if (func)
  19364. mFuncReferences[methodInstance] = func;
  19365. }
  19366. }
  19367. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  19368. {
  19369. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  19370. auto owningModule = methodInstance->GetOwner()->mModule;
  19371. if (!owningModule->mIsScratchModule)
  19372. owningModule->mOnDemandMethodCount++;
  19373. VerifyOnDemandMethods();
  19374. }
  19375. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  19376. if (wasAwaitingDecl)
  19377. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  19378. if (addToWorkList)
  19379. {
  19380. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  19381. {
  19382. AddMethodToWorkList(methodInstance);
  19383. }
  19384. else
  19385. {
  19386. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  19387. methodInstance->mIgnoreBody = true;
  19388. if (typeInstance->IsUnspecializedType())
  19389. {
  19390. // Don't hold on to actual Function for unspecialized types
  19391. methodInstance->mIRFunction = BfIRFunction();
  19392. }
  19393. }
  19394. }
  19395. else
  19396. {
  19397. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  19398. }
  19399. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  19400. (!methodDef->mIsLocalMethod) &&
  19401. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  19402. (!methodDef->mReturnTypeRef->IsTemporary()))
  19403. {
  19404. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  19405. {
  19406. //TODO:
  19407. //CS0053
  19408. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  19409. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  19410. methodDef->mReturnTypeRef, true);
  19411. }
  19412. else
  19413. {
  19414. //CS0050
  19415. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  19416. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  19417. methodDef->mReturnTypeRef, true);
  19418. }
  19419. }
  19420. if (typeInstance->IsInterface())
  19421. {
  19422. if (methodDef->mMethodType == BfMethodType_Ctor)
  19423. Fail("Interfaces cannot contain constructors", methodDeclaration);
  19424. if (methodDeclaration != NULL)
  19425. {
  19426. if (methodDef->mBody == NULL)
  19427. {
  19428. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  19429. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  19430. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  19431. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  19432. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  19433. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  19434. }
  19435. }
  19436. }
  19437. bool foundHiddenMethod = false;
  19438. BfTokenNode* virtualToken = NULL;
  19439. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19440. if (propertyDeclaration != NULL)
  19441. virtualToken = propertyDeclaration->mVirtualSpecifier;
  19442. else if (methodDeclaration != NULL)
  19443. virtualToken = methodDeclaration->mVirtualSpecifier;
  19444. // Don't compare specialized generic methods against normal methods
  19445. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  19446. (!methodDef->mIsLocalMethod))
  19447. {
  19448. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  19449. {
  19450. typeDef->PopulateMemberSets();
  19451. BfMethodDef* nextMethod = NULL;
  19452. BfMemberSetEntry* entry = NULL;
  19453. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19454. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19455. while (nextMethod != NULL)
  19456. {
  19457. auto checkMethod = nextMethod;
  19458. nextMethod = nextMethod->mNextWithSameName;
  19459. if (checkMethod == methodDef)
  19460. continue;
  19461. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19462. if (checkMethodInstance == NULL)
  19463. {
  19464. if ((methodDef->mIsNew) && (methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  19465. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  19466. if (checkMethodInstance == NULL)
  19467. continue;
  19468. }
  19469. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  19470. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  19471. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  19472. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  19473. {
  19474. bool canChain = false;
  19475. if ((methodDef->mParams.empty()) &&
  19476. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  19477. {
  19478. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  19479. canChain = true;
  19480. else if (methodDef->mMethodType == BfMethodType_Normal)
  19481. {
  19482. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  19483. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  19484. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  19485. canChain = true;
  19486. }
  19487. }
  19488. if (canChain)
  19489. {
  19490. bool isBetter;
  19491. bool isWorse;
  19492. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  19493. if (isBetter && !isWorse)
  19494. {
  19495. methodInstance->mChainType = BfMethodChainType_ChainHead;
  19496. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  19497. }
  19498. else
  19499. {
  19500. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  19501. methodInstance->mChainType = BfMethodChainType_ChainMember;
  19502. }
  19503. }
  19504. else
  19505. {
  19506. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  19507. continue;
  19508. bool silentlyAllow = false;
  19509. bool extensionWarn = false;
  19510. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  19511. {
  19512. if (typeInstance->IsInterface())
  19513. {
  19514. if (methodDef->mIsOverride)
  19515. silentlyAllow = true;
  19516. }
  19517. else
  19518. {
  19519. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  19520. {
  19521. silentlyAllow = true;
  19522. methodInstance->mIsInnerOverride = true;
  19523. CheckOverridenMethod(methodInstance, checkMethodInstance);
  19524. }
  19525. else if ((methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject) &&
  19526. (!checkMethod->mDeclaringType->IsExtension()))
  19527. {
  19528. foundHiddenMethod = true;
  19529. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  19530. silentlyAllow = true;
  19531. else if (methodDef->mIsNew)
  19532. {
  19533. silentlyAllow = true;
  19534. }
  19535. else
  19536. extensionWarn = true;
  19537. }
  19538. else
  19539. silentlyAllow = true;
  19540. }
  19541. }
  19542. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  19543. silentlyAllow = true;
  19544. if (!silentlyAllow)
  19545. {
  19546. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  19547. {
  19548. auto refNode = methodDef->GetRefNode();
  19549. BfError* bfError;
  19550. if (extensionWarn)
  19551. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  19552. 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'.",
  19553. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  19554. else
  19555. bfError = Fail("Method already declared with the same parameter types", refNode, true);
  19556. if (bfError != NULL)
  19557. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  19558. }
  19559. }
  19560. }
  19561. }
  19562. }
  19563. }
  19564. // Virtual methods give their error while slotting
  19565. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  19566. (!methodDef->mIsLocalMethod) &&
  19567. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  19568. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  19569. {
  19570. auto baseType = typeInstance->mBaseType;
  19571. while (baseType != NULL)
  19572. {
  19573. auto baseTypeDef = baseType->mTypeDef;
  19574. baseTypeDef->PopulateMemberSets();
  19575. BfMethodDef* checkMethod = NULL;
  19576. BfMemberSetEntry* entry = NULL;
  19577. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19578. checkMethod = (BfMethodDef*)entry->mMemberDef;
  19579. while (checkMethod != NULL)
  19580. {
  19581. if (checkMethod->mMethodDeclaration == NULL)
  19582. continue;
  19583. if (baseType->mMethodInstanceGroups.size() == 0)
  19584. {
  19585. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  19586. break;
  19587. }
  19588. if (checkMethod == methodDef)
  19589. continue;
  19590. if (checkMethod->mName != methodDef->mName)
  19591. continue;
  19592. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  19593. if (checkMethodInstance != NULL)
  19594. {
  19595. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  19596. (checkMethod->mProtection != BfProtection_Private) &&
  19597. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  19598. {
  19599. if (!methodDef->mIsNew)
  19600. {
  19601. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  19602. if (refNode != NULL)
  19603. {
  19604. 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?
  19605. if (bfError != NULL)
  19606. bfError->mIsPersistent = true;
  19607. }
  19608. }
  19609. foundHiddenMethod = true;
  19610. break;
  19611. }
  19612. }
  19613. checkMethod = checkMethod->mNextWithSameName;
  19614. }
  19615. if (foundHiddenMethod)
  19616. break;
  19617. baseType = baseType->mBaseType;
  19618. }
  19619. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  19620. {
  19621. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19622. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  19623. methodDeclaration->mNewSpecifier;
  19624. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  19625. }
  19626. }
  19627. }
  19628. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  19629. {
  19630. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  19631. Fail("No suitable method found to override", virtualToken, true);
  19632. else
  19633. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  19634. }
  19635. else if (methodDef->mIsVirtual)
  19636. {
  19637. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  19638. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  19639. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  19640. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  19641. }
  19642. mCompiler->mStats.mMethodDeclarations++;
  19643. mCompiler->UpdateCompletion();
  19644. }
  19645. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  19646. {
  19647. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  19648. auto typeInstance = mCurTypeInstance;
  19649. auto methodDef = methodInstance->mMethodDef;
  19650. int virtualMethodMatchIdx = -1;
  19651. if (typeInstance->mHotTypeData != NULL)
  19652. {
  19653. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  19654. {
  19655. BF_ASSERT(mCompiler->IsHotCompile());
  19656. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  19657. // may slot this override anyway (?)
  19658. int vTableStart = 0;
  19659. auto implBaseType = typeInstance->GetImplBaseType();
  19660. if (implBaseType != NULL)
  19661. vTableStart = implBaseType->mVirtualMethodTableSize;
  19662. StringT<128> mangledName;
  19663. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  19664. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  19665. {
  19666. // O(1) checking when virtual methods haven't changed
  19667. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  19668. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  19669. if (mangledName == entry.mFuncName)
  19670. {
  19671. virtualMethodMatchIdx = vTableStart + checkIdx;
  19672. break;
  19673. }
  19674. }
  19675. if (virtualMethodMatchIdx != -1)
  19676. {
  19677. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19678. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  19679. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  19680. }
  19681. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  19682. }
  19683. }
  19684. if (virtualMethodMatchIdx == -1)
  19685. {
  19686. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  19687. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  19688. typeInstance->mVirtualMethodTable.push_back(entry);
  19689. }
  19690. }
  19691. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  19692. {
  19693. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  19694. {
  19695. // When we provide an extension override in the same project a root type override
  19696. isBetter = true;
  19697. isWorse = false;
  19698. }
  19699. else
  19700. {
  19701. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  19702. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  19703. }
  19704. }
  19705. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  19706. {
  19707. BP_ZONE("BfModule::SlotVirtualMethod");
  19708. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  19709. return false;
  19710. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  19711. {
  19712. if (!mCompiler->mOptions.mAllowHotSwapping)
  19713. return;
  19714. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  19715. return;
  19716. if (methodInstance->mHotMethod == NULL)
  19717. CheckHotMethod(methodInstance, "");
  19718. if (methodInstance->mHotMethod == NULL)
  19719. return;
  19720. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  19721. if (declMethodInstance->mHotMethod == NULL)
  19722. CheckHotMethod(declMethodInstance, "");
  19723. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  19724. virtualDecl->mRefCount++;
  19725. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  19726. };
  19727. auto typeInstance = mCurTypeInstance;
  19728. auto typeDef = typeInstance->mTypeDef;
  19729. auto methodDef = methodInstance->mMethodDef;
  19730. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19731. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  19732. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19733. if (methodInstance->mIsInnerOverride)
  19734. return false;
  19735. BfAstNode* declaringNode = methodDeclaration;
  19736. if (propertyMethodDeclaration != NULL)
  19737. declaringNode = propertyMethodDeclaration->mNameNode;
  19738. BfMethodInstance* methodOverriden = NULL;
  19739. bool usedMethod = false;
  19740. BfTokenNode* virtualToken = NULL;
  19741. if (propertyDeclaration != NULL)
  19742. virtualToken = propertyDeclaration->mVirtualSpecifier;
  19743. else if (methodDeclaration != NULL)
  19744. virtualToken = methodDeclaration->mVirtualSpecifier;
  19745. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  19746. {
  19747. //Fail: Static members cannot be marked as override, virtual, or abstract
  19748. }
  19749. else if (methodDef->mIsVirtual)
  19750. {
  19751. if (mCompiler->IsHotCompile())
  19752. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  19753. BfTypeInstance* checkBase = typeInstance;
  19754. // If we are in an extension, look in ourselves first
  19755. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  19756. checkBase = checkBase->mBaseType;
  19757. if (typeInstance->IsValueType())
  19758. {
  19759. if (typeInstance->mBaseType == NULL)
  19760. return false; // It's actually ValueType
  19761. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  19762. if (!methodDef->mIsOverride)
  19763. {
  19764. Fail("Structs cannot have virtual methods", virtualToken, true);
  19765. return false;
  19766. }
  19767. checkBase = mContext->mBfObjectType;
  19768. if (checkBase->mVirtualMethodTableSize == 0)
  19769. PopulateType(checkBase, BfPopulateType_Full);
  19770. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  19771. return false; // System circular ref, don't do struct checking on those
  19772. }
  19773. int virtualMethodMatchIdx = -1;
  19774. bool hadHidingError = false;
  19775. BfMethodInstance* bestOverrideMethodInstance = NULL;
  19776. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  19777. int bestOverrideMethodIdx = -1;
  19778. int ambiguousOverrideMethodIdx = -1;
  19779. if (checkBase != NULL)
  19780. {
  19781. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19782. auto lookupType = checkBase;
  19783. while (lookupType != NULL)
  19784. {
  19785. lookupType->mTypeDef->PopulateMemberSets();
  19786. BfMethodDef* nextMethodDef = NULL;
  19787. BfMemberSetEntry* entry;
  19788. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  19789. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  19790. while (nextMethodDef != NULL)
  19791. {
  19792. auto checkMethodDef = nextMethodDef;
  19793. nextMethodDef = nextMethodDef->mNextWithSameName;
  19794. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  19795. continue;
  19796. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  19797. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  19798. continue;
  19799. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  19800. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  19801. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  19802. {
  19803. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  19804. continue;
  19805. }
  19806. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19807. if (baseMethodInstance == NULL)
  19808. {
  19809. AssertErrorState();
  19810. continue;
  19811. }
  19812. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  19813. {
  19814. if (methodDef->mIsOverride)
  19815. {
  19816. BfMethodInstance* checkMethodInstance;
  19817. if (typeInstance->IsValueType())
  19818. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19819. else
  19820. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19821. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  19822. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  19823. continue;
  19824. if (bestOverrideMethodInstance != NULL)
  19825. {
  19826. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  19827. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  19828. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  19829. if (isBetter == isWorse)
  19830. {
  19831. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  19832. }
  19833. else
  19834. {
  19835. if (isWorse)
  19836. continue;
  19837. ambiguousOverrideMethodInstance = NULL;
  19838. }
  19839. }
  19840. bestOverrideMethodInstance = checkMethodInstance;
  19841. bestOverrideMethodIdx = checkMethodIdx;
  19842. }
  19843. else
  19844. {
  19845. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  19846. {
  19847. if (!hadHidingError)
  19848. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  19849. hadHidingError = true;
  19850. }
  19851. }
  19852. }
  19853. }
  19854. lookupType = lookupType->mBaseType;
  19855. }
  19856. }
  19857. //TODO:
  19858. if ((checkBase != NULL)
  19859. && (false)
  19860. )
  19861. {
  19862. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19863. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  19864. {
  19865. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  19866. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  19867. {
  19868. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  19869. continue;
  19870. }
  19871. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19872. if (baseMethodInstance == NULL)
  19873. {
  19874. AssertErrorState();
  19875. continue;
  19876. }
  19877. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  19878. {
  19879. if (methodDef->mIsOverride)
  19880. {
  19881. BfMethodInstance* checkMethodInstance;
  19882. if (typeInstance->IsValueType())
  19883. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19884. else
  19885. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  19886. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  19887. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  19888. continue;
  19889. if (bestOverrideMethodInstance != NULL)
  19890. {
  19891. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  19892. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  19893. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  19894. if (isBetter == isWorse)
  19895. {
  19896. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  19897. }
  19898. else
  19899. {
  19900. if (isWorse)
  19901. continue;
  19902. ambiguousOverrideMethodInstance = NULL;
  19903. }
  19904. }
  19905. bestOverrideMethodInstance = checkMethodInstance;
  19906. bestOverrideMethodIdx = checkMethodIdx;
  19907. }
  19908. else
  19909. {
  19910. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  19911. {
  19912. if (!hadHidingError)
  19913. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  19914. hadHidingError = true;
  19915. }
  19916. }
  19917. }
  19918. }
  19919. }
  19920. if (bestOverrideMethodInstance != NULL)
  19921. {
  19922. if (ambiguousOverrideMethodInstance != NULL)
  19923. {
  19924. bool allow = false;
  19925. // 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.
  19926. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  19927. bool canSeeEachOther = false;
  19928. //
  19929. {
  19930. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  19931. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19932. canSeeEachOther = true;
  19933. }
  19934. //
  19935. {
  19936. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  19937. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19938. canSeeEachOther = true;
  19939. }
  19940. if (!canSeeEachOther)
  19941. {
  19942. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  19943. }
  19944. else
  19945. {
  19946. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  19947. if (error != NULL)
  19948. {
  19949. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  19950. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  19951. }
  19952. }
  19953. }
  19954. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19955. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  19956. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  19957. {
  19958. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  19959. {
  19960. BfTypeReference* returnTypeRef;
  19961. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19962. {
  19963. returnTypeRef = propertyDeclaration->mTypeRef;
  19964. Fail("Property differs from overridden property by type", returnTypeRef, true);
  19965. }
  19966. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19967. {
  19968. returnTypeRef = methodDeclaration->mReturnType;
  19969. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  19970. }
  19971. else
  19972. {
  19973. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  19974. }
  19975. return usedMethod;
  19976. }
  19977. }
  19978. if (methodDef->mIsOverride)
  19979. {
  19980. // We can have multiple matches when a virtual method is used to implement interface methods
  19981. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  19982. // vtable entries for this method signature
  19983. virtualMethodMatchIdx = bestOverrideMethodIdx;
  19984. if (!typeInstance->IsValueType())
  19985. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19986. if (typeInstance->IsValueType())
  19987. {
  19988. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19989. }
  19990. else
  19991. {
  19992. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19993. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  19994. BfMethodInstance* setMethodInstance = methodInstance;
  19995. bool doOverride = false;
  19996. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19997. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  19998. {
  19999. methodOverriden = overridenRef;
  20000. doOverride = true;
  20001. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  20002. {
  20003. bool isBetter = false;
  20004. bool isWorse = false;
  20005. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  20006. if (isBetter == isWorse)
  20007. {
  20008. // We have to resolve later per-project
  20009. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  20010. {
  20011. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  20012. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  20013. }
  20014. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  20015. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  20016. doOverride = false;
  20017. }
  20018. else
  20019. {
  20020. if ((isBetter) && (ambiguityContext != NULL))
  20021. {
  20022. ambiguityContext->Remove(virtualMethodMatchIdx);
  20023. }
  20024. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  20025. {
  20026. if (preferRootDefinition)
  20027. {
  20028. // Leave the master GCMarkMember
  20029. isBetter = false;
  20030. isWorse = true;
  20031. }
  20032. }
  20033. doOverride = isBetter;
  20034. }
  20035. }
  20036. }
  20037. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  20038. {
  20039. methodOverriden = overridenRef;
  20040. doOverride = true;
  20041. }
  20042. if (doOverride)
  20043. {
  20044. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  20045. _AddVirtualDecl(declMethodInstance);
  20046. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  20047. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  20048. }
  20049. }
  20050. if (methodOverriden != NULL)
  20051. {
  20052. CheckOverridenMethod(methodInstance, methodOverriden);
  20053. }
  20054. }
  20055. }
  20056. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  20057. {
  20058. if (methodDef->mIsOverride)
  20059. {
  20060. BfTokenNode* overrideToken = NULL;
  20061. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20062. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  20063. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20064. overrideToken = methodDeclaration->mVirtualSpecifier;
  20065. if (overrideToken != NULL)
  20066. {
  20067. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  20068. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  20069. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  20070. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  20071. else
  20072. Fail("No suitable method found to override", overrideToken, true);
  20073. }
  20074. return usedMethod;
  20075. }
  20076. UniqueSlotVirtualMethod(methodInstance);
  20077. }
  20078. else
  20079. usedMethod = true;
  20080. if (typeInstance->IsValueType())
  20081. return usedMethod;
  20082. }
  20083. bool foundInterface = false;
  20084. bool hadAnyMatch = false;
  20085. // See if this method matches interfaces
  20086. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  20087. {
  20088. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  20089. if (ifaceInst->IsIncomplete())
  20090. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  20091. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  20092. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  20093. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  20094. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  20095. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  20096. continue;
  20097. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  20098. continue;
  20099. bool hadMatch = false;
  20100. BfMethodInstance* hadNameMatch = NULL;
  20101. BfType* expectedReturnType = NULL;
  20102. bool showedError = false;
  20103. // We go through our VTable looking for NULL entries within the interface sections
  20104. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  20105. // because a normal method declared in this type could have matched earlier
  20106. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  20107. ifaceInst->mTypeDef->PopulateMemberSets();
  20108. BfMethodDef* checkMethodDef = NULL;
  20109. BfMemberSetEntry* entry;
  20110. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  20111. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  20112. while (checkMethodDef != NULL)
  20113. {
  20114. int iMethodIdx = checkMethodDef->mIdx;
  20115. int iTableIdx = iMethodIdx + startIdx;
  20116. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  20117. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  20118. bool storeIFaceMethod = false;
  20119. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  20120. {
  20121. checkMethodDef = checkMethodDef->mNextWithSameName;
  20122. continue;
  20123. }
  20124. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  20125. auto iMethodInst = iMethodGroup.mDefault;
  20126. if (iMethodInst == NULL)
  20127. {
  20128. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  20129. AssertErrorState();
  20130. checkMethodDef = checkMethodDef->mNextWithSameName;
  20131. continue;
  20132. }
  20133. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  20134. hadNameMatch = iMethodInst;
  20135. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  20136. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  20137. {
  20138. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  20139. }
  20140. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  20141. {
  20142. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  20143. {
  20144. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  20145. {
  20146. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  20147. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  20148. if (error != NULL)
  20149. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  20150. showedError = true;
  20151. }
  20152. }
  20153. }
  20154. if (doesMethodSignatureMatch)
  20155. {
  20156. usedMethod = true;
  20157. hadMatch = true;
  20158. hadAnyMatch = true;
  20159. storeIFaceMethod = true;
  20160. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  20161. {
  20162. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  20163. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  20164. {
  20165. // When autocompletion regenerates a single method body but not the whole type then
  20166. // we will see ourselves in the vtable already
  20167. return usedMethod;
  20168. }
  20169. bool isBetter = false;
  20170. bool isWorse = false;
  20171. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  20172. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  20173. if (isBetter == isWorse)
  20174. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  20175. if (isBetter == isWorse)
  20176. {
  20177. if (ambiguityContext != NULL)
  20178. {
  20179. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  20180. }
  20181. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  20182. storeIFaceMethod = true;
  20183. }
  20184. else
  20185. {
  20186. if ((isBetter) && (ambiguityContext != NULL))
  20187. ambiguityContext->Remove(~iTableIdx);
  20188. storeIFaceMethod = isBetter;
  20189. }
  20190. }
  20191. }
  20192. if (storeIFaceMethod)
  20193. {
  20194. if (methodInstance->GetNumGenericParams() != 0)
  20195. _AddVirtualDecl(iMethodInst);
  20196. *iMethodPtr = methodInstance;
  20197. }
  20198. checkMethodDef = checkMethodDef->mNextWithSameName;
  20199. }
  20200. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  20201. {
  20202. if (expectedReturnType != NULL)
  20203. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  20204. else if (hadNameMatch != NULL)
  20205. {
  20206. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  20207. if (error != NULL)
  20208. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  20209. }
  20210. else
  20211. {
  20212. auto propertyDecl = methodDef->GetPropertyDeclaration();
  20213. if (propertyDecl != NULL)
  20214. {
  20215. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  20216. String name;
  20217. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  20218. name = "this[]";
  20219. else if (propertyDecl->mNameNode != NULL)
  20220. propertyDecl->mNameNode->ToString(name);
  20221. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  20222. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  20223. }
  20224. else
  20225. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  20226. }
  20227. }
  20228. }
  20229. // Any overriden virtual methods that were used in interfaces also need to be replaced
  20230. if (methodOverriden != NULL)
  20231. {
  20232. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  20233. {
  20234. if (methodEntry.mMethodRef == methodOverriden)
  20235. methodEntry.mMethodRef = methodInstance;
  20236. }
  20237. }
  20238. return usedMethod;
  20239. }
  20240. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  20241. {
  20242. auto methodDef = methodInstance->mMethodDef;
  20243. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  20244. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  20245. {
  20246. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  20247. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  20248. BfAstNode* protectionRefNode = NULL;
  20249. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  20250. {
  20251. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  20252. if (protectionRefNode == NULL)
  20253. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  20254. if (protectionRefNode == NULL)
  20255. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  20256. }
  20257. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20258. {
  20259. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  20260. if (protectionRefNode == NULL)
  20261. protectionRefNode = methodDeclaration->mNameNode;
  20262. }
  20263. if (protectionRefNode != NULL)
  20264. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  20265. }
  20266. }
  20267. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  20268. {
  20269. auto typeInstance = mCurTypeInstance;
  20270. auto methodDef = methodInstance->mMethodDef;
  20271. if (methodDef->mMethodType == BfMethodType_Ctor)
  20272. return true;
  20273. bool foundOverride = false;
  20274. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  20275. {
  20276. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20277. BfAstNode* refNode = NULL;
  20278. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  20279. refNode = propertyDeclaration->mProtectionSpecifier;
  20280. else if (methodDeclaration != NULL)
  20281. refNode = methodDeclaration->mProtectionSpecifier;
  20282. Fail("Private interface methods must provide a body", refNode);
  20283. }
  20284. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  20285. {
  20286. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  20287. }
  20288. BfAstNode* declaringNode = methodDef->GetRefNode();
  20289. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  20290. {
  20291. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  20292. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  20293. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  20294. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  20295. continue;
  20296. ifaceInst->mTypeDef->PopulateMemberSets();
  20297. BfMethodDef* nextMethod = NULL;
  20298. BfMemberSetEntry* entry = NULL;
  20299. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20300. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20301. while (nextMethod != NULL)
  20302. {
  20303. auto checkMethod = nextMethod;
  20304. nextMethod = nextMethod->mNextWithSameName;
  20305. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20306. if (ifaceMethod == NULL)
  20307. continue;
  20308. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  20309. {
  20310. if (methodDef->mIsOverride)
  20311. {
  20312. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  20313. {
  20314. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  20315. if (error != NULL)
  20316. {
  20317. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  20318. }
  20319. }
  20320. foundOverride = true;
  20321. }
  20322. else if (!methodDef->mIsNew)
  20323. {
  20324. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  20325. }
  20326. }
  20327. }
  20328. }
  20329. if ((methodDef->mIsOverride) && (!foundOverride))
  20330. {
  20331. // This allows us to declare a method in the base definition or in an extension and then provide
  20332. // an implementation in a more-specific extension
  20333. typeInstance->mTypeDef->PopulateMemberSets();
  20334. BfMethodDef* nextMethod = NULL;
  20335. BfMemberSetEntry* entry = NULL;
  20336. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  20337. nextMethod = (BfMethodDef*)entry->mMemberDef;
  20338. while (nextMethod != NULL)
  20339. {
  20340. auto checkMethod = nextMethod;
  20341. nextMethod = nextMethod->mNextWithSameName;
  20342. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  20343. if (ifaceMethod == NULL)
  20344. continue;
  20345. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  20346. continue;
  20347. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  20348. {
  20349. foundOverride = true;
  20350. }
  20351. }
  20352. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  20353. // {
  20354. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  20355. // if (ifaceMethod == NULL)
  20356. // continue;
  20357. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  20358. // continue;
  20359. //
  20360. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  20361. // {
  20362. // foundOverride = true;
  20363. // }
  20364. // }
  20365. }
  20366. if (methodDef->mIsOverride)
  20367. {
  20368. if (!foundOverride)
  20369. {
  20370. BfTokenNode* overrideToken = NULL;
  20371. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  20372. overrideToken = propertyDeclaration->mVirtualSpecifier;
  20373. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  20374. overrideToken = methodDeclaration->mVirtualSpecifier;
  20375. if (overrideToken != NULL)
  20376. {
  20377. Fail("No suitable method found to override", overrideToken, true);
  20378. }
  20379. else
  20380. {
  20381. // Possible cause - DTOR with params
  20382. AssertErrorState();
  20383. }
  20384. }
  20385. return true;
  20386. }
  20387. // Generic methods can't be called virtually
  20388. if (methodInstance->GetNumGenericParams() != 0)
  20389. return true;
  20390. // Only public methods can be called virtually
  20391. if (methodDef->mProtection != BfProtection_Public)
  20392. return true;
  20393. UniqueSlotVirtualMethod(methodInstance);
  20394. return true;
  20395. }
  20396. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  20397. {
  20398. if (methodInstance->mMethodInfoEx == NULL)
  20399. return;
  20400. int wantMinDepth = -1;
  20401. if (mCurTypeInstance != NULL)
  20402. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  20403. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  20404. {
  20405. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  20406. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  20407. wantMinDepth = wantTypeMinDepth;
  20408. }
  20409. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  20410. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  20411. }
  20412. void BfModule::DbgFinish()
  20413. {
  20414. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  20415. return;
  20416. if (mAwaitingInitFinish)
  20417. FinishInit();
  20418. if (mHasForceLinkMarker)
  20419. return;
  20420. String markerName;
  20421. BfIRValue linkMarker;
  20422. if (mBfIRBuilder->DbgHasInfo())
  20423. {
  20424. bool needForceLinking = false;
  20425. for (auto& ownedType : mOwnedTypeInstances)
  20426. {
  20427. bool hasConfirmedReference = false;
  20428. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  20429. {
  20430. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  20431. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  20432. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  20433. (methodInstGroup.mHasEmittedReference))
  20434. {
  20435. hasConfirmedReference = true;
  20436. }
  20437. }
  20438. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  20439. needForceLinking = true;
  20440. }
  20441. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  20442. {
  20443. BfMethodState methodState;
  20444. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20445. methodState.mTempKind = BfMethodState::TempKind_Static;
  20446. mHasForceLinkMarker = true;
  20447. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  20448. SizedArray<BfIRType, 0> paramTypes;
  20449. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  20450. String linkName = "FORCELINKMOD_" + mModuleName;
  20451. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  20452. mBfIRBuilder->SetActiveFunction(func);
  20453. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  20454. mBfIRBuilder->SetInsertPoint(entryBlock);
  20455. auto firstType = mOwnedTypeInstances[0];
  20456. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  20457. SizedArray<BfIRMDNode, 1> diParamTypes;
  20458. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  20459. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  20460. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  20461. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  20462. methodState.mCurScope->mDIScope = diScope;
  20463. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  20464. SizedArray<BfIRValue, 8> args;
  20465. BfExprEvaluator exprEvaluator(this);
  20466. for (auto& ownedType : mOwnedTypeInstances)
  20467. {
  20468. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  20469. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  20470. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  20471. }
  20472. mBfIRBuilder->CreateRetVoid();
  20473. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  20474. }
  20475. }
  20476. }
  20477. bool BfModule::Finish()
  20478. {
  20479. BP_ZONE("BfModule::Finish");
  20480. BfLogSysM("BfModule finish: %p\n", this);
  20481. if (mHadBuildError)
  20482. {
  20483. // Don't AssertErrorState here, this current pass may not have failed but
  20484. // the module was still queued in mFinishedModuleWorkList
  20485. ClearModule();
  20486. return true;
  20487. }
  20488. if (mUsedSlotCount != -1)
  20489. {
  20490. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  20491. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  20492. }
  20493. BF_ASSERT(mAddedToCount);
  20494. mAddedToCount = false;
  20495. mAwaitingFinish = false;
  20496. mCompiler->mStats.mModulesFinished++;
  20497. if (HasCompiledOutput())
  20498. {
  20499. DbgFinish();
  20500. if (mAwaitingInitFinish)
  20501. FinishInit();
  20502. for (auto ownedTypeInst : mOwnedTypeInstances)
  20503. {
  20504. // Generate dbg info and add global variables if we haven't already
  20505. mBfIRBuilder->PopulateType(ownedTypeInst);
  20506. }
  20507. if (mBfIRBuilder->DbgHasInfo())
  20508. {
  20509. mBfIRBuilder->DbgFinalize();
  20510. }
  20511. String objOutputPath;
  20512. String irOutputPath;
  20513. mIsModuleMutable = false;
  20514. //mOutFileNames.Clear();
  20515. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  20516. bool writeModule = mBfIRBuilder->HasExports();
  20517. String outputPath;
  20518. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  20519. auto& compilerOpts = mCompiler->mOptions;
  20520. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  20521. auto moduleOptions = GetModuleOptions();
  20522. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  20523. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  20524. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  20525. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  20526. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  20527. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  20528. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  20529. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  20530. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  20531. bool allowWriteToLib = true;
  20532. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  20533. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  20534. {
  20535. codeGenOptions.mWriteToLib = true;
  20536. mWroteToLib = true;
  20537. }
  20538. else
  20539. {
  20540. mWroteToLib = false;
  20541. }
  20542. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  20543. {
  20544. outputPath = mModuleName;
  20545. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  20546. BfModuleFileName moduleFileName;
  20547. if (mParentModule != NULL)
  20548. {
  20549. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  20550. {
  20551. if (checkPair.mValue == this)
  20552. moduleFileName.mProjects = checkPair.mKey;
  20553. }
  20554. }
  20555. moduleFileName.mProjects.Add(mProject);
  20556. if (fileIdx > 0)
  20557. outputPath += StrFormat("@%d", fileIdx + 1);
  20558. if (mCompiler->mOptions.mWriteIR)
  20559. irOutputPath = outputPath + ".ll";
  20560. if (mCompiler->mOptions.mGenerateObj)
  20561. {
  20562. objOutputPath = outputPath + BF_OBJ_EXT;
  20563. moduleFileName.mFileName = objOutputPath;
  20564. }
  20565. else if (mCompiler->mOptions.mWriteIR)
  20566. {
  20567. moduleFileName.mFileName = irOutputPath;
  20568. }
  20569. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  20570. {
  20571. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  20572. }
  20573. moduleFileName.mModuleWritten = writeModule;
  20574. moduleFileName.mWroteToLib = mWroteToLib;
  20575. if (!mOutFileNames.Contains(moduleFileName))
  20576. mOutFileNames.Add(moduleFileName);
  20577. }
  20578. if (mCompiler->IsHotCompile())
  20579. {
  20580. codeGenOptions.mIsHotCompile = true;
  20581. if (mParentModule != NULL)
  20582. mParentModule->mHadHotObjectWrites = true;
  20583. mHadHotObjectWrites = true;
  20584. }
  20585. //TODO: Testing VDATA
  20586. /*if (mModuleName == "vdata")
  20587. {
  20588. codeGenOptions.mOptLevel = 4;
  20589. }*/
  20590. codeGenOptions.GenerateHash();
  20591. BP_ZONE("BfModule::Finish.WriteObjectFile");
  20592. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  20593. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  20594. mLastModuleWrittenRevision = mCompiler->mRevision;
  20595. }
  20596. else
  20597. {
  20598. for (auto type : mOwnedTypeInstances)
  20599. {
  20600. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  20601. }
  20602. }
  20603. for (auto& specModulePair : mSpecializedMethodModules)
  20604. {
  20605. auto specModule = specModulePair.mValue;
  20606. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  20607. {
  20608. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  20609. }
  20610. }
  20611. CleanupFileInstances();
  20612. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  20613. return true;
  20614. }
  20615. void BfModule::ReportMemory(MemReporter* memReporter)
  20616. {
  20617. memReporter->Add(sizeof(BfModule));
  20618. if (mBfIRBuilder != NULL)
  20619. {
  20620. memReporter->BeginSection("IRBuilder_ConstData");
  20621. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  20622. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  20623. memReporter->EndSection();
  20624. memReporter->BeginSection("IRBuilder_BFIR");
  20625. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  20626. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  20627. memReporter->EndSection();
  20628. memReporter->Add(sizeof(BfIRBuilder));
  20629. }
  20630. memReporter->BeginSection("FileInstanceMap");
  20631. memReporter->AddMap(mFileInstanceMap);
  20632. memReporter->AddMap(mNamedFileInstanceMap);
  20633. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  20634. memReporter->EndSection();
  20635. memReporter->AddVec(mOwnedTypeInstances, false);
  20636. memReporter->AddVec(mSpecializedMethodModules, false);
  20637. memReporter->AddVec(mOutFileNames, false);
  20638. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  20639. memReporter->AddMap(mInterfaceSlotRefs, false);
  20640. memReporter->AddMap(mStaticFieldRefs, false);
  20641. memReporter->AddMap(mClassVDataRefs, false);
  20642. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  20643. memReporter->AddMap(mTypeDataRefs, false);
  20644. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  20645. memReporter->AddMap(mDeferredMethodCallData, false);
  20646. memReporter->AddHashSet(mDeferredMethodIds, false);
  20647. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  20648. }
  20649. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  20650. // be transient through the next compile
  20651. void BfModule::ClearModuleData(bool clearTransientData)
  20652. {
  20653. BfLogSysM("ClearModuleData %p\n", this);
  20654. if (mAddedToCount)
  20655. {
  20656. mCompiler->mStats.mModulesFinished++;
  20657. mAddedToCount = false;
  20658. }
  20659. mDICompileUnit = BfIRMDNode();
  20660. mIsModuleMutable = false;
  20661. if (clearTransientData)
  20662. mIncompleteMethodCount = 0;
  20663. mHasGenericMethods = false;
  20664. // We don't want to clear these because we want it to persist through module extensions-
  20665. // otherwise we may think an extension succeeds even though the base module failed
  20666. //mHadBuildError = false;
  20667. //mHadBuildWarning = false;
  20668. mClassVDataRefs.Clear();
  20669. mClassVDataExtRefs.Clear();
  20670. for (auto& kv : mTypeDataRefs)
  20671. kv.mValue = BfIRValue();
  20672. mStringCharPtrPool.Clear();
  20673. mStringObjectPool.Clear();
  20674. mStaticFieldRefs.Clear();
  20675. BF_ASSERT(!mIgnoreErrors);
  20676. for (auto prevIRBuilder : mPrevIRBuilders)
  20677. delete prevIRBuilder;
  20678. mPrevIRBuilders.Clear();
  20679. for (auto& specPair : mSpecializedMethodModules)
  20680. {
  20681. auto specModule = specPair.mValue;
  20682. specModule->ClearModuleData();
  20683. }
  20684. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  20685. mBuiltInFuncs[i] = BfIRFunction();
  20686. if (mNextAltModule != NULL)
  20687. mNextAltModule->ClearModuleData();
  20688. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  20689. delete mBfIRBuilder;
  20690. mBfIRBuilder = NULL;
  20691. mWantsIRIgnoreWrites = false;
  20692. }
  20693. void BfModule::DisownMethods()
  20694. {
  20695. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  20696. mBuiltInFuncs[i] = BfIRFunction();
  20697. BfModule* methodModule = this;
  20698. if (mParentModule != NULL)
  20699. methodModule = mParentModule;
  20700. for (auto typeInst : methodModule->mOwnedTypeInstances)
  20701. {
  20702. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  20703. {
  20704. if (methodGroup.mDefault != NULL)
  20705. {
  20706. if (methodGroup.mDefault->mIRFunction)
  20707. {
  20708. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  20709. if (methodGroup.mDefault->mDeclModule == this)
  20710. {
  20711. methodGroup.mDefault->mIRFunction = BfIRFunction();
  20712. }
  20713. }
  20714. }
  20715. if (methodGroup.mMethodSpecializationMap != NULL)
  20716. {
  20717. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  20718. {
  20719. auto methodInstance = mapPair.mValue;
  20720. if (methodInstance->mDeclModule == this)
  20721. {
  20722. methodInstance->mIRFunction = BfIRFunction();
  20723. }
  20724. }
  20725. }
  20726. }
  20727. }
  20728. }
  20729. void BfModule::ClearModule()
  20730. {
  20731. ClearModuleData();
  20732. DisownMethods();
  20733. for (auto& specPair : mSpecializedMethodModules)
  20734. {
  20735. auto specModule = specPair.mValue;
  20736. specModule->ClearModule();
  20737. }
  20738. if (mNextAltModule != NULL)
  20739. mNextAltModule->ClearModule();
  20740. }