BfModule.cpp 742 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mReportErrors = true;
  698. mIsInsideAutoComplete = false;
  699. mIsDeleting = false;
  700. mSkipInnerLookup = false;
  701. mIsHotModule = false;
  702. mSetIllegalSrcPosition = false;
  703. mNoResolveGenericParams = false;
  704. mWroteToLib = false;
  705. mContext = context;
  706. mCompiler = context->mCompiler;
  707. mSystem = mCompiler->mSystem;
  708. mProject = NULL;
  709. mCurMethodState = NULL;
  710. mAttributeState = NULL;
  711. mCurLocalMethodId = 0;
  712. mParentNodeEntry = NULL;
  713. mRevision = -1;
  714. mRebuildIdx = 0;
  715. mLastModuleWrittenRevision = 0;
  716. mIsModuleMutable = false;
  717. mExtensionCount = 0;
  718. mIncompleteMethodCount = 0;
  719. mOnDemandMethodCount = 0;
  720. mHasGenericMethods = false;
  721. mCurMethodInstance = NULL;
  722. mCurTypeInstance = NULL;
  723. mAwaitingInitFinish = false;
  724. mAwaitingFinish = false;
  725. mHasFullDebugInfo = false;
  726. mHadHotObjectWrites = false;
  727. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  728. mBuiltInFuncs[i] = BfIRFunction();
  729. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  730. }
  731. void BfReportMemory();
  732. BfModule::~BfModule()
  733. {
  734. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  735. if (!mIsDeleting)
  736. RemoveModuleData();
  737. }
  738. void BfModule::RemoveModuleData()
  739. {
  740. BF_ASSERT(!mIsDeleting);
  741. if (!mModuleName.empty())
  742. {
  743. // Note: module names not necessarily unique
  744. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  745. }
  746. CleanupFileInstances();
  747. delete mBfIRBuilder;
  748. mBfIRBuilder = NULL;
  749. //delete mCpu;
  750. for (auto prevModule : mPrevIRBuilders)
  751. delete prevModule;
  752. mPrevIRBuilders.Clear();
  753. for (auto& pairVal : mDeferredMethodCallData)
  754. delete pairVal.mValue;
  755. mDeferredMethodCallData.Clear();
  756. mDeferredMethodIds.Clear();
  757. for (auto& specModulePair : mSpecializedMethodModules)
  758. delete specModulePair.mValue;
  759. mSpecializedMethodModules.Clear();
  760. if (mNextAltModule != NULL)
  761. delete mNextAltModule;
  762. mNextAltModule = NULL;
  763. if (mModuleOptions != NULL)
  764. delete mModuleOptions;
  765. mModuleOptions = NULL;
  766. BfReportMemory();
  767. }
  768. void BfModule::Init(bool isFullRebuild)
  769. {
  770. mContext->mFinishedModuleWorkList.Remove(this);
  771. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  772. BF_ASSERT(mIsReified);
  773. if (!mIsScratchModule)
  774. {
  775. mCompiler->mStats.mModulesStarted++;
  776. if (mIsReified)
  777. mCompiler->mStats.mReifiedModuleCount++;
  778. mAddedToCount = true;
  779. }
  780. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  781. mFuncReferences.Clear();
  782. mClassVDataRefs.Clear();
  783. mClassVDataExtRefs.Clear();
  784. //mTypeDataRefs.Clear();
  785. mDbgRawAllocDataRefs.Clear();
  786. CleanupFileInstances();
  787. mStaticFieldRefs.Clear();
  788. //mInterfaceSlotRefs.Clear();
  789. // If we are just doing an extension then the ownede types aren't rebuilt.
  790. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  791. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  792. if (isFullRebuild)
  793. mRevision = mCompiler->mRevision;
  794. BF_ASSERT(mCurTypeInstance == NULL);
  795. mIsModuleMutable = true;
  796. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  797. #ifdef _DEBUG
  798. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  799. #else
  800. EnsureIRBuilder(false);
  801. #endif
  802. mCurMethodState = NULL;
  803. mAwaitingInitFinish = true;
  804. mOnDemandMethodCount = 0;
  805. mAwaitingFinish = false;
  806. mHasForceLinkMarker = false;
  807. mUsedSlotCount = -1;
  808. }
  809. bool BfModule::WantsFinishModule()
  810. {
  811. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  812. }
  813. void BfModule::FinishInit()
  814. {
  815. BF_ASSERT(mAwaitingInitFinish);
  816. auto moduleOptions = GetModuleOptions();
  817. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  818. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  819. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  820. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  821. {
  822. // Og+ requires debug info
  823. moduleOptions.mEmitDebugInfo = 1;
  824. }
  825. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  826. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  827. {
  828. mBfIRBuilder->DbgInit();
  829. }
  830. else
  831. mHasFullDebugInfo = false;
  832. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  833. ((moduleOptions.mEmitDebugInfo != 0)))
  834. {
  835. if (mCompiler->mOptions.IsCodeView())
  836. {
  837. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  838. }
  839. else
  840. {
  841. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  842. }
  843. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  844. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  845. }
  846. mAwaitingInitFinish = false;
  847. }
  848. void BfModule::ReifyModule()
  849. {
  850. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  851. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  852. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  853. mIsReified = true;
  854. mReifyQueued = false;
  855. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  856. mCompiler->mStats.mModulesReified++;
  857. }
  858. void BfModule::UnreifyModule()
  859. {
  860. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  861. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  862. mIsReified = false;
  863. mReifyQueued = false;
  864. StartNewRevision(RebuildKind_None, true);
  865. mCompiler->mStats.mModulesUnreified++;
  866. }
  867. void BfModule::CleanupFileInstances()
  868. {
  869. for (auto& itr : mNamedFileInstanceMap)
  870. {
  871. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  872. delete itr.mValue;
  873. }
  874. mCurFilePosition.mFileInstance = NULL;//
  875. mFileInstanceMap.Clear();
  876. mNamedFileInstanceMap.Clear();
  877. }
  878. void BfModule::Cleanup()
  879. {
  880. CleanupFileInstances();
  881. }
  882. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  883. {
  884. if (HasCompiledOutput())
  885. {
  886. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  887. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  888. {
  889. StartExtension();
  890. }
  891. }
  892. else
  893. {
  894. EnsureIRBuilder();
  895. }
  896. }
  897. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  898. {
  899. BF_ASSERT(!mIsDeleting);
  900. if (mBfIRBuilder == NULL)
  901. {
  902. if ((!mIsScratchModule) && (!mAddedToCount))
  903. {
  904. mCompiler->mStats.mModulesStarted++;
  905. mAddedToCount = true;
  906. }
  907. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  908. /*if (mCompiler->mIsResolveOnly)
  909. BF_ASSERT(mIsResolveOnly);*/
  910. mBfIRBuilder = new BfIRBuilder(this);
  911. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  912. if (mIsScratchModule)
  913. {
  914. mBfIRBuilder->mIgnoreWrites = true;
  915. BF_ASSERT(!dbgVerifyCodeGen);
  916. }
  917. #ifdef _DEBUG
  918. if (mCompiler->mIsResolveOnly)
  919. {
  920. // For "deep" verification testing
  921. /*if (!mIsSpecialModule)
  922. dbgVerifyCodeGen = true;*/
  923. // We only want to turn this off on smaller builds for testing
  924. mBfIRBuilder->mIgnoreWrites = true;
  925. if (dbgVerifyCodeGen)
  926. mBfIRBuilder->mIgnoreWrites = false;
  927. if (!mBfIRBuilder->mIgnoreWrites)
  928. {
  929. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  930. mBfIRBuilder->mDbgVerifyCodeGen = true;
  931. }
  932. }
  933. else if (!mIsReified)
  934. {
  935. mBfIRBuilder->mIgnoreWrites = true;
  936. }
  937. else
  938. {
  939. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  940. // code as we walk the AST
  941. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  942. if (
  943. (mModuleName == "-")
  944. //|| (mModuleName == "Tests_FuncRefs_Class")
  945. //|| (mModuleName == "Tests_FuncRefs")
  946. )
  947. mBfIRBuilder->mDbgVerifyCodeGen = true;
  948. // Just for testing!
  949. //mBfIRBuilder->mIgnoreWrites = true;
  950. }
  951. #else
  952. if (mCompiler->mIsResolveOnly)
  953. {
  954. // Always ignore writes in resolveOnly for release builds
  955. mBfIRBuilder->mIgnoreWrites = true;
  956. }
  957. else
  958. {
  959. // Just for memory testing! This breaks everything.
  960. //mBfIRBuilder->mIgnoreWrites = true;
  961. // For "deep" verification testing
  962. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  963. }
  964. #endif
  965. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  966. }
  967. }
  968. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  969. {
  970. String name = "FORCELINKMOD_" + module->mModuleName;
  971. if (outName != NULL)
  972. *outName = name;
  973. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  974. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  975. }
  976. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  977. {
  978. BP_ZONE("BfModule::StartNewRevision");
  979. // The project MAY be deleted because disabling a project can cause types to be deleted which
  980. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  981. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  982. // Already on new revision?
  983. if ((mRevision == mCompiler->mRevision) && (!force))
  984. return;
  985. mHadBuildError = false;
  986. mHadBuildWarning = false;
  987. mExtensionCount = 0;
  988. mRevision = mCompiler->mRevision;
  989. mRebuildIdx++;
  990. ClearModuleData();
  991. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  992. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  993. mStringPoolRefs.Clear();
  994. mDllImportEntries.Clear();
  995. mImportFileNames.Clear();
  996. for (auto& pairVal : mDeferredMethodCallData)
  997. delete pairVal.mValue;
  998. mDeferredMethodCallData.Clear();
  999. mDeferredMethodIds.Clear();
  1000. mModuleRefs.Clear();
  1001. mOutFileNames.Clear();
  1002. mTypeDataRefs.Clear();
  1003. mInterfaceSlotRefs.Clear();
  1004. if (rebuildKind == BfModule::RebuildKind_None)
  1005. {
  1006. for (auto& specPair : mSpecializedMethodModules)
  1007. {
  1008. auto specModule = specPair.mValue;
  1009. if (specModule->mIsReified != mIsReified)
  1010. {
  1011. if (mIsReified)
  1012. specModule->ReifyModule();
  1013. else
  1014. specModule->UnreifyModule();
  1015. }
  1016. }
  1017. }
  1018. else
  1019. {
  1020. for (auto& specPair : mSpecializedMethodModules)
  1021. {
  1022. auto specModule = specPair.mValue;
  1023. delete specModule;
  1024. }
  1025. }
  1026. mSpecializedMethodModules.Clear();
  1027. delete mNextAltModule;
  1028. mNextAltModule = NULL;
  1029. BF_ASSERT(mModuleOptions == NULL);
  1030. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1031. bool needsTypePopulated = false;
  1032. int oldOnDemandCount = 0;
  1033. // We don't have to rebuild types in the unspecialized module because there is no
  1034. // data that's needed -- their method instances are all NULL and the module
  1035. // doesn't get included in the build
  1036. if (this != mContext->mScratchModule)
  1037. {
  1038. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1039. {
  1040. auto typeInst = mOwnedTypeInstances[typeIdx];
  1041. if (!typeInst->IsDeleting())
  1042. {
  1043. typeInst->mIsReified = mIsReified;
  1044. if (rebuildKind != BfModule::RebuildKind_None)
  1045. {
  1046. if (typeInst->IsOnDemand())
  1047. {
  1048. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1049. if (rebuildKind == BfModule::RebuildKind_All)
  1050. mContext->DeleteType(typeInst);
  1051. else
  1052. {
  1053. RebuildMethods(typeInst);
  1054. }
  1055. }
  1056. else
  1057. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1058. mContext->RebuildType(typeInst, false, false, true);
  1059. //mContext->RebuildType(typeInst, false, false, false);
  1060. }
  1061. else
  1062. {
  1063. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1064. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1065. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1066. {
  1067. oldOnDemandCount++;
  1068. }
  1069. }
  1070. if (typeInst->IsDeleting())
  1071. typeIdx--;
  1072. }
  1073. }
  1074. }
  1075. if (!mIsDeleting)
  1076. Init();
  1077. mOnDemandMethodCount += oldOnDemandCount;
  1078. }
  1079. void BfModule::StartExtension()
  1080. {
  1081. BF_ASSERT(!mIsModuleMutable);
  1082. BfLogSysM("Extension started of module %p\n", this);
  1083. mExtensionCount++;
  1084. if (mBfIRBuilder != NULL)
  1085. mPrevIRBuilders.push_back(mBfIRBuilder);
  1086. mBfIRBuilder = NULL;
  1087. mWantsIRIgnoreWrites = false;
  1088. mFuncReferences.Clear();
  1089. mClassVDataRefs.Clear();
  1090. mClassVDataExtRefs.Clear();
  1091. for (auto& kv : mTypeDataRefs)
  1092. kv.mValue = BfIRValue();
  1093. mDbgRawAllocDataRefs.Clear();
  1094. mStringCharPtrPool.Clear();
  1095. mStringObjectPool.Clear();
  1096. mStaticFieldRefs.Clear();
  1097. for (auto& kv : mInterfaceSlotRefs)
  1098. kv.mValue = BfIRValue();
  1099. mDeferredMethodCallData.Clear();
  1100. mDeferredMethodIds.Clear();
  1101. DisownMethods();
  1102. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1103. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1104. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1105. Init(false);
  1106. if (!wasAwaitingInitFinish)
  1107. FinishInit();
  1108. mOnDemandMethodCount = prevOnDemandMethodCount;
  1109. }
  1110. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1111. {
  1112. BfIRValue vDataValue;
  1113. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1114. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1115. else
  1116. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1117. typeValueParams.push_back(vDataValue);
  1118. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1119. {
  1120. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1121. typeValueParams.push_back(GetDefaultValue(primType));
  1122. }
  1123. }
  1124. BfIRValue BfModule::GetConstValue(int64 val)
  1125. {
  1126. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1127. }
  1128. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1129. {
  1130. BfType* checkType = type;
  1131. if (type->IsTypedPrimitive())
  1132. {
  1133. checkType = type->GetUnderlyingType();
  1134. }
  1135. if (checkType->IsPrimitiveType())
  1136. {
  1137. auto primType = (BfPrimitiveType*)checkType;
  1138. if (checkType->IsFloat())
  1139. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1140. else
  1141. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1142. }
  1143. return BfIRValue();
  1144. }
  1145. BfIRValue BfModule::GetConstValue8(int val)
  1146. {
  1147. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1148. }
  1149. BfIRValue BfModule::GetConstValue32(int32 val)
  1150. {
  1151. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1152. }
  1153. BfIRValue BfModule::GetConstValue64(int64 val)
  1154. {
  1155. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1156. }
  1157. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1158. {
  1159. PopulateType(type, BfPopulateType_Data);
  1160. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1161. if (type->IsTypedPrimitive())
  1162. {
  1163. auto underlyingType = type->GetUnderlyingType();
  1164. if (underlyingType == NULL)
  1165. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1166. return GetDefaultValue(type->GetUnderlyingType());
  1167. }
  1168. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1169. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1170. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1171. if ((type->IsIntegral()) || (type->IsBoolean()))
  1172. {
  1173. auto primType = (BfPrimitiveType*)type;
  1174. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1175. }
  1176. if (type->IsFloat())
  1177. {
  1178. auto primType = (BfPrimitiveType*)type;
  1179. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1180. }
  1181. if (type->IsVoid())
  1182. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1183. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1184. }
  1185. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1186. {
  1187. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1188. if (type->mSize == 0)
  1189. return BfTypedValue(BfIRValue::sValueless, type);
  1190. else
  1191. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1192. }
  1193. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1194. {
  1195. if (type->IsVar())
  1196. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1197. PopulateType(type, BfPopulateType_Data);
  1198. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1199. if (defaultValueKind == BfDefaultValueKind_Undef)
  1200. {
  1201. auto primType = type->ToPrimitiveType();
  1202. if (primType != NULL)
  1203. {
  1204. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1205. }
  1206. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1207. }
  1208. BfTypedValue typedValue;
  1209. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1210. {
  1211. if (type->IsRef())
  1212. {
  1213. BfRefType* refType = (BfRefType*)type;
  1214. BfType* underlyingType = refType->GetUnderlyingType();
  1215. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1216. }
  1217. else
  1218. {
  1219. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1220. }
  1221. if (!mBfIRBuilder->mIgnoreWrites)
  1222. {
  1223. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1224. GetConstValue(type->mSize), type->mAlign);
  1225. }
  1226. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1227. typedValue = LoadValue(typedValue);
  1228. return typedValue;
  1229. }
  1230. if ((type->IsRef()) && (!allowRef))
  1231. {
  1232. BfRefType* refType = (BfRefType*)type;
  1233. BfType* underlyingType = refType->GetUnderlyingType();
  1234. if (underlyingType->IsValuelessType())
  1235. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1236. else
  1237. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1238. }
  1239. else
  1240. {
  1241. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1242. }
  1243. return typedValue;
  1244. }
  1245. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1246. {
  1247. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1248. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1249. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1250. BfIRValue strConstant;
  1251. if (define)
  1252. {
  1253. strConstant = mBfIRBuilder->CreateConstString(str);
  1254. }
  1255. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1256. true, BfIRLinkageType_External,
  1257. strConstant, stringDataName);
  1258. if (define)
  1259. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1260. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1261. }
  1262. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1263. {
  1264. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1265. mBfIRBuilder->PopulateType(stringTypeInst);
  1266. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1267. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1268. BfIRValue stringValData;
  1269. if (define)
  1270. {
  1271. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1272. mStringCharPtrPool[stringId] = stringCharsVal;
  1273. SizedArray<BfIRValue, 8> typeValueParams;
  1274. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1275. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1276. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1277. typeValueParams.clear();
  1278. typeValueParams.push_back(objData);
  1279. if (lenByteCount == 4)
  1280. {
  1281. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1282. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1283. }
  1284. else
  1285. {
  1286. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1287. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1288. }
  1289. typeValueParams.push_back(stringCharsVal); // mPtr
  1290. for (int fieldIdx = 0; fieldIdx < (int)stringTypeInst->mFieldInstances.size(); fieldIdx++)
  1291. {
  1292. auto fieldInstance = &stringTypeInst->mFieldInstances[fieldIdx];
  1293. if (fieldInstance->mDataIdx < 4)
  1294. continue;
  1295. while (fieldInstance->mDataIdx >= typeValueParams.size())
  1296. typeValueParams.Add(BfIRValue());
  1297. typeValueParams[fieldInstance->mDataIdx] = GetDefaultValue(fieldInstance->mResolvedType);
  1298. }
  1299. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1300. }
  1301. mBfIRBuilder->PopulateType(stringTypeInst);
  1302. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1303. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1304. true,
  1305. BfIRLinkageType_External,
  1306. define ? stringValData : BfIRValue(),
  1307. stringObjName);
  1308. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1309. return stringVal;
  1310. }
  1311. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1312. {
  1313. BF_ASSERT(constantStr.IsConst());
  1314. if (constHolder == NULL)
  1315. constHolder = mBfIRBuilder;
  1316. auto constant = constHolder->GetConstant(constantStr);
  1317. if (constant->mTypeCode == BfTypeCode_StringId)
  1318. {
  1319. return constant->mInt32;
  1320. }
  1321. while (constant->mConstType == BfConstType_BitCast)
  1322. {
  1323. auto constBitCast = (BfConstantBitCast*)constant;
  1324. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1325. }
  1326. if (constant->mConstType == BfConstType_GEP32_2)
  1327. {
  1328. auto constGEP = (BfConstantGEP32_2*)constant;
  1329. constant = constHolder->GetConstantById(constGEP->mTarget);
  1330. }
  1331. if (constant->mConstType == BfConstType_GlobalVar)
  1332. {
  1333. auto constGV = (BfGlobalVar*)constant;
  1334. const char* strDataPrefix = "__bfStrData";
  1335. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1336. return atoi(constGV->mName + strlen(strDataPrefix));
  1337. const char* strObjPrefix = "__bfStrObj";
  1338. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1339. return atoi(constGV->mName + strlen(strObjPrefix));
  1340. }
  1341. return -1;
  1342. }
  1343. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1344. {
  1345. int strId = GetStringPoolIdx(constantStr, constHolder);
  1346. if (strId != -1)
  1347. {
  1348. auto& entry = mContext->mStringObjectIdMap[strId];
  1349. return &entry.mString;
  1350. }
  1351. return NULL;
  1352. }
  1353. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1354. {
  1355. BfIRValue* irValue = NULL;
  1356. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1357. return *irValue;
  1358. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1359. if (!mStringObjectPool.ContainsKey(stringId))
  1360. mStringPoolRefs.Add(stringId);
  1361. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1362. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1363. *irValue = strCharPtrConst;
  1364. return strCharPtrConst;
  1365. }
  1366. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1367. {
  1368. if (strValue.IsConst())
  1369. {
  1370. int stringId = GetStringPoolIdx(strValue);
  1371. BF_ASSERT(stringId != -1);
  1372. return GetStringCharPtr(stringId);
  1373. }
  1374. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1375. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1376. return charPtr;
  1377. }
  1378. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1379. {
  1380. return GetStringCharPtr(GetStringObjectValue(str));
  1381. }
  1382. BfIRValue BfModule::GetStringObjectValue(int strId)
  1383. {
  1384. BfIRValue* objValue;
  1385. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1386. return *objValue;
  1387. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1388. return GetStringObjectValue(stringPoolEntry.mString, true);
  1389. }
  1390. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1391. {
  1392. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1393. mBfIRBuilder->PopulateType(stringType);
  1394. int strId = mContext->GetStringLiteralId(str);
  1395. BfIRValue* irValuePtr = NULL;
  1396. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1397. return *irValuePtr;
  1398. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1399. if (!mStringCharPtrPool.ContainsKey(strId))
  1400. mStringPoolRefs.Add(strId);
  1401. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1402. *irValuePtr = strObject;
  1403. mStringPoolRefs.Add(strId);
  1404. return strObject;
  1405. }
  1406. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1407. {
  1408. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1409. type,
  1410. true,
  1411. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1412. constant,
  1413. name.c_str());
  1414. return newConst;
  1415. }
  1416. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1417. {
  1418. auto curScope = mCurMethodState->mCurScope;
  1419. if (curScope->mLabelNode != NULL)
  1420. {
  1421. curScope->mLabelNode->ToString(curScope->mLabel);
  1422. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1423. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1424. auto autoComplete = mCompiler->GetAutoComplete();
  1425. if (autoComplete != NULL)
  1426. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1427. }
  1428. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1429. {
  1430. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1431. while (checkScope != NULL)
  1432. {
  1433. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1434. {
  1435. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1436. if (errorNode != NULL)
  1437. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1438. break;
  1439. }
  1440. checkScope = checkScope->mPrevScope;
  1441. }
  1442. }
  1443. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1444. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1445. {
  1446. if (prevScope->mHadScopeValueRetain)
  1447. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1448. else
  1449. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1450. }
  1451. mCurMethodState->mBlockNestLevel++;
  1452. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1453. {
  1454. // DIScope could be NULL if we're in an unspecialized method (for example)
  1455. if (mCurMethodState->mCurScope->mDIScope)
  1456. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1457. }
  1458. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1459. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1460. }
  1461. void BfModule::RestoreScoreState_LocalVariables()
  1462. {
  1463. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1464. {
  1465. auto localVar = mCurMethodState->mLocals.back();
  1466. LocalVariableDone(localVar, false);
  1467. mCurMethodState->mLocals.pop_back();
  1468. if (localVar->mShadowedLocal != NULL)
  1469. {
  1470. BfLocalVarEntry* localVarEntryPtr;
  1471. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1472. {
  1473. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1474. }
  1475. }
  1476. else
  1477. {
  1478. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1479. }
  1480. delete localVar;
  1481. }
  1482. }
  1483. void BfModule::RestoreScopeState()
  1484. {
  1485. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1486. mCurMethodState->mBlockNestLevel--;
  1487. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1488. {
  1489. BfIRBlock afterEndBlock;
  1490. if (!mCurMethodState->mLeftBlockUncond)
  1491. {
  1492. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1493. mBfIRBuilder->CreateBr(afterEndBlock);
  1494. mBfIRBuilder->ClearDebugLocation_Last();
  1495. }
  1496. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1497. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1498. if (afterEndBlock)
  1499. {
  1500. mBfIRBuilder->AddBlock(afterEndBlock);
  1501. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1502. }
  1503. }
  1504. if (!mCurMethodState->mLeftBlockUncond)
  1505. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1506. RestoreScoreState_LocalVariables();
  1507. if (mCurMethodState->mCurScope->mValueScopeStart)
  1508. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1509. mCurMethodState->mCurScope = prevScopeData;
  1510. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1511. }
  1512. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1513. {
  1514. if (mBfIRBuilder->mIgnoreWrites)
  1515. return mBfIRBuilder->GetFakeVal();
  1516. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1517. mBfIRBuilder->PopulateType(type);
  1518. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1519. if (!mBfIRBuilder->mIgnoreWrites)
  1520. BF_ASSERT(!prevInsertBlock.IsFake());
  1521. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1522. BfIRValue allocaInst;
  1523. if (arraySize)
  1524. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1525. else
  1526. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1527. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1528. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1529. if (name != NULL)
  1530. mBfIRBuilder->SetName(allocaInst, name);
  1531. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1532. if ((addLifetime) && (WantsLifetimes()))
  1533. {
  1534. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1535. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1536. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1537. }
  1538. return allocaInst;
  1539. }
  1540. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1541. {
  1542. if (mBfIRBuilder->mIgnoreWrites)
  1543. return mBfIRBuilder->GetFakeVal();
  1544. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1545. mBfIRBuilder->PopulateType(typeInst);
  1546. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1547. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1548. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1549. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1550. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1551. if (name != NULL)
  1552. mBfIRBuilder->SetName(allocaInst, name);
  1553. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1554. if ((addLifetime) && (WantsLifetimes()))
  1555. {
  1556. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1557. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1558. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1559. }
  1560. return allocaInst;
  1561. }
  1562. void BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1563. {
  1564. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1565. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1566. /*if (mCurMethodState->mInHeadScope)
  1567. isScopeAlloc = true;*/
  1568. if (scopeData == NULL)
  1569. return;
  1570. auto checkBaseType = val.mType->ToTypeInstance();
  1571. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1572. {
  1573. bool hadDtorCall = false;
  1574. while (checkBaseType != NULL)
  1575. {
  1576. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1577. {
  1578. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1579. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1580. BfIRValue useVal = val.mValue;
  1581. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1582. if (isDynAlloc)
  1583. {
  1584. //
  1585. }
  1586. else if (condAlloca)
  1587. {
  1588. BF_ASSERT(!IsTargetingBeefBackend());
  1589. BF_ASSERT(!isDynAlloc);
  1590. auto valPtr = CreateAlloca(checkBaseType);
  1591. mBfIRBuilder->CreateStore(useVal, valPtr);
  1592. useVal = valPtr;
  1593. }
  1594. SizedArray<BfIRValue, 1> llvmArgs;
  1595. llvmArgs.push_back(useVal);
  1596. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1597. if (deferredCall != NULL)
  1598. {
  1599. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1600. if (condAlloca)
  1601. deferredCall->mArgsNeedLoad = true;
  1602. }
  1603. hadDtorCall = true;
  1604. break;
  1605. }
  1606. checkBaseType = checkBaseType->mBaseType;
  1607. }
  1608. return;
  1609. }
  1610. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1611. if (mayEscape)
  1612. {
  1613. if ((!IsOptimized()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1614. {
  1615. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1616. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1617. if (!isDyn)
  1618. {
  1619. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1620. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1621. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1622. if (!dtorMethodInstance.mMethodInstance)
  1623. {
  1624. Fail(StrFormat("Unable to find %s", methodName));
  1625. }
  1626. else
  1627. {
  1628. SizedArray<BfIRValue, 1> llvmArgs;
  1629. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1630. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1631. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1632. if (arraySize)
  1633. llvmArgs.push_back(arraySize);
  1634. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1635. }
  1636. }
  1637. else
  1638. {
  1639. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1640. {
  1641. BfIRValue clearSize = arraySize;
  1642. if (val.mType->GetStride() > 1)
  1643. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1644. const char* methodName = "SetDeletedX";
  1645. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1646. BF_ASSERT(dtorMethodInstance);
  1647. if (!dtorMethodInstance)
  1648. {
  1649. Fail(StrFormat("Unable to find %s", methodName));
  1650. }
  1651. else
  1652. {
  1653. SizedArray<BfIRValue, 1> llvmArgs;
  1654. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1655. llvmArgs.push_back(clearSize);
  1656. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1657. }
  1658. }
  1659. else
  1660. {
  1661. intptr clearSize = val.mType->mSize;
  1662. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1663. if (constant != NULL)
  1664. clearSize = (intptr)(clearSize * constant->mInt64);
  1665. const char* funcName = "SetDeleted1";
  1666. if (clearSize >= 16)
  1667. funcName = "SetDeleted16";
  1668. else if (clearSize >= 8)
  1669. funcName = "SetDeleted8";
  1670. else if (clearSize >= 4)
  1671. funcName = "SetDeleted4";
  1672. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1673. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1674. if (!dtorMethodInstance)
  1675. {
  1676. Fail(StrFormat("Unable to find %s", funcName));
  1677. }
  1678. else
  1679. {
  1680. SizedArray<BfIRValue, 1> llvmArgs;
  1681. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1682. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1683. }
  1684. }
  1685. }
  1686. }
  1687. }
  1688. }
  1689. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1690. {
  1691. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1692. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1693. return false;
  1694. auto checkTypeInstance = startTypeInstance;
  1695. while (checkTypeInstance != NULL)
  1696. {
  1697. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1698. {
  1699. if (fieldInstance.mMergedDataIdx != -1)
  1700. {
  1701. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1702. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1703. {
  1704. // For fields added in extensions, we automatically initialize those if necessary
  1705. auto fieldDef = fieldInstance.GetFieldDef();
  1706. if (!fieldDef->mDeclaringType->IsExtension())
  1707. return false;
  1708. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1709. {
  1710. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1711. mBfIRBuilder->SaveDebugLocation();
  1712. if (localVar->IsParam())
  1713. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1714. else
  1715. {
  1716. BF_ASSERT(localVar->mDeclBlock);
  1717. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1718. }
  1719. mBfIRBuilder->ClearDebugLocation();
  1720. BfIRValue curVal;
  1721. if (localVar->mIsThis)
  1722. curVal = mBfIRBuilder->GetArgument(0);
  1723. else
  1724. curVal = localVar->mAddr;
  1725. auto subTypeInstance = startTypeInstance;
  1726. while (subTypeInstance != checkTypeInstance)
  1727. {
  1728. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1729. subTypeInstance = subTypeInstance->mBaseType;
  1730. }
  1731. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1732. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1733. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1734. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1735. mBfIRBuilder->RestoreDebugLocation();
  1736. }
  1737. localVar->mUnassignedFieldFlags &= ~checkMask;
  1738. if (localVar->mUnassignedFieldFlags == 0)
  1739. localVar->mIsAssigned = true;
  1740. }
  1741. }
  1742. }
  1743. checkTypeInstance = checkTypeInstance->mBaseType;
  1744. }
  1745. return localVar->mIsAssigned;
  1746. }
  1747. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1748. {
  1749. //if (localVar->mAddr == NULL)
  1750. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1751. {
  1752. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1753. {
  1754. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1755. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1756. }
  1757. }*/
  1758. BfAstNode* localNameNode = localVar->mNameNode;
  1759. if (localVar->mIsThis)
  1760. {
  1761. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1762. }
  1763. if (localNameNode != NULL)
  1764. {
  1765. bool isOut = false;
  1766. if (localVar->mResolvedType->IsRef())
  1767. {
  1768. auto refType = (BfRefType*)localVar->mResolvedType;
  1769. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1770. }
  1771. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1772. {
  1773. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1774. TryLocalVariableInit(localVar);
  1775. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1776. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1777. //bool deferFullAnalysis = true;
  1778. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1779. if (!localVar->mIsAssigned)
  1780. {
  1781. if (deferUsageWarning)
  1782. {
  1783. // Ignore
  1784. }
  1785. else if (localVar->mIsThis)
  1786. {
  1787. bool foundFields = false;
  1788. auto checkTypeInstance = mCurTypeInstance;
  1789. while (checkTypeInstance != NULL)
  1790. {
  1791. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1792. {
  1793. if (fieldInstance.mMergedDataIdx != -1)
  1794. {
  1795. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1796. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1797. {
  1798. auto fieldDef = fieldInstance.GetFieldDef();
  1799. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1800. {
  1801. String propName;
  1802. if (propertyDeclaration->mNameNode != NULL)
  1803. propertyDeclaration->mNameNode->ToString(propName);
  1804. if (checkTypeInstance == mCurTypeInstance)
  1805. {
  1806. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1807. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1808. }
  1809. else
  1810. {
  1811. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  1812. TypeToString(checkTypeInstance).c_str(),
  1813. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1814. }
  1815. }
  1816. else
  1817. {
  1818. if (checkTypeInstance == mCurTypeInstance)
  1819. {
  1820. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1821. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1822. }
  1823. else
  1824. {
  1825. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1826. TypeToString(checkTypeInstance).c_str(),
  1827. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1828. }
  1829. }
  1830. foundFields = true;
  1831. }
  1832. }
  1833. }
  1834. checkTypeInstance = checkTypeInstance->mBaseType;
  1835. }
  1836. if (!foundFields)
  1837. {
  1838. if (mCurTypeInstance->mInstSize > 0)
  1839. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1840. }
  1841. }
  1842. else if (localVar->IsParam())
  1843. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1844. else if (!deferUsageWarning)
  1845. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1846. }
  1847. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1848. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1849. }
  1850. }
  1851. }
  1852. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1853. {
  1854. auto checkScope = mCurMethodState->mCurScope;
  1855. while (true)
  1856. {
  1857. if (checkScope == scopeData)
  1858. break;
  1859. checkScope->mHadOuterDynStack = true;
  1860. checkScope = checkScope->mPrevScope;
  1861. }
  1862. }
  1863. void BfModule::SaveStackState(BfScopeData* scopeData)
  1864. {
  1865. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1866. // scopes within scopeData restore the stack
  1867. auto checkScope = mCurMethodState->mCurScope;
  1868. while (true)
  1869. {
  1870. if (checkScope == scopeData)
  1871. {
  1872. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1873. {
  1874. if (mBfIRBuilder->mHasDebugInfo)
  1875. mBfIRBuilder->SaveDebugLocation();
  1876. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1877. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1878. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1879. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1880. mBfIRBuilder->SetInsertPoint(prevPos);
  1881. if (mBfIRBuilder->mHasDebugInfo)
  1882. mBfIRBuilder->RestoreDebugLocation();
  1883. }
  1884. break;
  1885. }
  1886. if (checkScope->mSavedStack)
  1887. {
  1888. for (auto usage : checkScope->mSavedStackUses)
  1889. mBfIRBuilder->EraseInstFromParent(usage);
  1890. checkScope->mSavedStackUses.Clear();
  1891. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1892. checkScope->mSavedStack = BfIRValue();
  1893. }
  1894. checkScope = checkScope->mPrevScope;
  1895. }
  1896. }
  1897. BfIRValue BfModule::ValueScopeStart()
  1898. {
  1899. if (IsTargetingBeefBackend())
  1900. return mBfIRBuilder->CreateValueScopeStart();
  1901. return BfIRValue();
  1902. }
  1903. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1904. {
  1905. if (valueScopeStart)
  1906. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1907. }
  1908. BfProjectSet* BfModule::GetVisibleProjectSet()
  1909. {
  1910. if (mCurMethodState == NULL)
  1911. return NULL;
  1912. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  1913. {
  1914. HashSet<BfType*> seenTypes;
  1915. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  1916. {
  1917. if (mCurMethodState->mVisibleProjectSet.Add(project))
  1918. {
  1919. for (auto dep : project->mDependencies)
  1920. _AddProject(dep);
  1921. }
  1922. };
  1923. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  1924. {
  1925. auto typeInstance = type->ToTypeInstance();
  1926. if (typeInstance == NULL)
  1927. return;
  1928. _AddProject(typeInstance->mTypeDef->mProject);
  1929. if (typeInstance->mGenericTypeInfo == NULL)
  1930. return;
  1931. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  1932. {
  1933. if (seenTypes.Add(type))
  1934. _AddType(type);
  1935. }
  1936. };
  1937. if (mCurTypeInstance != NULL)
  1938. _AddType(mCurTypeInstance);
  1939. auto methodState = mCurMethodState;
  1940. while (methodState != NULL)
  1941. {
  1942. if (methodState->mMethodInstance != NULL)
  1943. {
  1944. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  1945. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  1946. {
  1947. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  1948. _AddType(type);
  1949. }
  1950. }
  1951. methodState = methodState->mPrevMethodState;
  1952. }
  1953. }
  1954. return &mCurMethodState->mVisibleProjectSet;
  1955. }
  1956. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1957. {
  1958. auto bfParser = astNode->GetSourceData()->ToParserData();
  1959. if (bfParser == NULL)
  1960. return NULL;
  1961. BfFileInstance** fileInstancePtr = NULL;
  1962. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1963. {
  1964. return *fileInstancePtr;
  1965. }
  1966. else
  1967. {
  1968. // It's possible two parsers have the same file name (ie: mNextRevision)
  1969. BfFileInstance** namedFileInstancePtr = NULL;
  1970. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1971. {
  1972. auto bfFileInstance = *namedFileInstancePtr;
  1973. *fileInstancePtr = bfFileInstance;
  1974. return bfFileInstance;
  1975. }
  1976. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1977. auto bfFileInstance = new BfFileInstance();
  1978. *fileInstancePtr = bfFileInstance;
  1979. *namedFileInstancePtr = bfFileInstance;
  1980. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1981. bfFileInstance->mParser = bfParser;
  1982. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1983. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1984. {
  1985. String fileName = bfParser->mFileName;
  1986. for (int i = 0; i < (int)fileName.length(); i++)
  1987. {
  1988. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1989. fileName[i] = DIR_SEP_CHAR;
  1990. }
  1991. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos), bfParser->mMD5Hash);
  1992. }
  1993. return bfFileInstance;
  1994. }
  1995. }
  1996. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1997. {
  1998. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1999. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2000. return;
  2001. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2002. if (astNode == NULL)
  2003. return;
  2004. auto bfParser = astNode->GetSourceData()->ToParserData();
  2005. if (bfParser == NULL)
  2006. return;
  2007. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2008. {
  2009. if (mCurFilePosition.mFileInstance != NULL)
  2010. {
  2011. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2012. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2013. }
  2014. auto bfFileInstance = GetFileFromNode(astNode);
  2015. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2016. {
  2017. mCurFilePosition = bfFileInstance->mPrevPosition;
  2018. }
  2019. else
  2020. {
  2021. mCurFilePosition.mFileInstance = bfFileInstance;
  2022. mCurFilePosition.mCurLine = 0;
  2023. mCurFilePosition.mCurSrcPos = 0;
  2024. }
  2025. }
  2026. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2027. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2028. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2029. if (jumpEntry->mCharIdx > srcPos)
  2030. jumpEntry--;
  2031. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2032. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2033. mCurFilePosition.mCurColumn = 0;
  2034. while (mCurFilePosition.mCurSrcPos < srcPos)
  2035. {
  2036. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2037. {
  2038. mCurFilePosition.mCurLine++;
  2039. mCurFilePosition.mCurColumn = 0;
  2040. }
  2041. else
  2042. {
  2043. mCurFilePosition.mCurColumn++;
  2044. }
  2045. mCurFilePosition.mCurSrcPos++;
  2046. }
  2047. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2048. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2049. {
  2050. int column = mCurFilePosition.mCurColumn + 1;
  2051. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2052. {
  2053. // Set to illegal position
  2054. column = 0;
  2055. }
  2056. if (mSetIllegalSrcPosition)
  2057. column = 0;
  2058. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2059. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2060. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2061. {
  2062. // This is from a different scope...
  2063. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2064. {
  2065. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2066. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2067. }
  2068. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2069. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2070. }
  2071. else
  2072. {
  2073. if (mCurMethodState->mCurScope->mAltDIFile)
  2074. {
  2075. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2076. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2077. }
  2078. }
  2079. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2080. if (mCurMethodState->mCrossingMixin)
  2081. inlineAt = BfIRMDNode();
  2082. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2083. if ((flags & BfSrcPosFlag_Expression) == 0)
  2084. mBfIRBuilder->CreateStatementStart();
  2085. }
  2086. }
  2087. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2088. {
  2089. // We've turned off expr src pos (for now?)
  2090. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2091. }
  2092. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2093. {
  2094. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2095. SetIllegalSrcPos();
  2096. }
  2097. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2098. {
  2099. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2100. {
  2101. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2102. {
  2103. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2104. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2105. }
  2106. else
  2107. {
  2108. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2109. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2110. }
  2111. if ((flags & BfSrcPosFlag_Expression) == 0)
  2112. mBfIRBuilder->CreateStatementStart();
  2113. }
  2114. }
  2115. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2116. {
  2117. // We've turned off expr src pos (for now?)
  2118. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2119. }
  2120. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2121. {
  2122. if ((protection == BfProtection_Public) ||
  2123. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2124. ((protection == BfProtection_Private) && (allowPrivate)))
  2125. return true;
  2126. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2127. return true;
  2128. return false;
  2129. }
  2130. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2131. {
  2132. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2133. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2134. {
  2135. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2136. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2137. }
  2138. allowProtected = allowPrivate;
  2139. }
  2140. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2141. {
  2142. if (memberProtection == BfProtection_Hidden)
  2143. return false;
  2144. if (memberProtection == BfProtection_Public)
  2145. return true;
  2146. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2147. {
  2148. BfTypeInstance* curCheckType = mCurTypeInstance;
  2149. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2150. {
  2151. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2152. curCheckType = mixinOwner;
  2153. }
  2154. bool allowPrivate = (curCheckType != NULL) && (memberOwner->mTypeDef == curCheckType->mTypeDef);
  2155. if (curCheckType != NULL)
  2156. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2157. if (allowPrivate)
  2158. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2159. else
  2160. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2161. }
  2162. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2163. return true;
  2164. if (memberProtection == BfProtection_Protected)
  2165. {
  2166. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2167. {
  2168. bool allowProtected = false;
  2169. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2170. auto curCheckType = mCurTypeInstance;
  2171. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2172. {
  2173. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2174. curCheckType = mixinOwner;
  2175. }
  2176. auto lookupCheckType = lookupStartType;
  2177. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2178. {
  2179. if (lookupCheckType == curCheckType)
  2180. {
  2181. allowProtected = true;
  2182. break;
  2183. }
  2184. if (lookupCheckType == memberOwner)
  2185. break;
  2186. lookupCheckType = lookupCheckType->mBaseType;
  2187. if (lookupCheckType == NULL)
  2188. break;
  2189. }
  2190. if (!allowProtected)
  2191. {
  2192. // It's possible our outer type is derived from 'memberOwner'
  2193. while (curCheckType->mTypeDef->mNestDepth > 0)
  2194. {
  2195. curCheckType = GetOuterType(curCheckType);
  2196. if (curCheckType == NULL)
  2197. break;
  2198. auto lookupCheckType = lookupStartType;
  2199. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2200. {
  2201. if (lookupCheckType == curCheckType)
  2202. {
  2203. allowProtected = true;
  2204. break;
  2205. }
  2206. if (lookupCheckType == memberOwner)
  2207. break;
  2208. lookupCheckType = lookupCheckType->mBaseType;
  2209. if (lookupCheckType == NULL)
  2210. break;
  2211. }
  2212. }
  2213. }
  2214. if (allowProtected)
  2215. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2216. else
  2217. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2218. }
  2219. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2220. return true;
  2221. }
  2222. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2223. return true;
  2224. return false;
  2225. }
  2226. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2227. {
  2228. if ((mCompiler->mResolvePassData != NULL) &&
  2229. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2230. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2231. {
  2232. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2233. }
  2234. }
  2235. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2236. {
  2237. BP_ZONE("BfModule::Fail");
  2238. if (mIgnoreErrors)
  2239. {
  2240. return NULL;
  2241. }
  2242. if (!mReportErrors)
  2243. {
  2244. mCompiler->mPassInstance->SilentFail();
  2245. return NULL;
  2246. }
  2247. if (refNode != NULL)
  2248. refNode = BfNodeToNonTemporary(refNode);
  2249. //BF_ASSERT(refNode != NULL);
  2250. if (mCurMethodInstance != NULL)
  2251. mCurMethodInstance->mHasFailed = true;
  2252. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2253. return NULL;
  2254. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2255. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2256. if (!mHadBuildError)
  2257. mHadBuildError = true;
  2258. if (mParentModule != NULL)
  2259. mParentModule->mHadBuildError = true;
  2260. if (mCurTypeInstance != NULL)
  2261. AddFailType(mCurTypeInstance);
  2262. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2263. String errorString = error;
  2264. bool isWhileSpecializing = false;
  2265. bool isWhileSpecializingMethod = false;
  2266. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2267. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2268. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2269. errorString += StrFormat("\n while generating append size calculating method");
  2270. else if (refNode == NULL)
  2271. {
  2272. if (mCurTypeInstance != NULL)
  2273. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2274. else if (mProject != NULL)
  2275. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2276. }
  2277. if (mCurTypeInstance != NULL)
  2278. {
  2279. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2280. {
  2281. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2282. methodInstance->mHasFailed = true;
  2283. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2284. if (isSpecializedMethod)
  2285. {
  2286. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2287. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2288. if (unspecializedMethod->mHasFailed)
  2289. return false; // At least SOME error has already been reported
  2290. }
  2291. if (isSpecializedMethod)
  2292. {
  2293. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2294. isWhileSpecializing = true;
  2295. isWhileSpecializingMethod = true;
  2296. }
  2297. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2298. {
  2299. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2300. isWhileSpecializing = true;
  2301. isWhileSpecializingMethod = true;
  2302. }
  2303. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2304. {
  2305. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2306. isWhileSpecializing = true;
  2307. }
  2308. return true;
  2309. };
  2310. if (mCurMethodState != NULL)
  2311. {
  2312. auto checkMethodState = mCurMethodState;
  2313. while (checkMethodState != NULL)
  2314. {
  2315. auto methodInstance = checkMethodState->mMethodInstance;
  2316. if (methodInstance == NULL)
  2317. {
  2318. checkMethodState = checkMethodState->mPrevMethodState;
  2319. continue;
  2320. }
  2321. if (!_CheckMethodInstance(methodInstance))
  2322. return NULL;
  2323. checkMethodState = checkMethodState->mPrevMethodState;
  2324. }
  2325. }
  2326. else if (mCurMethodInstance != NULL)
  2327. {
  2328. if (!_CheckMethodInstance(mCurMethodInstance))
  2329. return NULL;
  2330. }
  2331. // Keep in mind that all method specializations with generic type instances as its method generic params
  2332. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2333. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2334. // those method specializations if that occurs
  2335. if (isWhileSpecializing)
  2336. {
  2337. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2338. if (bfError != NULL)
  2339. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2340. return bfError;
  2341. }
  2342. }
  2343. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2344. {
  2345. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2346. isWhileSpecializing = true;
  2347. }
  2348. if (!mHadBuildError)
  2349. mHadBuildError = true;
  2350. // Check mixins
  2351. {
  2352. auto checkMethodInstance = mCurMethodState;
  2353. while (checkMethodInstance != NULL)
  2354. {
  2355. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2356. if (rootMixinState != NULL)
  2357. {
  2358. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2359. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2360. auto mixinState = checkMethodInstance->mMixinState;
  2361. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2362. {
  2363. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2364. mixinState = mixinState->mPrevMixinState;
  2365. }
  2366. return bfError;
  2367. }
  2368. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2369. }
  2370. }
  2371. BfError* bfError = NULL;
  2372. if (refNode == NULL)
  2373. bfError = mCompiler->mPassInstance->Fail(errorString);
  2374. else
  2375. {
  2376. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2377. }
  2378. if (bfError != NULL)
  2379. {
  2380. bfError->mProject = mProject;
  2381. bfError->mIsPersistent = isPersistent;
  2382. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2383. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2384. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2385. }
  2386. return bfError;
  2387. }
  2388. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2389. {
  2390. if (mHadBuildError)
  2391. return NULL;
  2392. return Fail(error, refNode);
  2393. }
  2394. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2395. {
  2396. if (mIgnoreErrors)
  2397. return NULL;
  2398. if (refNode != NULL)
  2399. refNode = BfNodeToNonTemporary(refNode);
  2400. mHadBuildError = true;
  2401. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2402. if (bfError != NULL)
  2403. bfError->mProject = mProject;
  2404. return bfError;
  2405. }
  2406. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2407. {
  2408. if (mIgnoreErrors || mIgnoreWarnings)
  2409. return NULL;
  2410. if (!mReportErrors)
  2411. {
  2412. mCompiler->mPassInstance->SilentFail();
  2413. return NULL;
  2414. }
  2415. BfAstNode* unwarnNode = refNode;
  2416. //
  2417. {
  2418. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2419. while (parentNodeEntry != NULL)
  2420. {
  2421. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2422. break;
  2423. unwarnNode = parentNodeEntry->mNode;
  2424. parentNodeEntry = parentNodeEntry->mPrev;
  2425. }
  2426. }
  2427. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2428. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2429. {
  2430. return NULL;
  2431. }
  2432. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2433. if (mCurMethodInstance != NULL)
  2434. {
  2435. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2436. return NULL;
  2437. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2438. return NULL; // No ctorCalcAppend warnings
  2439. }
  2440. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2441. return NULL;
  2442. if (refNode != NULL)
  2443. refNode = BfNodeToNonTemporary(refNode);
  2444. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2445. {
  2446. // We used to bubble up warnings into the mixin injection site, BUT
  2447. // we are now assuming any relevant warnings will be given at the declaration site
  2448. return NULL;
  2449. }
  2450. BfError* bfError;
  2451. if (refNode != NULL)
  2452. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2453. else
  2454. bfError = mCompiler->mPassInstance->Warn(warningNum, warning);
  2455. if (bfError != NULL)
  2456. {
  2457. bfError->mProject = mProject;
  2458. AddFailType(mCurTypeInstance);
  2459. mHadBuildWarning = true;
  2460. bfError->mIsPersistent = isPersistent;
  2461. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2462. {
  2463. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2464. if (parser != NULL)
  2465. {
  2466. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2467. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2468. if (warningNum != 0)
  2469. {
  2470. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\tusing|%s|%d||#pragma warning disable %d",
  2471. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2472. }
  2473. }
  2474. }
  2475. }
  2476. return bfError;
  2477. }
  2478. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2479. {
  2480. auto _AddDeclarationMoreInfo = [&]()
  2481. {
  2482. if (methodInstance != NULL)
  2483. {
  2484. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2485. mCompiler->mPassInstance->MoreInfo(
  2486. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2487. methodInstance->mMethodDef->GetRefNode());
  2488. }
  2489. else
  2490. {
  2491. mCompiler->mPassInstance->MoreInfo(
  2492. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2493. typeInstance->mTypeDef->GetRefNode());
  2494. }
  2495. };
  2496. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2497. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2498. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2499. {
  2500. String err;
  2501. if (methodInstance != NULL)
  2502. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2503. else
  2504. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2505. bool isError = false;
  2506. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2507. if (constant->mTypeCode == BfTypeCode_Boolean)
  2508. {
  2509. isError = constant->mBool;
  2510. }
  2511. else if (customAttribute->mCtorArgs.size() >= 2)
  2512. {
  2513. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2514. if (str != NULL)
  2515. {
  2516. err += ":\n '";
  2517. err += *str;
  2518. err += "'";
  2519. }
  2520. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2521. isError = constant->mBool;
  2522. }
  2523. BfError* error = NULL;
  2524. if (isError)
  2525. error = Fail(err, targetSrc);
  2526. else
  2527. error = Warn(0, err, targetSrc);
  2528. if (error != NULL)
  2529. _AddDeclarationMoreInfo();
  2530. }
  2531. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2532. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2533. {
  2534. String err;
  2535. if (methodInstance != NULL)
  2536. StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2537. else
  2538. StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2539. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2540. if (str != NULL)
  2541. err += *str;
  2542. err += "'";
  2543. if (Fail(err, targetSrc) != NULL)
  2544. _AddDeclarationMoreInfo();
  2545. }
  2546. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2547. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2548. {
  2549. String err;
  2550. if (methodInstance != NULL)
  2551. StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2552. else
  2553. StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2554. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2555. if (str != NULL)
  2556. err += *str;
  2557. err += "'";
  2558. if (Warn(0, err, targetSrc) != NULL)
  2559. _AddDeclarationMoreInfo();
  2560. }
  2561. }
  2562. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2563. {
  2564. if (mBfIRBuilder->mOpFailed)
  2565. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2566. }
  2567. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2568. {
  2569. String fullError = error;
  2570. if (file != NULL)
  2571. fullError += StrFormat(" at %s:%d", file, line);
  2572. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2573. if (mCurTypeInstance != NULL)
  2574. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2575. if (mCurMethodInstance != NULL)
  2576. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2577. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2578. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2579. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2580. }
  2581. void BfModule::NotImpl(BfAstNode* astNode)
  2582. {
  2583. Fail("INTERNAL ERROR: Not implemented", astNode);
  2584. }
  2585. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2586. {
  2587. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2588. if (!allowPrivate)
  2589. allowPrivate |= memberType->IsInterface();
  2590. bool allowProtected = allowPrivate;
  2591. //TODO: We had this commented out, but this makes accessing protected properties fail
  2592. if (mCurTypeInstance != NULL)
  2593. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2594. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2595. {
  2596. return false;
  2597. }
  2598. return true;
  2599. }
  2600. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2601. {
  2602. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2603. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2604. auto memberTypeInstance = memberType->ToTypeInstance();
  2605. if (memberTypeInstance == NULL)
  2606. {
  2607. auto underlyingType = memberType->GetUnderlyingType();
  2608. if (underlyingType != NULL)
  2609. return CheckDefineMemberProtection(protection, underlyingType);
  2610. return true;
  2611. }
  2612. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2613. return false;
  2614. if (memberTypeInstance->IsGenericTypeInstance())
  2615. {
  2616. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2617. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  2618. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2619. {
  2620. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2621. return false;
  2622. }
  2623. }
  2624. return true;
  2625. }
  2626. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyDependencyFlag flags)
  2627. {
  2628. if (usedType == userType)
  2629. return;
  2630. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2631. return;
  2632. if (usedType->IsSpecializedByAutoCompleteMethod())
  2633. return;
  2634. // if (usedType->IsBoxed())
  2635. // {
  2636. // NOP;
  2637. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  2638. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  2639. // {
  2640. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  2641. // }
  2642. // }
  2643. BfType* origUsedType = usedType;
  2644. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  2645. if (isDataAccess)
  2646. {
  2647. while (true)
  2648. {
  2649. if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  2650. usedType = usedType->GetUnderlyingType();
  2651. else if (usedType->IsArray())
  2652. {
  2653. usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  2654. }
  2655. else
  2656. break;
  2657. }
  2658. }
  2659. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  2660. {
  2661. bool addType = true;
  2662. auto checkType = usedType;
  2663. PopulateType(checkType, BfPopulateType_Data);
  2664. if (checkType->IsValuelessType())
  2665. addType = false;
  2666. else if (checkType->IsPrimitiveType())
  2667. addType = false;
  2668. else
  2669. {
  2670. auto checkTypeInst = checkType->ToTypeInstance();
  2671. if (checkTypeInst == NULL)
  2672. {
  2673. addType = false;
  2674. }
  2675. else
  2676. {
  2677. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2678. addType = false;
  2679. }
  2680. }
  2681. if (addType)
  2682. {
  2683. auto checkTypeInst = checkType->ToTypeInstance();
  2684. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2685. BF_ASSERT(hotTypeVersion != NULL);
  2686. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2687. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2688. (checkType->IsComposite()))
  2689. isAllocation = true;
  2690. if (isAllocation)
  2691. {
  2692. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2693. }
  2694. else
  2695. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2696. }
  2697. }
  2698. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2699. {
  2700. auto usingModule = userType->GetModule();
  2701. BfModule* usedModule;
  2702. if (usedType->IsFunction())
  2703. {
  2704. auto typeInst = usedType->ToTypeInstance();
  2705. if (typeInst->mBaseType == NULL)
  2706. PopulateType(typeInst);
  2707. usedModule = typeInst->mBaseType->GetModule();
  2708. }
  2709. else
  2710. usedModule = usedType->GetModule();
  2711. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2712. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2713. {
  2714. usingModule->mModuleRefs.Add(usedModule);
  2715. }
  2716. }
  2717. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2718. {
  2719. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2720. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2721. if (genericArg == usedType)
  2722. return;
  2723. }
  2724. auto depFlag = flags;
  2725. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) == 0)
  2726. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef; // Will cause a rebuild but not an outright deletion of the type
  2727. auto underlyingType = usedType->GetUnderlyingType();
  2728. if (underlyingType != NULL)
  2729. AddDependency(underlyingType, userType, depFlag);
  2730. BfDependedType* checkDType = usedType->ToDependedType();
  2731. if (checkDType == NULL)
  2732. return;
  2733. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2734. mContext->MarkAsReferenced(checkDType);
  2735. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  2736. return;
  2737. if (checkDType->IsGenericTypeInstance())
  2738. {
  2739. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  2740. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2741. {
  2742. AddDependency(genericArg, userType, depFlag);
  2743. }
  2744. }
  2745. if (checkDType->IsTuple())
  2746. {
  2747. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  2748. {
  2749. if (field.mDataIdx != -1)
  2750. AddDependency(field.mResolvedType, userType, depFlag);
  2751. }
  2752. }
  2753. }
  2754. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2755. {
  2756. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2757. {
  2758. if (methodInstance->mHotMethod == NULL)
  2759. CheckHotMethod(methodInstance, "");
  2760. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2761. if (devirtualized)
  2762. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2763. else
  2764. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2765. }
  2766. }
  2767. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2768. {
  2769. auto checkTypeInst = typeInst;
  2770. while (checkTypeInst != NULL)
  2771. {
  2772. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2773. return true;
  2774. checkTypeInst = checkTypeInst->mBaseType;
  2775. }
  2776. return false;
  2777. }
  2778. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2779. {
  2780. if (mContext->mCurTypeState == NULL)
  2781. return;
  2782. BP_ZONE("PopulateGlobalContainersList");
  2783. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2784. if (userTypeDef == NULL)
  2785. userTypeDef = mCurTypeInstance->mTypeDef;
  2786. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2787. {
  2788. mContext->mCurTypeState->mGlobalContainers.Clear();
  2789. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2790. {
  2791. BfAtomComposite findStr;
  2792. if (namespaceIdx != -1)
  2793. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2794. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2795. while (typeDefItr)
  2796. {
  2797. auto typeDef = *typeDefItr;
  2798. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2799. {
  2800. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2801. {
  2802. BfGlobalContainerEntry globalEntry;
  2803. globalEntry.mTypeDef = typeDef;
  2804. globalEntry.mTypeInst = NULL;
  2805. typeDef->PopulateMemberSets();
  2806. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2807. }
  2808. }
  2809. else if (!typeDef->mIsPartial)
  2810. {
  2811. //break;
  2812. }
  2813. typeDefItr.MoveToNextHashMatch();
  2814. }
  2815. }
  2816. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2817. }
  2818. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2819. // reifing types
  2820. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2821. {
  2822. if (globalEntry.mTypeInst == NULL)
  2823. {
  2824. bool include = false;
  2825. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2826. include = true;
  2827. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2828. {
  2829. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2830. include = true;
  2831. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2832. include = true;
  2833. }
  2834. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2835. {
  2836. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2837. include = true;
  2838. }
  2839. if (include)
  2840. {
  2841. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2842. if (type != NULL)
  2843. globalEntry.mTypeInst = type->ToTypeInstance();
  2844. }
  2845. }
  2846. }
  2847. }
  2848. BfStaticSearch* BfModule::GetStaticSearch()
  2849. {
  2850. auto activeTypeDef = GetActiveTypeDef();
  2851. BfStaticSearch* staticSearch = NULL;
  2852. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2853. return staticSearch;
  2854. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2855. return staticSearch;
  2856. return NULL;
  2857. }
  2858. void PrintUsers(llvm::MDNode* md);
  2859. BfModuleOptions BfModule::GetModuleOptions()
  2860. {
  2861. if (mIsScratchModule)
  2862. return BfModuleOptions();
  2863. if (mModuleOptions != NULL)
  2864. return *mModuleOptions;
  2865. BfModuleOptions moduleOptions;
  2866. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2867. if (mProject != NULL)
  2868. {
  2869. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2870. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2871. }
  2872. auto headModule = this;
  2873. while (headModule->mParentModule != NULL)
  2874. headModule = headModule->mParentModule;
  2875. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2876. if (headModule->mOwnedTypeInstances.size() > 0)
  2877. {
  2878. auto typeInst = headModule->mOwnedTypeInstances[0];
  2879. PopulateType(typeInst);
  2880. if (typeInst->mTypeOptionsIdx != -1)
  2881. {
  2882. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2883. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2884. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2885. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2886. }
  2887. }
  2888. return moduleOptions;
  2889. }
  2890. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2891. {
  2892. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  2893. return BfCheckedKind_Unchecked;
  2894. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2895. auto typeOptions = GetTypeOptions();
  2896. if (typeOptions != NULL)
  2897. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  2898. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2899. }
  2900. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2901. {
  2902. mContext->mFailTypes.Add(typeInstance);
  2903. }
  2904. void BfModule::CheckAddFailType()
  2905. {
  2906. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2907. // but we still need to add the owning type to the FailTypes list
  2908. //.. OLD:
  2909. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2910. /*if (mCurTypeInstance->mModule != this)
  2911. return;*/
  2912. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2913. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2914. // being recompiled. This forces types with warnings to be recompiled.
  2915. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2916. // constantly warning-aware
  2917. if ((mHadBuildError) ||
  2918. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2919. {
  2920. //mContext->mFailTypes.Add(mCurTypeInstance);
  2921. }
  2922. }
  2923. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2924. {
  2925. if (!mCompiler->IsHotCompile())
  2926. return;
  2927. typeInst->mDirty = true;
  2928. for (auto& dep : typeInst->mDependencyMap)
  2929. {
  2930. auto depType = dep.mKey;
  2931. auto depFlags = dep.mValue.mFlags;
  2932. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2933. {
  2934. MarkDerivedDirty(depType->ToTypeInstance());
  2935. }
  2936. }
  2937. }
  2938. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2939. {
  2940. auto fieldType = fieldInstance->GetResolvedType();
  2941. auto field = fieldInstance->GetFieldDef();
  2942. if (fieldType->IsVar())
  2943. return;
  2944. BfIRValue initValue;
  2945. if (field->mIsConst)
  2946. {
  2947. if (fieldType->IsPointer())
  2948. fieldType = fieldType->GetUnderlyingType();
  2949. }
  2950. if (!field->mIsExtern)
  2951. initValue = GetDefaultValue(fieldType);
  2952. if (fieldInstance->mOwner->IsUnspecializedType())
  2953. {
  2954. // Placeholder
  2955. auto ptrVal = CreatePointerType(fieldType);
  2956. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2957. }
  2958. else
  2959. {
  2960. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2961. StringT<128> staticVarName;
  2962. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2963. if (!fieldType->IsValuelessType())
  2964. {
  2965. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2966. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2967. false,
  2968. BfIRLinkageType_External,
  2969. initValue,
  2970. staticVarName,
  2971. isThreadLocal);
  2972. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  2973. BF_ASSERT(globalVar);
  2974. mStaticFieldRefs[fieldInstance] = globalVar;
  2975. }
  2976. }
  2977. }
  2978. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2979. {
  2980. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2981. BfType* fieldType = NULL;
  2982. if (fieldInstance != NULL)
  2983. {
  2984. fieldType = fieldInstance->GetResolvedType();
  2985. if (fieldType == NULL)
  2986. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2987. }
  2988. else
  2989. {
  2990. BF_ASSERT(mCompiler->IsAutocomplete());
  2991. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2992. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2993. {
  2994. fieldType = typeInstance;
  2995. }
  2996. else
  2997. {
  2998. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2999. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3000. if (isLet || isVar)
  3001. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3002. else
  3003. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3004. if (fieldType == NULL)
  3005. fieldType = mContext->mBfObjectType;
  3006. }
  3007. }
  3008. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3009. return;
  3010. if (mContext->mFieldResolveReentrys.size() > 1)
  3011. {
  3012. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3013. {
  3014. String failStr = "Circular data reference detected between the following fields:";
  3015. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3016. {
  3017. if (i > 1)
  3018. failStr += ",";
  3019. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3020. }
  3021. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3022. if (err)
  3023. err->mIsPersistent = true;
  3024. return;
  3025. }
  3026. }
  3027. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3028. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3029. if (fieldInstance == NULL)
  3030. popTypeResolveReentry.Pop();
  3031. auto typeDef = typeInstance->mTypeDef;
  3032. BfIRValue constValue;
  3033. if (fieldDef->mIsExtern)
  3034. {
  3035. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3036. {
  3037. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3038. }
  3039. if (fieldDef->mInitializer != NULL)
  3040. {
  3041. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3042. }
  3043. }
  3044. else if (fieldDef->mInitializer == NULL)
  3045. {
  3046. if (fieldDef->IsEnumCaseEntry())
  3047. {
  3048. if (typeInstance->IsTypedPrimitive())
  3049. {
  3050. BfFieldInstance* prevFieldInstance = NULL;
  3051. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3052. {
  3053. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3054. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3055. {
  3056. prevFieldInstance = checkFieldInst;
  3057. break;
  3058. }
  3059. }
  3060. if (prevFieldInstance == NULL)
  3061. constValue = GetConstValue(0, typeInstance);
  3062. else
  3063. {
  3064. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3065. if (prevFieldInstance->mConstIdx == -1)
  3066. {
  3067. if (!mCompiler->IsAutocomplete())
  3068. AssertErrorState();
  3069. constValue = GetConstValue(0, typeInstance);
  3070. }
  3071. else
  3072. {
  3073. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3074. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3075. }
  3076. }
  3077. }
  3078. }
  3079. else
  3080. {
  3081. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3082. }
  3083. }
  3084. else
  3085. {
  3086. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3087. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3088. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3089. BfMethodState methodState;
  3090. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3091. methodState.mTempKind = BfMethodState::TempKind_Static;
  3092. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3093. if (fieldType->IsVar())
  3094. {
  3095. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3096. if (!initValue)
  3097. {
  3098. AssertErrorState();
  3099. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3100. }
  3101. if (fieldInstance != NULL)
  3102. {
  3103. fieldInstance->mResolvedType = initValue.mType;
  3104. }
  3105. constValue = initValue.mValue;
  3106. }
  3107. else
  3108. {
  3109. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3110. constValue = uncastedInitValue.mValue;
  3111. }
  3112. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3113. }
  3114. if (fieldInstance != NULL)
  3115. {
  3116. fieldType = fieldInstance->GetResolvedType();
  3117. if ((fieldType == NULL) || (fieldType->IsVar()))
  3118. {
  3119. AssertErrorState();
  3120. // Default const type is 'int'
  3121. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3122. if (fieldInstance != NULL)
  3123. {
  3124. fieldInstance->mResolvedType = initValue.mType;
  3125. }
  3126. constValue = initValue.mValue;
  3127. }
  3128. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3129. {
  3130. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3131. CurrentAddToConstHolder(constValue);
  3132. fieldInstance->mConstIdx = constValue.mId;
  3133. }
  3134. }
  3135. }
  3136. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3137. {
  3138. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3139. auto fieldType = fieldInstance->GetResolvedType();
  3140. if ((field->mIsConst) && (!isDeclType))
  3141. {
  3142. ResolveConstField(typeInstance, fieldInstance, field);
  3143. return fieldInstance->GetResolvedType();
  3144. }
  3145. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3146. if (!fieldInstance->mIsInferredType)
  3147. return fieldType;
  3148. if (!fieldType->IsVar())
  3149. return fieldType;
  3150. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3151. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3152. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  3153. auto typeDef = typeInstance->mTypeDef;
  3154. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3155. {
  3156. AssertErrorState();
  3157. return GetPrimitiveType(BfTypeCode_Var);
  3158. }
  3159. bool hadInferenceCycle = false;
  3160. if (mContext->mFieldResolveReentrys.size() > 1)
  3161. {
  3162. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3163. {
  3164. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3165. {
  3166. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3167. auto fieldDef = fieldInst->GetFieldDef();
  3168. auto fieldOwner = fieldInst->mOwner;
  3169. auto fieldModule = fieldOwner->mModule;
  3170. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3171. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3172. }
  3173. return GetPrimitiveType(BfTypeCode_Var);
  3174. }
  3175. }
  3176. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3177. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3178. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3179. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3180. if ((field->mInitializer == NULL) && (!isDeclType))
  3181. {
  3182. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3183. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3184. return GetPrimitiveType(BfTypeCode_Var);
  3185. }
  3186. BfType* resolvedType = NULL;
  3187. if (!hadInferenceCycle)
  3188. {
  3189. BfTypeState typeState;
  3190. typeState.mPrevState = mContext->mCurTypeState;
  3191. typeState.mTypeInstance = typeInstance;
  3192. typeState.mCurFieldDef = field;
  3193. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3194. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3195. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3196. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3197. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3198. BfMethodState methodState;
  3199. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3200. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3201. if (!staticOnly)
  3202. {
  3203. //BfLocalVariable localVar;
  3204. //methodState.mLocals.push_back(localVar);
  3205. }
  3206. if (isDeclType)
  3207. {
  3208. auto fieldDef = fieldInstance->GetFieldDef();
  3209. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3210. }
  3211. else
  3212. {
  3213. BfTypedValue valueFromExpr;
  3214. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3215. FixIntUnknown(valueFromExpr);
  3216. resolvedType = valueFromExpr.mType;
  3217. }
  3218. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3219. }
  3220. if (resolvedType == NULL)
  3221. return GetPrimitiveType(BfTypeCode_Var);
  3222. fieldInstance->SetResolvedType(resolvedType);
  3223. if (field->mIsStatic)
  3224. {
  3225. }
  3226. else if (fieldInstance->mDataIdx >= 0)
  3227. {
  3228. }
  3229. else
  3230. {
  3231. BF_ASSERT(typeInstance->IsIncomplete());
  3232. }
  3233. return resolvedType;
  3234. }
  3235. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3236. {
  3237. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3238. auto fieldType = fieldInstance->GetResolvedType();
  3239. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3240. {
  3241. int fieldDataCount = 1;
  3242. if (fieldType->IsStruct())
  3243. {
  3244. auto structTypeInst = fieldType->ToTypeInstance();
  3245. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  3246. }
  3247. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3248. auto thisVariable = GetThisVariable();
  3249. if (thisVariable != NULL)
  3250. {
  3251. for (int i = 0; i < fieldDataCount; i++)
  3252. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  3253. }
  3254. }
  3255. }
  3256. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3257. {
  3258. if (fieldInstance->mCustomAttributes == NULL)
  3259. return false;
  3260. auto fieldDef = fieldInstance->GetFieldDef();
  3261. if (!fieldDef->mIsStatic)
  3262. return false;
  3263. bool isThreadLocal = false;
  3264. if (fieldInstance->mCustomAttributes != NULL)
  3265. {
  3266. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3267. {
  3268. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3269. return true;
  3270. }
  3271. }
  3272. return false;
  3273. }
  3274. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3275. {
  3276. if (fieldDef == NULL)
  3277. fieldDef = fieldInstance->GetFieldDef();
  3278. if (fieldType == NULL)
  3279. fieldType = fieldInstance->GetResolvedType();
  3280. if (initializer == NULL)
  3281. {
  3282. if (fieldDef == NULL)
  3283. return BfTypedValue();
  3284. initializer = fieldDef->mInitializer;
  3285. }
  3286. BfTypedValue staticVarRef;
  3287. BfTypedValue result;
  3288. if (initializer == NULL)
  3289. {
  3290. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3291. }
  3292. else
  3293. {
  3294. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3295. {
  3296. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3297. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3298. }
  3299. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3300. {
  3301. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3302. BfConstResolver constResolver(this);
  3303. constResolver.Resolve(initializer);
  3304. return GetDefaultTypedValue(fieldType);
  3305. }
  3306. else if (fieldDef->mIsConst)
  3307. {
  3308. BfTypeState typeState;
  3309. typeState.mTypeInstance = mCurTypeInstance;
  3310. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3311. typeState.mCurFieldDef = fieldDef;
  3312. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3313. BfConstResolver constResolver(this);
  3314. if (fieldType->IsVar())
  3315. return constResolver.Resolve(initializer);
  3316. else
  3317. {
  3318. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3319. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3320. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3321. {
  3322. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3323. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3324. resolveFlags = BfConstResolveFlag_NoCast;
  3325. }
  3326. UpdateSrcPos(initializer);
  3327. return constResolver.Resolve(initializer, fieldType, resolveFlags);
  3328. }
  3329. }
  3330. BfExprEvaluator exprEvaluator(this);
  3331. if (doStore)
  3332. {
  3333. staticVarRef = ReferenceStaticField(fieldInstance);
  3334. exprEvaluator.mReceivingValue = &staticVarRef;
  3335. }
  3336. if (fieldType->IsVar())
  3337. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3338. else
  3339. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3340. if (doStore)
  3341. {
  3342. if (exprEvaluator.mReceivingValue == NULL)
  3343. doStore = false; // Already stored
  3344. }
  3345. }
  3346. if (fieldInstance != NULL)
  3347. MarkFieldInitialized(fieldInstance);
  3348. if ((doStore) && (result))
  3349. {
  3350. result = LoadValue(result);
  3351. if (!result.mType->IsValuelessType())
  3352. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3353. }
  3354. return result;
  3355. }
  3356. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3357. {
  3358. }
  3359. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3360. {
  3361. PopulateType(classType);
  3362. if (isInterfacePass)
  3363. {
  3364. for (auto ifaceInst : classType->mInterfaces)
  3365. {
  3366. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3367. continue;
  3368. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3369. continue;
  3370. if (ifaceInst.mDeclaringType->IsExtension())
  3371. {
  3372. bool needsExCheck = false;
  3373. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3374. {
  3375. exChecks->push_back(ifaceInst.mInterfaceType);
  3376. continue;
  3377. }
  3378. }
  3379. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3380. }
  3381. }
  3382. else
  3383. {
  3384. outVals->push_back(classType->mTypeId);
  3385. }
  3386. if (classType->mBaseType != NULL)
  3387. {
  3388. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3389. }
  3390. }
  3391. void BfModule::CreateDynamicCastMethod()
  3392. {
  3393. auto objType = mContext->mBfObjectType;
  3394. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3395. {
  3396. // The main reason to punt on this method for ResolveOnly is because types can be created
  3397. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3398. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3399. // remove this punt when we recycle typeId's
  3400. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3401. mCurMethodState->mHadReturn = true;
  3402. return;
  3403. }
  3404. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3405. auto func = mCurMethodState->mIRFunction;
  3406. auto thisValue = mBfIRBuilder->GetArgument(0);
  3407. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3408. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3409. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3410. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3411. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3412. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3413. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3414. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3415. SizedArray<int, 8> typeMatches;
  3416. SizedArray<BfTypeInstance*, 8> exChecks;
  3417. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3418. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3419. {
  3420. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3421. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3422. BfTypeVector genericArgs;
  3423. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3424. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3425. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3426. typeMatches.push_back(unboundType->mTypeId);
  3427. }
  3428. if (mCurTypeInstance->IsBoxed())
  3429. {
  3430. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3431. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  3432. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3433. if (innerType->IsTypedPrimitive())
  3434. {
  3435. auto underlyingType = innerType->GetUnderlyingType();
  3436. typeMatches.push_back(underlyingType->mTypeId);
  3437. }
  3438. auto innerTypeInst = innerType->ToTypeInstance();
  3439. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3440. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3441. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3442. {
  3443. PopulateType(innerTypeInst);
  3444. //TODO: What case was this supposed to handle?
  3445. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3446. }
  3447. }
  3448. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3449. BfIRValue vDataPtr;
  3450. if (!exChecks.empty())
  3451. {
  3452. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3453. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3454. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3455. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3456. }
  3457. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3458. for (auto typeMatch : typeMatches)
  3459. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3460. Array<BfIRValue> incomingFalses;
  3461. for (auto ifaceTypeInst : exChecks)
  3462. {
  3463. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3464. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3465. mBfIRBuilder->SetInsertPoint(nextBB);
  3466. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3467. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3468. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3469. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3470. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3471. incomingFalses.push_back(nextBB);
  3472. }
  3473. mBfIRBuilder->AddBlock(trueBB);
  3474. mBfIRBuilder->SetInsertPoint(trueBB);
  3475. mBfIRBuilder->CreateBr(exitBB);
  3476. mBfIRBuilder->AddBlock(exitBB);
  3477. mBfIRBuilder->SetInsertPoint(exitBB);
  3478. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3479. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3480. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3481. for (auto incomingFalseBlock : incomingFalses)
  3482. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3483. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3484. mBfIRBuilder->CreateRet(phi);
  3485. mCurMethodState->mHadReturn = true;
  3486. }
  3487. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  3488. {
  3489. BfExprEvaluator exprEvaluator(this);
  3490. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3491. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3492. BfTypedValue result = exprEvaluator.GetResult();
  3493. if ((result) && (!result.mType->IsVar()))
  3494. {
  3495. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3496. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3497. mBfIRBuilder->AddBlock(nextBB);
  3498. mBfIRBuilder->SetInsertPoint(nextBB);
  3499. }
  3500. }
  3501. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3502. {
  3503. if (mCurMethodInstance->mHasFailed)
  3504. return;
  3505. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  3506. return;
  3507. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3508. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3509. SizedArray<BfIRType, 4> paramTypes;
  3510. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3511. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3512. mBfIRBuilder->SetActiveFunction(func);
  3513. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3514. mBfIRBuilder->SetInsertPoint(entryBlock);
  3515. BfMethodState methodState;
  3516. methodState.mIRHeadBlock = entryBlock;
  3517. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3518. SizedArray<BfIRValue, 8> args;
  3519. BfExprEvaluator exprEvaluator(this);
  3520. if (mCurMethodInstance->GetStructRetIdx() != -1)
  3521. {
  3522. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3523. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3524. }
  3525. if (mCurMethodInstance->HasThis())
  3526. {
  3527. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  3528. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3529. }
  3530. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3531. {
  3532. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3533. if (paramType->IsValuelessType())
  3534. continue;
  3535. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  3536. }
  3537. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3538. mBfIRBuilder->CreateRetVoid();
  3539. }
  3540. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  3541. {
  3542. if (mCurMethodInstance->mIsUnspecialized)
  3543. return;
  3544. if (mCurTypeInstance->IsTypedPrimitive())
  3545. return;
  3546. if (mBfIRBuilder->mIgnoreWrites)
  3547. return;
  3548. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3549. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3550. bool isValid = true;
  3551. auto compareDType = compareType->ToDependedType();
  3552. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3553. if (compareTypeInst != NULL)
  3554. {
  3555. if (compareType->IsPrimitiveType())
  3556. compareTypeInst = GetWrappedStructType(compareType);
  3557. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3558. {
  3559. isValid = false;
  3560. }
  3561. mBfIRBuilder->PopulateType(compareTypeInst);
  3562. }
  3563. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3564. if (!isValid)
  3565. {
  3566. ClearLifetimeEnds();
  3567. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3568. return;
  3569. }
  3570. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3571. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3572. if (refNode == NULL)
  3573. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3574. UpdateSrcPos(refNode);
  3575. SetIllegalSrcPos();
  3576. auto resultVal = CreateAlloca(boolType);
  3577. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3578. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3579. if (compareType->IsValuelessType())
  3580. {
  3581. // Always equal, nothing to do
  3582. }
  3583. else if (compareType->IsSizedArray())
  3584. {
  3585. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3586. if (sizedArrayType->mElementCount > 6)
  3587. {
  3588. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3589. auto itr = CreateAlloca(intPtrType);
  3590. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3591. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3592. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3593. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3594. mBfIRBuilder->CreateBr(loopBB);
  3595. mBfIRBuilder->SetInsertPoint(loopBB);
  3596. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3597. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3598. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3599. mBfIRBuilder->SetInsertPoint(bodyBB);
  3600. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3601. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3602. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3603. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3604. mBfIRBuilder->CreateStore(incValue, itr);
  3605. mBfIRBuilder->CreateBr(loopBB);
  3606. mBfIRBuilder->SetInsertPoint(doneBB);
  3607. }
  3608. else
  3609. {
  3610. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3611. {
  3612. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3613. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3614. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3615. }
  3616. }
  3617. }
  3618. else if (compareType->IsMethodRef())
  3619. {
  3620. auto methodRefType = (BfMethodRefType*)compareType;
  3621. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3622. BfExprEvaluator exprEvaluator(this);
  3623. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3624. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3625. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3626. // values for the same method reference -- they will always refer back to the same local variables.
  3627. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3628. if (dataIdx != -1)
  3629. {
  3630. bool failed = false;
  3631. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3632. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3633. BF_ASSERT(!failed);
  3634. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3635. }
  3636. }
  3637. else if (compareTypeInst->IsEnum())
  3638. {
  3639. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3640. BfExprEvaluator exprEvaluator(this);
  3641. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3642. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3643. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3644. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3645. leftValue = LoadValue(leftValue);
  3646. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3647. rightValue = LoadValue(rightValue);
  3648. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3649. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3650. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3651. int enumCount = 0;
  3652. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3653. {
  3654. BfFieldInstance* fieldInstance = &fieldRef;
  3655. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3656. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3657. {
  3658. enumCount = -fieldInstance->mDataIdx;
  3659. }
  3660. }
  3661. if (enumCount > 0)
  3662. {
  3663. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3664. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3665. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3666. {
  3667. BfFieldInstance* fieldInstance = &fieldRef;
  3668. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3669. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3670. {
  3671. int enumIdx = -fieldInstance->mDataIdx - 1;
  3672. if (fieldInstance->mResolvedType->mSize == 0)
  3673. {
  3674. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3675. }
  3676. else
  3677. {
  3678. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3679. mBfIRBuilder->SetInsertPoint(caseBlock);
  3680. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3681. BfTypedValue leftTuple;
  3682. BfTypedValue rightTuple;
  3683. if (leftPayload.IsAddr())
  3684. {
  3685. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3686. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3687. }
  3688. else
  3689. {
  3690. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3691. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3692. }
  3693. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  3694. mBfIRBuilder->CreateBr(matchedBlock);
  3695. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3696. }
  3697. }
  3698. }
  3699. mBfIRBuilder->AddBlock(matchedBlock);
  3700. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3701. }
  3702. }
  3703. else if (compareTypeInst->IsUnion())
  3704. {
  3705. auto innerType = compareTypeInst->GetUnionInnerType();
  3706. if (!innerType->IsValuelessType())
  3707. {
  3708. BfExprEvaluator exprEvaluator(this);
  3709. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3710. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3711. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3712. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3713. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  3714. }
  3715. }
  3716. else
  3717. {
  3718. BfExprEvaluator exprEvaluator(this);
  3719. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3720. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3721. bool hadComparison = false;
  3722. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3723. {
  3724. BfFieldInstance* fieldInstance = &fieldRef;
  3725. if (fieldInstance->mDataOffset == -1)
  3726. continue;
  3727. if (fieldInstance->mResolvedType->IsValuelessType())
  3728. continue;
  3729. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3730. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3731. if (!fieldInstance->mResolvedType->IsComposite())
  3732. {
  3733. leftValue = LoadValue(leftValue);
  3734. rightValue = LoadValue(rightValue);
  3735. }
  3736. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3737. }
  3738. auto baseTypeInst = compareTypeInst->mBaseType;
  3739. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3740. {
  3741. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  3742. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  3743. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3744. }
  3745. }
  3746. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3747. mBfIRBuilder->CreateBr(exitBB);
  3748. mBfIRBuilder->AddBlock(exitBB);
  3749. mBfIRBuilder->SetInsertPoint(exitBB);
  3750. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3751. ClearLifetimeEnds();
  3752. mBfIRBuilder->CreateRet(loadedResult);
  3753. mCurMethodState->mHadReturn = true;
  3754. }
  3755. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3756. {
  3757. if (mBfIRBuilder->mIgnoreWrites)
  3758. return mBfIRBuilder->GetFakeVal();
  3759. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3760. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3761. BfIRValue* globalVariablePtr = NULL;
  3762. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3763. int numElements = 1;
  3764. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3765. {
  3766. numElements += mCompiler->mMaxInterfaceSlots;
  3767. auto maxIFaceVirtIdx = 0;
  3768. if (!typeInstance->IsInterface())
  3769. {
  3770. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3771. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3772. numElements += typeInstance->GetOrigVTableSize();
  3773. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3774. if (typeInstance->mHotTypeData != NULL)
  3775. {
  3776. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3777. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3778. }
  3779. numElements += ifaceMethodLen;
  3780. }
  3781. if (outNumElements != NULL)
  3782. *outNumElements = numElements;
  3783. }
  3784. StringT<128> classVDataName;
  3785. String memberName = "sBfClassVData";
  3786. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3787. {
  3788. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3789. memberName += "_";
  3790. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3791. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3792. }
  3793. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3794. if (outMangledName != NULL)
  3795. *outMangledName = classVDataName;
  3796. /*if (itr != mClassVDataRefs.end())
  3797. {
  3798. globalVariable = itr->second;
  3799. }*/
  3800. BfIRValue globalVariable;
  3801. if (globalVariablePtr != NULL)
  3802. {
  3803. globalVariable = *globalVariablePtr;
  3804. }
  3805. else
  3806. {
  3807. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3808. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3809. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3810. arrayType,
  3811. true,
  3812. BfIRLinkageType_External,
  3813. BfIRValue(),
  3814. classVDataName);
  3815. mClassVDataRefs[typeInstance] = globalVariable;
  3816. }
  3817. return globalVariable;
  3818. }
  3819. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3820. {
  3821. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3822. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3823. }
  3824. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3825. {
  3826. if (mBfIRBuilder->mIgnoreWrites)
  3827. return mBfIRBuilder->GetFakeVal();
  3828. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3829. BF_ASSERT(numElements >= 0);
  3830. if (numElements <= 0)
  3831. return BfIRValue();
  3832. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3833. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3834. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3835. BF_ASSERT(declTypeInst == implTypeInst);
  3836. else
  3837. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3838. if (declTypeInst != implTypeInst)
  3839. {
  3840. BfTypeInstance* highestImpl = declTypeInst;
  3841. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3842. {
  3843. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3844. break; // Start of an ext entry for another type
  3845. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3846. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3847. highestImpl = checkImplTypeInst;
  3848. }
  3849. if (highestImpl != implTypeInst)
  3850. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3851. }
  3852. BfVDataExtEntry mapEntry;
  3853. mapEntry.mDeclTypeInst = declTypeInst;
  3854. mapEntry.mImplTypeInst = implTypeInst;
  3855. BfIRValue* irValuePtr = NULL;
  3856. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3857. return *irValuePtr;
  3858. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3859. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3860. StringT<128> classVDataName;
  3861. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3862. if (declTypeInst != implTypeInst)
  3863. {
  3864. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3865. }
  3866. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3867. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3868. SizedArray<BfIRValue, 32> vData;
  3869. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3870. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3871. {
  3872. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3873. break; // Start of an ext entry for another type
  3874. BfIRValue vValue;
  3875. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3876. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3877. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3878. {
  3879. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3880. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3881. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3882. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3883. {
  3884. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3885. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  3886. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3887. vValue = funcPtr;
  3888. }
  3889. }
  3890. if (!vValue)
  3891. vValue = voidPtrNull;
  3892. vData.Add(vValue);
  3893. }
  3894. BF_ASSERT((int)vData.size() == numElements);
  3895. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3896. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3897. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3898. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3899. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3900. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3901. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3902. mClassVDataExtRefs[mapEntry] = globalVariable;
  3903. return globalVariable;
  3904. }
  3905. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3906. {
  3907. if (mBfIRBuilder->mIgnoreWrites)
  3908. {
  3909. return mBfIRBuilder->CreateTypeOf(type);
  3910. }
  3911. BfIRValue globalVariable;
  3912. BfIRValue* globalVariablePtr = NULL;
  3913. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3914. {
  3915. globalVariable = *globalVariablePtr;
  3916. if (globalVariable)
  3917. return globalVariable;
  3918. }
  3919. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3920. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3921. auto typeInstance = type->ToTypeInstance();
  3922. StringT<128> typeDataName;
  3923. if (typeInstance != NULL)
  3924. {
  3925. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3926. }
  3927. else
  3928. {
  3929. typeDataName += "sBfTypeData.";
  3930. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  3931. }
  3932. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3933. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3934. mTypeDataRefs[type] = globalVariable;
  3935. return globalVariable;
  3936. }
  3937. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3938. {
  3939. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3940. return BfIRValue();
  3941. BfIRValue* irValuePtr = NULL;
  3942. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3943. {
  3944. return *irValuePtr;
  3945. }
  3946. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3947. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3948. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3949. if (typeInstanceType == NULL)
  3950. {
  3951. AssertErrorState();
  3952. return BfIRValue();
  3953. }
  3954. BfIRValue typeTypeData;
  3955. int typeFlags = 0;
  3956. if (needsTypeData)
  3957. {
  3958. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3959. BfTypeInstance* typeDataSource = NULL;
  3960. if (typeInstance != NULL)
  3961. {
  3962. if (typeInstance->IsUnspecializedType())
  3963. {
  3964. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3965. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3966. }
  3967. else if (typeInstance->IsArray())
  3968. {
  3969. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3970. typeFlags |= BfTypeFlags_Array;
  3971. }
  3972. else if (typeInstance->IsGenericTypeInstance())
  3973. {
  3974. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3975. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3976. }
  3977. else
  3978. typeDataSource = typeInstanceTypeInstance;
  3979. }
  3980. else if (type->IsPointer())
  3981. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3982. else if (type->IsRef())
  3983. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  3984. else if (type->IsSizedArray())
  3985. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3986. else
  3987. typeDataSource = mContext->mBfTypeType;
  3988. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3989. {
  3990. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3991. }
  3992. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3993. }
  3994. else
  3995. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3996. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3997. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3998. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3999. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4000. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4001. BfType* typeIdType = intType;
  4002. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4003. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4004. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4005. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4006. SizedArray<BfIRValue, 4> typeValueParams;
  4007. GetConstClassValueParam(typeTypeData, typeValueParams);
  4008. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4009. StringT<128> typeDataName;
  4010. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4011. {
  4012. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4013. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4014. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4015. }
  4016. else
  4017. {
  4018. typeDataName += "sBfTypeData.";
  4019. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4020. }
  4021. int typeCode = BfTypeCode_None;
  4022. if (typeInstance != NULL)
  4023. {
  4024. typeCode = typeInstance->mTypeDef->mTypeCode;
  4025. }
  4026. else if (type->IsPrimitiveType())
  4027. {
  4028. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4029. typeCode = primType->mTypeDef->mTypeCode;
  4030. }
  4031. else if (type->IsPointer())
  4032. {
  4033. typeCode = BfTypeCode_Pointer;
  4034. typeFlags |= BfTypeFlags_Pointer;
  4035. }
  4036. else if (type->IsRef())
  4037. {
  4038. typeCode = BfTypeCode_Pointer;
  4039. typeFlags |= BfTypeFlags_Pointer;
  4040. }
  4041. if (type->IsObject())
  4042. {
  4043. typeFlags |= BfTypeFlags_Object;
  4044. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4045. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4046. typeFlags |= BfTypeFlags_HasDestructor;
  4047. }
  4048. if (type->IsStruct())
  4049. typeFlags |= BfTypeFlags_Struct;
  4050. if (type->IsBoxed())
  4051. {
  4052. typeFlags |= BfTypeFlags_Boxed;
  4053. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4054. typeFlags |= BfTypeFlags_Pointer;
  4055. }
  4056. if (type->IsPrimitiveType())
  4057. typeFlags |= BfTypeFlags_Primitive;
  4058. if (type->IsTypedPrimitive())
  4059. typeFlags |= BfTypeFlags_TypedPrimitive;
  4060. if (type->IsTuple())
  4061. typeFlags |= BfTypeFlags_Tuple;
  4062. if (type->IsNullable())
  4063. typeFlags |= BfTypeFlags_Nullable;
  4064. if (type->IsSizedArray())
  4065. typeFlags |= BfTypeFlags_SizedArray;
  4066. if (type->IsSplattable())
  4067. typeFlags |= BfTypeFlags_Splattable;
  4068. if (type->IsUnion())
  4069. typeFlags |= BfTypeFlags_Union;
  4070. if (type->IsDelegate())
  4071. typeFlags |= BfTypeFlags_Delegate;
  4072. if (type->IsFunction())
  4073. typeFlags |= BfTypeFlags_Function;
  4074. if (type->WantsGCMarking())
  4075. typeFlags |= BfTypeFlags_WantsMarking;
  4076. int memberDataOffset = 0;
  4077. if (typeInstance != NULL)
  4078. {
  4079. for (auto& fieldInstance : typeInstance->mFieldInstances)
  4080. {
  4081. if (fieldInstance.mDataOffset != -1)
  4082. {
  4083. memberDataOffset = fieldInstance.mDataOffset;
  4084. break;
  4085. }
  4086. }
  4087. }
  4088. SizedArray<BfIRValue, 8> typeDataParams =
  4089. {
  4090. objectData,
  4091. GetConstValue(type->mSize, intType), // mSize
  4092. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  4093. GetConstValue(typeFlags, intType), // mTypeFlags
  4094. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  4095. GetConstValue(typeCode, byteType), // mTypeCode
  4096. GetConstValue(type->mAlign, byteType),
  4097. };
  4098. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  4099. if (typeInstance == NULL)
  4100. {
  4101. BfIRValue typeDataVar;
  4102. if (needsTypeData)
  4103. {
  4104. if (type->IsPointer())
  4105. {
  4106. auto pointerType = (BfPointerType*)type;
  4107. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  4108. {
  4109. typeData,
  4110. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  4111. };
  4112. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4113. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  4114. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  4115. BfIRLinkageType_External, pointerTypeData, typeDataName);
  4116. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4117. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4118. }
  4119. else if (type->IsRef())
  4120. {
  4121. auto refType = (BfRefType*)type;
  4122. SizedArray<BfIRValue, 3> refTypeDataParms =
  4123. {
  4124. typeData,
  4125. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  4126. GetConstValue((int8)refType->mRefKind, byteType),
  4127. };
  4128. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4129. auto refTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  4130. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  4131. BfIRLinkageType_External, refTypeData, typeDataName);
  4132. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4133. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4134. }
  4135. else if (type->IsSizedArray())
  4136. {
  4137. auto sizedArrayType = (BfSizedArrayType*)type;
  4138. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  4139. {
  4140. typeData,
  4141. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  4142. GetConstValue(sizedArrayType->mElementCount, intType)
  4143. };
  4144. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4145. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  4146. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  4147. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  4148. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4149. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4150. }
  4151. else
  4152. {
  4153. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  4154. BfIRLinkageType_External, typeData, typeDataName);
  4155. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4156. }
  4157. }
  4158. else
  4159. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  4160. mTypeDataRefs[typeInstance] = typeDataVar;
  4161. return typeDataVar;
  4162. }
  4163. // Reserve position
  4164. mTypeDataRefs[typeInstance] = BfIRValue();
  4165. if (typeInstance->IsReified())
  4166. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4167. BfTypeDef* typeDef = typeInstance->mTypeDef;
  4168. StringT<128> mangledName;
  4169. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  4170. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4171. {
  4172. auto methodDef = typeDef->mMethods[methodIdx];
  4173. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  4174. if (methodInstance == NULL)
  4175. continue;
  4176. if (typeInstance->IsUnspecializedType())
  4177. continue;
  4178. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4179. {
  4180. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4181. {
  4182. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  4183. // We need to create an empty thunk for this chained method
  4184. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4185. mBfIRBuilder->SetActiveFunction(func);
  4186. auto block = mBfIRBuilder->CreateBlock("entry", true);
  4187. mBfIRBuilder->SetInsertPoint(block);
  4188. mBfIRBuilder->CreateRetVoid();
  4189. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  4190. }
  4191. }
  4192. }
  4193. SizedArray<BfIRValue, 32> vData;
  4194. BfIRValue classVDataVar;
  4195. String classVDataName;
  4196. if (typeInstance->mSlotNum >= 0)
  4197. {
  4198. // For interfaces we ONLY emit the slot num
  4199. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  4200. StringT<128> slotVarName;
  4201. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  4202. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4203. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  4204. GetConstValue32(virtSlotIdx), slotVarName);
  4205. }
  4206. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  4207. {
  4208. int dynCastDataElems = 0;
  4209. int numElements = 1;
  4210. int vDataOfs = 1; // The number of intptrs before the iface slot map
  4211. numElements += mCompiler->mMaxInterfaceSlots;
  4212. if (!typeInstance->IsInterface())
  4213. {
  4214. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4215. numElements += mCompiler->GetDynCastVDataCount();
  4216. numElements += typeInstance->mVirtualMethodTableSize;
  4217. }
  4218. int expectNumElements = 0;
  4219. if (!typeDef->mIsStatic)
  4220. {
  4221. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  4222. }
  4223. vData.push_back(BfIRValue()); // Type*
  4224. SizedArray<BfIRValue, 1> extVTableData;
  4225. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  4226. if (!typeInstance->IsInterface())
  4227. {
  4228. Array<int32> dynCastData;
  4229. if (typeInstance->IsBoxed())
  4230. {
  4231. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  4232. dynCastData.Add(underlyingType->mInheritanceId);
  4233. }
  4234. else
  4235. dynCastData.Add(typeInstance->mInheritanceId);
  4236. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  4237. dynCastData.Add(0);
  4238. dynCastData.Add(0);
  4239. auto checkTypeInst = typeInstance;
  4240. while (checkTypeInst != NULL)
  4241. {
  4242. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4243. {
  4244. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  4245. {
  4246. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  4247. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  4248. }
  4249. }
  4250. checkTypeInst = checkTypeInst->GetImplBaseType();
  4251. }
  4252. if (mSystem->mPtrSize == 8)
  4253. {
  4254. int intPtrCount = (dynCastDataElems + 1) / 2;
  4255. vDataOfs += intPtrCount;
  4256. uint64* intPtrData = (uint64*)&dynCastData[0];
  4257. for (int i = 0; i < intPtrCount; i++)
  4258. {
  4259. uint64 val = intPtrData[i];
  4260. if (val == 0)
  4261. {
  4262. vData.push_back(voidPtrNull);
  4263. }
  4264. else
  4265. {
  4266. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4267. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4268. }
  4269. }
  4270. }
  4271. else
  4272. {
  4273. int intPtrCount = dynCastDataElems;
  4274. vDataOfs += intPtrCount;
  4275. uint32* intPtrData = (uint32*)&dynCastData[0];
  4276. for (int i = 0; i < intPtrCount; i++)
  4277. {
  4278. uint32 val = intPtrData[i];
  4279. if (val == 0)
  4280. {
  4281. vData.push_back(voidPtrNull);
  4282. }
  4283. else
  4284. {
  4285. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  4286. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4287. }
  4288. }
  4289. }
  4290. }
  4291. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  4292. vData.push_back(voidPtrNull);
  4293. struct _InterfaceMatchEntry
  4294. {
  4295. BfTypeInterfaceEntry* mEntry;
  4296. BfTypeInstance* mEntrySource;
  4297. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  4298. };
  4299. int highestIFaceVirtIdx = 0;
  4300. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  4301. auto checkTypeInst = typeInstance;
  4302. bool forceInterfaceSet = false;
  4303. while (checkTypeInst != NULL)
  4304. {
  4305. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4306. {
  4307. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  4308. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  4309. continue;
  4310. _InterfaceMatchEntry* matchEntry = NULL;
  4311. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  4312. {
  4313. auto prevEntry = matchEntry->mEntry;
  4314. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  4315. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  4316. if (forceInterfaceSet)
  4317. {
  4318. isBetter = true;
  4319. isWorse = false;
  4320. }
  4321. if (isBetter == isWorse)
  4322. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4323. if (isBetter == isWorse)
  4324. {
  4325. if (matchEntry->mAmbiguousEntries.empty())
  4326. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4327. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4328. continue;
  4329. }
  4330. else if (isBetter)
  4331. {
  4332. matchEntry->mEntry = &interfaceEntry;
  4333. matchEntry->mEntrySource = checkTypeInst;
  4334. matchEntry->mAmbiguousEntries.Clear();
  4335. }
  4336. else
  4337. continue;
  4338. }
  4339. else
  4340. {
  4341. _InterfaceMatchEntry matchEntry;
  4342. matchEntry.mEntry = &interfaceEntry;
  4343. matchEntry.mEntrySource = checkTypeInst;
  4344. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4345. }
  4346. }
  4347. checkTypeInst = checkTypeInst->GetImplBaseType();
  4348. }
  4349. for (auto interfacePair : interfaceMap)
  4350. {
  4351. auto& interfaceMatchEntry = interfacePair.mValue;
  4352. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4353. {
  4354. 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());
  4355. if (error != NULL)
  4356. {
  4357. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4358. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4359. }
  4360. }
  4361. }
  4362. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4363. {
  4364. int startTabIdx = (int)vData.size();
  4365. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4366. BfTypeInstance* checkTypeInst = typeInstance;
  4367. while (checkTypeInst != NULL)
  4368. {
  4369. origVirtTypeStack.push_back(checkTypeInst);
  4370. checkTypeInst = checkTypeInst->GetImplBaseType();
  4371. }
  4372. Array<BfVirtualMethodEntry> origVTable;
  4373. int origVirtIdx = 0;
  4374. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4375. {
  4376. HashSet<String> reslotNames;
  4377. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4378. {
  4379. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4380. if (entry.mDeclaringMethod.mMethodNum == -1)
  4381. continue;
  4382. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4383. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4384. {
  4385. if (origVTable.empty())
  4386. origVTable = typeInstance->mVirtualMethodTable;
  4387. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4388. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4389. {
  4390. // Prepare to reslot...
  4391. entry.mImplementingMethod = entry.mDeclaringMethod;
  4392. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4393. }
  4394. else
  4395. {
  4396. // Decl isn't accessible, null out entry
  4397. entry.mImplementingMethod = BfMethodRef();
  4398. }
  4399. }
  4400. }
  4401. if (!reslotNames.IsEmpty())
  4402. {
  4403. BfAmbiguityContext ambiguityContext;
  4404. ambiguityContext.mTypeInstance = typeInstance;
  4405. ambiguityContext.mModule = this;
  4406. ambiguityContext.mIsProjectSpecific = true;
  4407. ambiguityContext.mIsReslotting = true;
  4408. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4409. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4410. {
  4411. auto methodInstance = methodGroup.mDefault;
  4412. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4413. continue;
  4414. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4415. continue;
  4416. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4417. continue;
  4418. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4419. continue;
  4420. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4421. }
  4422. ambiguityContext.Finish();
  4423. }
  4424. }
  4425. bool isInExts = false;
  4426. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4427. {
  4428. BfIRValue vValue = voidPtrNull;
  4429. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4430. BfModuleMethodInstance moduleMethodInst;
  4431. if (entry.mDeclaringMethod.mMethodNum == -1)
  4432. {
  4433. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4434. isInExts = true;
  4435. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4436. if (vExt)
  4437. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4438. }
  4439. else
  4440. {
  4441. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4442. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4443. {
  4444. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4445. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4446. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4447. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4448. {
  4449. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4450. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4451. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4452. vValue = funcPtr;
  4453. }
  4454. }
  4455. }
  4456. while (origVirtTypeStack.size() != 0)
  4457. {
  4458. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4459. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4460. {
  4461. // Moved past current base vtable size
  4462. origVirtTypeStack.pop_back();
  4463. continue;
  4464. }
  4465. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4466. {
  4467. // We are within the original vtable size
  4468. int idx = startTabIdx + origVirtIdx;
  4469. origVirtIdx++;
  4470. vData.push_back(vValue);
  4471. }
  4472. else
  4473. {
  4474. // This is a new entry, it only gets added to the ext
  4475. BF_ASSERT(isInExts);
  4476. }
  4477. break;
  4478. }
  4479. }
  4480. if (!origVTable.empty())
  4481. typeInstance->mVirtualMethodTable = origVTable;
  4482. }
  4483. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4484. if (typeInstance->mHotTypeData != NULL)
  4485. {
  4486. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4487. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4488. }
  4489. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4490. int iFaceMethodStartIdx = (int)vData.size();
  4491. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4492. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4493. vData[i] = voidPtrNull;
  4494. if (expectNumElements != 0)
  4495. BF_ASSERT(expectNumElements == vData.size());
  4496. //BF_ASSERT(vData.size() == expectNumElements);
  4497. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4498. // ifaceMethodExtData.Add(voidPtrNull);
  4499. int ifaceEntryIdx = iFaceMethodStartIdx;
  4500. for (auto& interfacePair : interfaceMap)
  4501. {
  4502. auto interfaceEntry = interfacePair.mValue.mEntry;
  4503. bool makeEmpty = false;
  4504. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4505. makeEmpty = true;
  4506. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4507. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4508. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4509. {
  4510. BfIRValue pushValue;
  4511. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4512. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4513. continue;
  4514. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4515. continue;
  4516. if (makeEmpty)
  4517. {
  4518. pushValue = voidPtrNull;
  4519. }
  4520. else
  4521. {
  4522. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4523. auto methodInstance = (BfMethodInstance*)methodRef;
  4524. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4525. {
  4526. BF_ASSERT(methodInstance->mIsReified);
  4527. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4528. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4529. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4530. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4531. pushValue = funcPtr;
  4532. }
  4533. else
  4534. {
  4535. pushValue = voidPtrNull;
  4536. }
  4537. }
  4538. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4539. if (idx < ifaceMethodExtStart)
  4540. {
  4541. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4542. vData[iFaceMethodStartIdx + idx] = pushValue;
  4543. }
  4544. else
  4545. {
  4546. BF_ASSERT(useExt);
  4547. int extIdx = idx - ifaceMethodExtStart;
  4548. while (extIdx >= ifaceMethodExtData.size())
  4549. ifaceMethodExtData.Add(voidPtrNull);
  4550. ifaceMethodExtData[extIdx] = pushValue;
  4551. }
  4552. }
  4553. }
  4554. if (typeInstance->IsBoxed())
  4555. {
  4556. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4557. if (boxedType->IsBoxedStructPtr())
  4558. {
  4559. // Force override of GetHashCode so we use the pointer address as the hash code
  4560. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4561. // Force override of GetHashCode so we use the pointer address as the hash code
  4562. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4563. {
  4564. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4565. {
  4566. BfIRValue pushValue;
  4567. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4568. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4569. continue;
  4570. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4571. continue;
  4572. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4573. auto methodInstance = (BfMethodInstance*)methodRef;
  4574. BF_ASSERT(methodInstance->mIsReified);
  4575. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4576. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4577. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4578. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4579. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4580. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4581. }
  4582. }
  4583. }
  4584. }
  4585. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4586. {
  4587. BfIRValue ifaceMethodExtVar;
  4588. if (!ifaceMethodExtData.IsEmpty())
  4589. {
  4590. StringT<128> classVDataName;
  4591. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4592. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4593. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4594. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4595. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4596. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4597. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4598. }
  4599. for (auto& ifaceInstPair : interfaceMap)
  4600. {
  4601. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4602. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4603. if (slotNum >= 0)
  4604. {
  4605. BfIRValue vtablePtr;
  4606. int idx = interfaceEntry->mStartVirtualIdx;
  4607. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4608. if (endVirtualIdx > ifaceMethodExtStart)
  4609. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4610. else
  4611. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4612. int slotVirtIdx = slotNum + vDataOfs;
  4613. if (vData[slotVirtIdx] == voidPtrNull)
  4614. {
  4615. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4616. }
  4617. else
  4618. {
  4619. if (mCompiler->IsHotCompile())
  4620. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4621. else
  4622. Fail("Interface slot collision error", typeDef->GetRefNode());
  4623. }
  4624. }
  4625. }
  4626. }
  4627. }
  4628. BfIRValue typeNameConst;
  4629. BfIRValue namespaceConst;
  4630. if (needsTypeNames)
  4631. {
  4632. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4633. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4634. }
  4635. else
  4636. {
  4637. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4638. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4639. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4640. }
  4641. int baseTypeId = 0;
  4642. if (typeInstance->mBaseType != NULL)
  4643. {
  4644. baseTypeId = typeInstance->mBaseType->mTypeId;
  4645. }
  4646. BfTypeOptions* typeOptions = NULL;
  4647. if (typeInstance->mTypeOptionsIdx >= 0)
  4648. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  4649. SizedArray<BfIRValue, 16> customAttrs;
  4650. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4651. BfIRValue castedClassVData;
  4652. if (classVDataVar)
  4653. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4654. else
  4655. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4656. bool freflectIncludeTypeData = false;
  4657. bool reflectIncludeAllFields = false;
  4658. bool reflectIncludeAllMethods = false;
  4659. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4660. {
  4661. reflectIncludeAllFields = true;
  4662. reflectIncludeAllMethods = true;
  4663. }
  4664. enum ReflectKind
  4665. {
  4666. ReflectKind_None = 0,
  4667. ReflectKind_Type = 1,
  4668. ReflectKind_NonStaticFields = 2,
  4669. ReflectKind_StaticFields = 4,
  4670. ReflectKind_DefaultConstructor = 8,
  4671. ReflectKind_Constructors = 0x10,
  4672. ReflectKind_StaticMethods = 0x20,
  4673. ReflectKind_Methods = 0x40,
  4674. ReflectKind_User = 0x80,
  4675. ReflectKind_All = 0x7F,
  4676. ReflectKind_ApplyToInnerTypes = 0x80
  4677. };
  4678. ReflectKind reflectKind = ReflectKind_Type;
  4679. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4680. {
  4681. ReflectKind reflectKind = ReflectKind_None;
  4682. if (attrType->mCustomAttributes != NULL)
  4683. {
  4684. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4685. {
  4686. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4687. {
  4688. for (auto& prop : customAttr.mSetProperties)
  4689. {
  4690. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4691. if (propDef->mName == "ReflectUser")
  4692. {
  4693. if (prop.mParam.mValue.IsConst())
  4694. {
  4695. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4696. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4697. }
  4698. }
  4699. }
  4700. // Check for Flags arg
  4701. if (customAttr.mCtorArgs.size() < 2)
  4702. continue;
  4703. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4704. if (constant == NULL)
  4705. continue;
  4706. if (constant->mTypeCode == BfTypeCode_Boolean)
  4707. continue;
  4708. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4709. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4710. }
  4711. }
  4712. }
  4713. return reflectKind;
  4714. };
  4715. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4716. {
  4717. ReflectKind reflectKind = ReflectKind_None;
  4718. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4719. if (customAttrs != NULL)
  4720. {
  4721. for (auto& attr : customAttrs->mAttributes)
  4722. {
  4723. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4724. }
  4725. }
  4726. return reflectKind;
  4727. };
  4728. //
  4729. {
  4730. auto checkTypeInstance = typeInstance;
  4731. while (checkTypeInstance != NULL)
  4732. {
  4733. if (checkTypeInstance->mCustomAttributes != NULL)
  4734. {
  4735. auto checkReflectKind = ReflectKind_None;
  4736. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4737. {
  4738. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4739. {
  4740. if (customAttr.mCtorArgs.size() > 0)
  4741. {
  4742. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4743. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4744. }
  4745. else
  4746. {
  4747. checkReflectKind = ReflectKind_All;
  4748. }
  4749. }
  4750. else
  4751. {
  4752. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4753. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4754. }
  4755. }
  4756. if ((checkTypeInstance == typeInstance) ||
  4757. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4758. {
  4759. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4760. }
  4761. }
  4762. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  4763. }
  4764. }
  4765. // Fields
  4766. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4767. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4768. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4769. {
  4770. if (customAttributes == NULL)
  4771. return -1;
  4772. Array<BfCustomAttribute*> reflectAttributes;
  4773. for (auto& attr : customAttributes->mAttributes)
  4774. {
  4775. bool wantAttribute = false;
  4776. if (attr.mType->mCustomAttributes != NULL)
  4777. {
  4778. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4779. if (usageAttribute != NULL)
  4780. {
  4781. // Check for Flags arg
  4782. if (usageAttribute->mCtorArgs.size() < 2)
  4783. continue;
  4784. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4785. if (constant == NULL)
  4786. continue;
  4787. if (constant->mTypeCode == BfTypeCode_Boolean)
  4788. continue;
  4789. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4790. wantAttribute = true;
  4791. }
  4792. }
  4793. if ((wantAttribute) && (attr.mType->mIsReified))
  4794. {
  4795. reflectAttributes.Add(&attr);
  4796. }
  4797. }
  4798. if (reflectAttributes.size() == 0)
  4799. return -1;
  4800. #define PUSH_INT8(val) data.push_back((uint8)val)
  4801. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4802. #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); }
  4803. #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); \
  4804. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4805. SizedArray<uint8, 16> data;
  4806. int customAttrIdx = (int)customAttrs.size();
  4807. data.push_back((uint8)reflectAttributes.size());
  4808. for (auto attr : reflectAttributes)
  4809. {
  4810. // Size prefix
  4811. int sizeIdx = (int)data.size();
  4812. PUSH_INT16(0); // mSize
  4813. PUSH_INT32(attr->mType->mTypeId); // mType
  4814. PUSH_INT16(attr->mCtor->mIdx);
  4815. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4816. int argIdx = 0;
  4817. for (auto arg : attr->mCtorArgs)
  4818. {
  4819. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4820. bool handled = false;
  4821. if (constant != NULL)
  4822. {
  4823. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4824. if (argType->IsObject())
  4825. {
  4826. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4827. int stringId = constant->mInt32;
  4828. int* orderedIdPtr;
  4829. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4830. {
  4831. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4832. }
  4833. GetStringObjectValue(stringId);
  4834. PUSH_INT8(0xFF); // String
  4835. PUSH_INT32(*orderedIdPtr);
  4836. continue;
  4837. }
  4838. PUSH_INT8(constant->mTypeCode);
  4839. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4840. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4841. (constant->mTypeCode == BfTypeCode_Double))
  4842. {
  4843. PUSH_INT64(constant->mInt64);
  4844. }
  4845. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4846. (constant->mTypeCode == BfTypeCode_UInt32))
  4847. {
  4848. PUSH_INT32(constant->mInt32);
  4849. }
  4850. else if (constant->mTypeCode == BfTypeCode_Float)
  4851. {
  4852. float val = (float)constant->mDouble;
  4853. PUSH_INT32(*(int*)&val);
  4854. }
  4855. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4856. (constant->mTypeCode == BfTypeCode_UInt16))
  4857. {
  4858. PUSH_INT16(constant->mInt16);
  4859. }
  4860. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4861. (constant->mTypeCode == BfTypeCode_UInt8))
  4862. {
  4863. PUSH_INT8(constant->mInt8);
  4864. }
  4865. else if (constant->mTypeCode == BfTypeCode_Object)
  4866. {
  4867. BFMODULE_FATAL(this, "Unhandled");
  4868. }
  4869. else
  4870. {
  4871. BFMODULE_FATAL(this, "Unhandled");
  4872. }
  4873. }
  4874. else if (!handled)
  4875. {
  4876. BFMODULE_FATAL(this, "Unhandled");
  4877. }
  4878. argIdx++;
  4879. }
  4880. int size = (int)data.size() - sizeIdx;
  4881. *((uint16*)&data[sizeIdx]) = size;
  4882. }
  4883. #undef PUSH_INT8
  4884. #undef PUSH_INT16
  4885. #undef PUSH_INT32
  4886. SizedArray<BfIRValue, 16> dataValues;
  4887. for (uint8 val : data)
  4888. dataValues.push_back(GetConstValue8(val));
  4889. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4890. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4891. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4892. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4893. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4894. customAttrs.push_back(customAttrArrayPtr);
  4895. return customAttrIdx;
  4896. };
  4897. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4898. SizedArray<int, 16> reflectFieldIndices;
  4899. for (int pass = 0; pass < 2; pass++)
  4900. {
  4901. bool skippedField = false;
  4902. reflectFieldIndices.clear();
  4903. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4904. {
  4905. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4906. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4907. if (fieldDef == NULL)
  4908. continue;
  4909. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4910. bool includeField = reflectIncludeAllFields;
  4911. if (fieldInstance->mCustomAttributes != NULL)
  4912. {
  4913. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4914. {
  4915. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4916. {
  4917. includeField = true;
  4918. }
  4919. else
  4920. {
  4921. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4922. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4923. }
  4924. }
  4925. }
  4926. if ((fieldReflectKind & ReflectKind_User) != 0)
  4927. includeField = true;
  4928. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4929. includeField = true;
  4930. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4931. includeField = true;
  4932. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  4933. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  4934. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  4935. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  4936. includeField |= forceReflectFields;
  4937. if (!includeField)
  4938. {
  4939. skippedField = true;
  4940. continue;
  4941. }
  4942. reflectFieldIndices.Add(fieldIdx);
  4943. }
  4944. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4945. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4946. // possible because we write out a SplatData structure containing just TypeIds in that case
  4947. if (pass == 0)
  4948. {
  4949. if (!typeInstance->IsSplattable())
  4950. break;
  4951. if (!skippedField)
  4952. break;
  4953. if (reflectFieldIndices.size() == 0)
  4954. break;
  4955. }
  4956. }
  4957. SizedArray<BfIRValue, 16> fieldTypes;
  4958. enum FieldFlags
  4959. {
  4960. FieldFlags_Protected = 3,
  4961. FieldFlags_Public = 6,
  4962. FieldFlags_Static = 0x10,
  4963. FieldFlags_Const = 0x40,
  4964. FieldFlags_SpecialName = 0x80,
  4965. FieldFlags_EnumPayload = 0x100,
  4966. FieldFlags_EnumDiscriminator = 0x200
  4967. };
  4968. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4969. {
  4970. BfType* payloadType = typeInstance->GetUnionInnerType();
  4971. if (!payloadType->IsValuelessType())
  4972. {
  4973. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4974. SizedArray<BfIRValue, 8> payloadFieldVals =
  4975. {
  4976. emptyValueType,
  4977. payloadNameConst, // mName
  4978. GetConstValue(0, intPtrType), // mData
  4979. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4980. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4981. GetConstValue(-1, intType), // mCustomAttributesIdx
  4982. };
  4983. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4984. fieldTypes.push_back(payloadFieldData);
  4985. }
  4986. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4987. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4988. SizedArray<BfIRValue, 8> dscrFieldVals =
  4989. {
  4990. emptyValueType,
  4991. dscrNameConst, // mName
  4992. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  4993. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4994. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4995. GetConstValue(-1, intType), // mCustomAttributesIdx
  4996. };
  4997. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4998. fieldTypes.push_back(dscrFieldData);
  4999. }
  5000. for (auto fieldIdx : reflectFieldIndices)
  5001. {
  5002. if (!needsTypeData)
  5003. break;
  5004. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5005. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5006. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  5007. int typeId = 0;
  5008. auto fieldType = fieldInstance->GetResolvedType();
  5009. if (fieldType->IsGenericParam())
  5010. {
  5011. //TODO:
  5012. }
  5013. else
  5014. typeId = fieldType->mTypeId;
  5015. FieldFlags fieldFlags = (FieldFlags)0;
  5016. if (fieldDef->mProtection == BfProtection_Protected)
  5017. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  5018. if (fieldDef->mProtection == BfProtection_Public)
  5019. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  5020. if (fieldDef->mIsStatic)
  5021. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  5022. if (fieldDef->mIsConst)
  5023. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  5024. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  5025. BfIRValue constValue;
  5026. if (fieldInstance->GetFieldDef()->mIsConst)
  5027. {
  5028. if (fieldInstance->mConstIdx != -1)
  5029. {
  5030. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5031. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, constant->mUInt64);
  5032. }
  5033. }
  5034. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5035. {
  5036. auto refVal = ReferenceStaticField(fieldInstance);
  5037. if (refVal.IsAddr())
  5038. {
  5039. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5040. }
  5041. }
  5042. if (!constValue)
  5043. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5044. SizedArray<BfIRValue, 8> fieldVals =
  5045. {
  5046. emptyValueType,
  5047. fieldNameConst, // mName
  5048. constValue, // mConstValue
  5049. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5050. GetConstValue(fieldFlags, shortType), // mFlags
  5051. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  5052. };
  5053. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  5054. fieldTypes.push_back(fieldData);
  5055. }
  5056. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5057. BfIRValue fieldDataPtr;
  5058. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5059. if (fieldTypes.size() == 0)
  5060. {
  5061. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5062. {
  5063. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5064. SizedArray<BfIRValue, 3> splatTypes;
  5065. SizedArray<BfIRValue, 3> splatOffsets;
  5066. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5067. {
  5068. auto checkTypeInstance = checkType->ToTypeInstance();
  5069. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5070. PopulateType(checkTypeInstance);
  5071. if (checkType->IsStruct())
  5072. {
  5073. int dataEnd = offset;
  5074. if (checkTypeInstance->mBaseType != NULL)
  5075. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5076. if (checkTypeInstance->mIsUnion)
  5077. {
  5078. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5079. _CheckSplat(unionInnerType, offset);
  5080. }
  5081. else
  5082. {
  5083. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5084. {
  5085. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5086. if (fieldInstance->mDataIdx >= 0)
  5087. {
  5088. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5089. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5090. }
  5091. }
  5092. }
  5093. if (checkTypeInstance->IsEnum())
  5094. {
  5095. // Add discriminator
  5096. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5097. if (!checkTypeInstance->mIsPacked)
  5098. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5099. _CheckSplat(dscrType, dataEnd);
  5100. }
  5101. }
  5102. else if (checkType->IsMethodRef())
  5103. {
  5104. // auto methodRefType = (BfMethodRefType*)checkType;
  5105. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5106. // {
  5107. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5108. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5109. // else
  5110. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5111. // }
  5112. }
  5113. else if (!checkType->IsValuelessType())
  5114. {
  5115. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5116. splatOffsets.Add(GetConstValue(offset, intType));
  5117. }
  5118. };
  5119. _CheckSplat(type, 0);
  5120. while (splatTypes.size() < 3)
  5121. {
  5122. splatTypes.Add(GetConstValue(0, typeIdType));
  5123. splatOffsets.Add(GetConstValue(0, intType));
  5124. }
  5125. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5126. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  5127. SizedArray<BfIRValue, 8> splatVals =
  5128. {
  5129. emptyValueType,
  5130. splatTypesConst,
  5131. splatOffsetsConst
  5132. };
  5133. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  5134. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  5135. fieldSplatData, typeDataName + ".splats");
  5136. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5137. }
  5138. else
  5139. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  5140. }
  5141. else
  5142. {
  5143. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  5144. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  5145. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  5146. fieldDataConst, "fields." + typeDataName);
  5147. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5148. }
  5149. /// Methods
  5150. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  5151. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  5152. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  5153. SizedArray<BfIRValue, 16> methodTypes;
  5154. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5155. {
  5156. if (!needsTypeData)
  5157. break;
  5158. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  5159. if (!methodInstanceGroup->IsImplemented())
  5160. continue;
  5161. auto methodDef = typeDef->mMethods[methodIdx];
  5162. if (methodDef->mNoReflect)
  5163. continue;
  5164. auto defaultMethod = methodInstanceGroup->mDefault;
  5165. if (defaultMethod == NULL)
  5166. continue;
  5167. if (defaultMethod->mIsUnspecialized)
  5168. continue;
  5169. if (!defaultMethod->mIsReified)
  5170. continue;
  5171. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  5172. continue;
  5173. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  5174. continue;
  5175. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  5176. bool includeMethod = reflectIncludeAllMethods;
  5177. BfCustomAttributes* methodCustomAttributes = NULL;
  5178. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  5179. {
  5180. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  5181. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  5182. {
  5183. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5184. {
  5185. includeMethod = true;
  5186. }
  5187. else
  5188. {
  5189. auto userReflectKind = _GetReflectUser(customAttr.mType);
  5190. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  5191. }
  5192. }
  5193. }
  5194. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5195. continue;
  5196. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  5197. {
  5198. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  5199. {
  5200. if (paramDecl->mAttributes != NULL)
  5201. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  5202. }
  5203. if (methodDeclaration->mReturnAttributes != NULL)
  5204. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  5205. }
  5206. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  5207. includeMethod = true;
  5208. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  5209. includeMethod = true;
  5210. if (methodDef->mMethodType == BfMethodType_Ctor)
  5211. {
  5212. if (typeOptions != NULL)
  5213. includeMethod = typeOptions->Apply(includeMethod, BfOptionFlags_ReflectConstructors);
  5214. }
  5215. else
  5216. {
  5217. if ((!methodDef->mIsStatic) && (typeOptions != NULL))
  5218. includeMethod = typeOptions->Apply(includeMethod, BfOptionFlags_ReflectNonStaticMethods);
  5219. if ((methodDef->mIsStatic) && (typeOptions != NULL))
  5220. includeMethod = typeOptions->Apply(includeMethod, BfOptionFlags_ReflectStaticMethods);
  5221. }
  5222. if (!includeMethod)
  5223. continue;
  5224. BfModuleMethodInstance moduleMethodInstance;
  5225. BfIRValue funcVal = voidPtrNull;
  5226. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  5227. (!typeInstance->IsUnspecializedType()) &&
  5228. (methodDef->mMethodType != BfMethodType_Ignore) &&
  5229. (methodDef->mMethodType != BfMethodType_Mixin) &&
  5230. (!methodDef->mIsAbstract) &&
  5231. (methodDef->mGenericParams.size() == 0))
  5232. {
  5233. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5234. if (moduleMethodInstance.mFunc)
  5235. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5236. }
  5237. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  5238. enum MethodFlags
  5239. {
  5240. MethodFlags_Protected = 3,
  5241. MethodFlags_Public = 6,
  5242. MethodFlags_Static = 0x10,
  5243. MethodFlags_Virtual = 0x40,
  5244. MethodFlags_StdCall = 0x1000,
  5245. MethodFlags_FastCall = 0x2000,
  5246. MethodFlags_ThisCall = 0x3000,
  5247. MethodFlags_Mutating = 0x4000,
  5248. MethodFlags_Constructor = 0x8000,
  5249. };
  5250. MethodFlags methodFlags = (MethodFlags)0;
  5251. if (methodDef->mProtection == BfProtection_Protected)
  5252. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  5253. if (methodDef->mProtection == BfProtection_Public)
  5254. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  5255. if (methodDef->mIsStatic)
  5256. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  5257. if (methodDef->mIsVirtual)
  5258. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  5259. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  5260. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5261. if (methodDef->mIsMutating)
  5262. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  5263. if (methodDef->mMethodType == BfMethodType_Ctor)
  5264. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Constructor);
  5265. auto callingConvention = GetIRCallingConvention(defaultMethod);
  5266. if (callingConvention == BfIRCallingConv_ThisCall)
  5267. methodFlags = (MethodFlags)(methodFlags | MethodFlags_ThisCall);
  5268. else if (callingConvention == BfIRCallingConv_StdCall)
  5269. methodFlags = (MethodFlags)(methodFlags | MethodFlags_StdCall);
  5270. else if (callingConvention == BfIRCallingConv_FastCall)
  5271. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5272. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  5273. enum ParamFlags
  5274. {
  5275. ParamFlag_None = 0,
  5276. ParamFlag_Splat = 1,
  5277. ParamFlag_Implicit = 2,
  5278. };
  5279. SizedArray<BfIRValue, 8> paramVals;
  5280. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  5281. {
  5282. String paramName = defaultMethod->GetParamName(paramIdx);
  5283. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  5284. ParamFlags paramFlags = ParamFlag_None;
  5285. if (defaultMethod->GetParamIsSplat(paramIdx))
  5286. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  5287. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  5288. SizedArray<BfIRValue, 8> paramDataVals =
  5289. {
  5290. emptyValueType,
  5291. paramNameConst,
  5292. GetConstValue(paramType->mTypeId, typeIdType),
  5293. GetConstValue((int32)paramFlags, shortType),
  5294. GetConstValue(customAttrIdx, intType) // defaultIdx
  5295. };
  5296. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  5297. paramVals.Add(paramData);
  5298. }
  5299. BfIRValue paramsVal;
  5300. if (paramVals.size() > 0)
  5301. {
  5302. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  5303. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  5304. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  5305. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  5306. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  5307. }
  5308. else
  5309. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  5310. int vDataVal = -1;
  5311. if (defaultMethod->mVirtualTableIdx != -1)
  5312. {
  5313. int vDataIdx = -1;
  5314. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  5315. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  5316. {
  5317. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  5318. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  5319. if (extMethodIdx >= 0)
  5320. {
  5321. // Extension?
  5322. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  5323. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  5324. }
  5325. else
  5326. {
  5327. // Map this new virtual index back to the original index
  5328. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  5329. }
  5330. }
  5331. else
  5332. {
  5333. vDataIdx += defaultMethod->mVirtualTableIdx;
  5334. }
  5335. if (vDataVal == -1)
  5336. vDataVal = vDataIdx * mSystem->mPtrSize;
  5337. }
  5338. SizedArray<BfIRValue, 8> methodDataVals =
  5339. {
  5340. emptyValueType,
  5341. methodNameConst, // mName
  5342. funcVal, // mFuncPtr
  5343. paramsVal,
  5344. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  5345. GetConstValue((int)paramVals.size(), shortType),
  5346. GetConstValue(methodFlags, shortType),
  5347. GetConstValue(vDataVal, intType),
  5348. GetConstValue(customAttrIdx, intType),
  5349. };
  5350. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  5351. methodTypes.push_back(methodData);
  5352. }
  5353. BfIRValue methodDataPtr;
  5354. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  5355. if (methodTypes.size() == 0)
  5356. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5357. else
  5358. {
  5359. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5360. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5361. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5362. methodDataConst, "methods." + typeDataName);
  5363. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5364. }
  5365. /////
  5366. int underlyingType = 0;
  5367. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5368. {
  5369. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5370. }
  5371. int outerTypeId = 0;
  5372. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  5373. if (outerType != NULL)
  5374. {
  5375. outerTypeId = outerType->mTypeId;
  5376. }
  5377. BfIRValue customAttrDataPtr;
  5378. if (customAttrs.size() > 0)
  5379. {
  5380. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5381. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5382. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5383. customAttrsConst, "customAttrs." + typeDataName);
  5384. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5385. }
  5386. else
  5387. {
  5388. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5389. }
  5390. SizedArray<BfIRValue, 32> typeDataVals =
  5391. {
  5392. typeData,
  5393. castedClassVData, // mTypeClassVData
  5394. typeNameConst, // mName
  5395. namespaceConst, // mNamespace
  5396. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5397. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5398. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5399. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5400. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5401. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5402. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5403. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5404. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5405. GetConstValue(0, byteType), // mInterfaceCount
  5406. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5407. GetConstValue(0, shortType), // mPropertyDataCount
  5408. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5409. voidPtrNull, // mInterfaceDataPtr
  5410. methodDataPtr, // mMethodDataPtr
  5411. voidPtrNull, // mPropertyDataPtr
  5412. fieldDataPtr, // mFieldDataPtr
  5413. customAttrDataPtr, // mCustomAttrDataPtr
  5414. };
  5415. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5416. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5417. if (!needsTypeData)
  5418. {
  5419. // No need for anything beyond typeInstanceData
  5420. }
  5421. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5422. {
  5423. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5424. SizedArray<BfIRValue, 4> unspecializedData =
  5425. {
  5426. typeInstanceData,
  5427. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5428. };
  5429. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5430. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5431. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5432. }
  5433. else if (typeInstance->IsGenericTypeInstance())
  5434. {
  5435. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5436. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5437. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5438. SizedArray<BfIRValue, 4> resolvedTypes;
  5439. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  5440. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5441. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5442. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5443. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5444. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5445. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5446. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5447. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5448. SizedArray<BfIRValue, 3> specGenericData =
  5449. {
  5450. typeInstanceData,
  5451. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5452. resovledTypesPtr, // mFieldDataPtr
  5453. };
  5454. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5455. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5456. if (typeInstance->IsArray())
  5457. {
  5458. auto arrayType = (BfArrayType*)typeInstance;
  5459. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  5460. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5461. SizedArray<BfIRValue, 4> arrayData =
  5462. {
  5463. typeInstanceData,
  5464. GetConstValue(elementType->mSize, intType), // mElementSize
  5465. GetConstValue(1, byteType), // mRank
  5466. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5467. };
  5468. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5469. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5470. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5471. }
  5472. }
  5473. BfIRValue typeDataVar;
  5474. if (needsTypeData)
  5475. {
  5476. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5477. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5478. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5479. if (mBfIRBuilder->DbgHasInfo())
  5480. {
  5481. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5482. }
  5483. }
  5484. else
  5485. {
  5486. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5487. }
  5488. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5489. mTypeDataRefs[typeInstance] = typeDataVar;
  5490. if (classVDataVar)
  5491. {
  5492. BF_ASSERT(!classVDataName.IsEmpty());
  5493. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5494. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5495. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5496. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5497. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5498. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5499. else
  5500. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5501. if (mBfIRBuilder->DbgHasInfo())
  5502. {
  5503. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5504. BfType* voidPtrType = CreatePointerType(voidType);
  5505. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5506. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5507. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5508. }
  5509. }
  5510. return typeDataVar;
  5511. }
  5512. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5513. {
  5514. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5515. return value;
  5516. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5517. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5518. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5519. }
  5520. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5521. {
  5522. // Note: this is not just for perf, it fixes a field var-type resolution issue
  5523. if (mBfIRBuilder->mIgnoreWrites)
  5524. return;
  5525. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5526. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5527. // When we access classes with static constructors FROM a static constructor,
  5528. // we call that other class's static constructor first. Recursion cannot occur, since
  5529. // we simply ignore subsequent attempts to re-enter the constructor
  5530. if (!typeInstance->mHasStaticInitMethod)
  5531. return;
  5532. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5533. return;
  5534. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5535. return;
  5536. auto checkTypeDef = typeInstance->mTypeDef;
  5537. checkTypeDef->PopulateMemberSets();
  5538. BfMethodDef* nextMethodDef = NULL;
  5539. BfMemberSetEntry* entry;
  5540. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5541. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5542. while (nextMethodDef != NULL)
  5543. {
  5544. auto checkMethod = nextMethodDef;
  5545. nextMethodDef = nextMethodDef->mNextWithSameName;
  5546. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5547. if (methodModule)
  5548. {
  5549. auto methodInstance = methodModule.mMethodInstance;
  5550. if ((methodInstance != NULL) &&
  5551. (methodInstance->mMethodDef->mIsStatic) &&
  5552. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5553. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5554. {
  5555. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5556. break;
  5557. }
  5558. }
  5559. }
  5560. }
  5561. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5562. {
  5563. auto methodOwner = methodInstance->GetOwner();
  5564. auto methodDef = methodInstance->mMethodDef;
  5565. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5566. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5567. if (!hasExternSpecifier)
  5568. return BfIRFunction();
  5569. if (methodInstance->GetCustomAttributes() == NULL)
  5570. return BfIRFunction();
  5571. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5572. {
  5573. String typeName = TypeToString(customAttribute.mType);
  5574. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5575. {
  5576. methodInstance->mIsIntrinsic = true;
  5577. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5578. String error;
  5579. if ((constant != NULL) && (constant->mTypeCode = BfTypeCode_StringId))
  5580. {
  5581. int stringId = constant->mInt32;
  5582. auto entry = mContext->mStringObjectIdMap[stringId];
  5583. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5584. if (intrinId != -1)
  5585. {
  5586. if (intrinId == BfIRIntrinsic_Malloc)
  5587. {
  5588. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5589. }
  5590. else if (intrinId == BfIRIntrinsic_Free)
  5591. {
  5592. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5593. }
  5594. SizedArray<BfIRType, 2> paramTypes;
  5595. for (auto& param : methodInstance->mParams)
  5596. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5597. return mBfIRBuilder->GetIntrinsic(intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  5598. }
  5599. else if (reportFailure)
  5600. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5601. }
  5602. else if (reportFailure)
  5603. error = "Intrinsic name must be a constant string";
  5604. if (reportFailure)
  5605. {
  5606. BfAstNode* ref = methodDeclaration->mAttributes;
  5607. Fail(error, ref);
  5608. }
  5609. }
  5610. }
  5611. return BfIRFunction();
  5612. }
  5613. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5614. {
  5615. if (mBfIRBuilder->mIgnoreWrites)
  5616. return mBfIRBuilder->GetFakeFunction();
  5617. if (!mBuiltInFuncs[(int)funcTypeId])
  5618. {
  5619. SizedArray<BfIRType, 4> paramTypes;
  5620. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5621. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5622. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5623. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5624. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5625. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5626. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5627. BfIRFunctionType funcType;
  5628. BfIRFunction func;
  5629. switch (funcTypeId)
  5630. {
  5631. case BfBuiltInFuncType_PrintF:
  5632. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5633. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5634. break;
  5635. case BfBuiltInFuncType_Malloc:
  5636. {
  5637. if (mCompiler->mOptions.mDebugAlloc)
  5638. {
  5639. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5640. }
  5641. else
  5642. {
  5643. String funcName = mCompiler->mOptions.mMallocLinkName;
  5644. if (funcName.IsEmpty())
  5645. funcName = "malloc";
  5646. func = mBfIRBuilder->GetFunction(funcName);
  5647. if (!func)
  5648. {
  5649. paramTypes.clear();
  5650. paramTypes.push_back(intType);
  5651. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5652. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5653. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5654. }
  5655. }
  5656. }
  5657. break;
  5658. case BfBuiltInFuncType_Free:
  5659. {
  5660. if (mCompiler->mOptions.mDebugAlloc)
  5661. {
  5662. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5663. }
  5664. else
  5665. {
  5666. String funcName = mCompiler->mOptions.mFreeLinkName;
  5667. if (funcName.IsEmpty())
  5668. funcName = "free";
  5669. func = mBfIRBuilder->GetFunction(funcName);
  5670. if (!func)
  5671. {
  5672. paramTypes.clear();
  5673. paramTypes.push_back(nullPtrType);
  5674. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5675. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5676. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5677. }
  5678. }
  5679. }
  5680. break;
  5681. case BfBuiltInFuncType_LoadSharedLibraries:
  5682. paramTypes.clear();
  5683. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5684. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5685. break;
  5686. default: break;
  5687. }
  5688. mBuiltInFuncs[(int)funcTypeId] = func;
  5689. return func;
  5690. }
  5691. return mBuiltInFuncs[(int)funcTypeId];
  5692. }
  5693. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5694. {
  5695. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5696. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5697. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5698. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5699. BfAutoComplete* bfAutocomplete = NULL;
  5700. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5701. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5702. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5703. {
  5704. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5705. {
  5706. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5707. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5708. {
  5709. String filter = nameNode->ToString();
  5710. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5711. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5712. if (nameIdx != 0)
  5713. {
  5714. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5715. }
  5716. }
  5717. }
  5718. }
  5719. for (auto constraint : constraintDef->mConstraints)
  5720. {
  5721. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5722. {
  5723. BfGenericOperatorConstraintInstance opConstraintInstance;
  5724. if (opConstraint->mLeftType != NULL)
  5725. {
  5726. if (bfAutocomplete != NULL)
  5727. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5728. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType);
  5729. if (opConstraintInstance.mLeftType == NULL)
  5730. continue;
  5731. }
  5732. if (opConstraint->mRightType == NULL)
  5733. {
  5734. // We had a failure in parsing
  5735. continue;
  5736. }
  5737. if (opConstraint->mRightType != NULL)
  5738. {
  5739. if (bfAutocomplete != NULL)
  5740. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  5741. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType);
  5742. if (opConstraintInstance.mRightType == NULL)
  5743. continue;
  5744. }
  5745. if (opConstraint->mOpToken == NULL)
  5746. {
  5747. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  5748. continue;
  5749. }
  5750. if (opConstraint->mLeftType != NULL)
  5751. {
  5752. if (opConstraint->mRightType == NULL)
  5753. {
  5754. // Parse should have failed
  5755. continue;
  5756. }
  5757. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  5758. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  5759. {
  5760. Fail("Invalid binary operator", opConstraint->mOpToken);
  5761. continue;
  5762. }
  5763. }
  5764. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  5765. {
  5766. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  5767. }
  5768. else
  5769. {
  5770. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  5771. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  5772. {
  5773. Fail("Invalid unary operator", opConstraint->mOpToken);
  5774. continue;
  5775. }
  5776. }
  5777. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5778. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  5779. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  5780. continue;
  5781. }
  5782. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  5783. if (bfAutocomplete != NULL)
  5784. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5785. //TODO: Constraints may refer to other generic params (of either type or method)
  5786. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5787. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5788. if (constraintType != NULL)
  5789. {
  5790. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5791. {
  5792. bool isValidTypeCode = false;
  5793. BfTypeCode typeCode = BfTypeCode_None;
  5794. if (constraintType->IsTypedPrimitive())
  5795. {
  5796. auto underlyingType = constraintType->GetUnderlyingType();
  5797. if (underlyingType->IsPrimitiveType())
  5798. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5799. }
  5800. if (constraintType->IsPrimitiveType())
  5801. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5802. switch (typeCode)
  5803. {
  5804. case BfTypeCode_Int8:
  5805. case BfTypeCode_UInt8:
  5806. case BfTypeCode_Int16:
  5807. case BfTypeCode_UInt16:
  5808. case BfTypeCode_Int32:
  5809. case BfTypeCode_UInt32:
  5810. case BfTypeCode_Int64:
  5811. case BfTypeCode_UInt64:
  5812. case BfTypeCode_IntPtr:
  5813. case BfTypeCode_UIntPtr:
  5814. case BfTypeCode_IntUnknown:
  5815. case BfTypeCode_UIntUnknown:
  5816. case BfTypeCode_Float:
  5817. case BfTypeCode_Double:
  5818. case BfTypeCode_Char8:
  5819. case BfTypeCode_Char16:
  5820. case BfTypeCode_Char32:
  5821. isValidTypeCode = true;
  5822. break;
  5823. default: break;
  5824. }
  5825. if (isValidTypeCode)
  5826. {
  5827. genericParamInstance->mTypeConstraint = constraintType;
  5828. }
  5829. else
  5830. {
  5831. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5832. }
  5833. }
  5834. else
  5835. {
  5836. bool checkEquality = false;
  5837. if (constraintType->IsPrimitiveType())
  5838. {
  5839. if (isUnspecialized)
  5840. {
  5841. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5842. continue;
  5843. }
  5844. checkEquality = true;
  5845. }
  5846. if (constraintType->IsArray())
  5847. {
  5848. if (isUnspecialized)
  5849. {
  5850. 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);
  5851. continue;
  5852. }
  5853. checkEquality = true;
  5854. }
  5855. if (constraintType->IsGenericParam())
  5856. {
  5857. continue;
  5858. }
  5859. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5860. {
  5861. if (isUnspecialized)
  5862. {
  5863. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5864. continue;
  5865. }
  5866. checkEquality = true;
  5867. }
  5868. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5869. {
  5870. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  5871. checkEquality = true;
  5872. }
  5873. if (checkEquality)
  5874. {
  5875. genericParamInstance->mTypeConstraint = constraintType;
  5876. }
  5877. else if (constraintType->IsInterface())
  5878. {
  5879. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5880. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  5881. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5882. }
  5883. else
  5884. {
  5885. auto constraintTypeInst = constraintType->ToTypeInstance();
  5886. if (genericParamInstance->mTypeConstraint != NULL)
  5887. {
  5888. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5889. {
  5890. // Allow more specific type
  5891. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5892. }
  5893. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5894. {
  5895. // Silently ignore less-specific type
  5896. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5897. {
  5898. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5899. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5900. }
  5901. }
  5902. else
  5903. {
  5904. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5905. return;
  5906. }
  5907. }
  5908. else
  5909. genericParamInstance->mTypeConstraint = constraintType;
  5910. }
  5911. }
  5912. }
  5913. }
  5914. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5915. (genericParamInstance->mTypeConstraint == NULL))
  5916. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5917. }
  5918. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5919. {
  5920. if (genericParamSource.mMethodInstance != NULL)
  5921. {
  5922. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5923. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5924. return MethodToString(methodInst);
  5925. }
  5926. else
  5927. {
  5928. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5929. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5930. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5931. return TypeToString(typeInst);
  5932. }
  5933. }
  5934. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5935. {
  5936. Array<String> methodParamNameOverrides;
  5937. auto _TypeToString = [&](BfType* type)
  5938. {
  5939. if (genericParamSource.mMethodInstance != NULL)
  5940. {
  5941. if (methodParamNameOverrides.IsEmpty())
  5942. {
  5943. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  5944. methodParamNameOverrides.Add(genericParam->mName);
  5945. }
  5946. return TypeToString(type, &methodParamNameOverrides);
  5947. }
  5948. return TypeToString(type);
  5949. };
  5950. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5951. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5952. BfType* origCheckArgType = checkArgType;
  5953. if (origCheckArgType->IsRef())
  5954. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5955. bool argMayBeReferenceType = false;
  5956. int checkGenericParamFlags = 0;
  5957. if (checkArgType->IsGenericParam())
  5958. {
  5959. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5960. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5961. if (checkGenericParamInst->mTypeConstraint != NULL)
  5962. checkArgType = checkGenericParamInst->mTypeConstraint;
  5963. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5964. {
  5965. argMayBeReferenceType = false;
  5966. }
  5967. else
  5968. {
  5969. argMayBeReferenceType = true;
  5970. }
  5971. }
  5972. if (checkArgType->IsObjectOrInterface())
  5973. argMayBeReferenceType = true;
  5974. BfTypeInstance* typeConstraintInst = NULL;
  5975. if (genericParamInst->mTypeConstraint != NULL)
  5976. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5977. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5978. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5979. {
  5980. if (!ignoreErrors)
  5981. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5982. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5983. return false;
  5984. }
  5985. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5986. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5987. {
  5988. if (!ignoreErrors)
  5989. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5990. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5991. return false;
  5992. }
  5993. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5994. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5995. {
  5996. if (!ignoreErrors)
  5997. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5998. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5999. return false;
  6000. }
  6001. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6002. {
  6003. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  6004. {
  6005. if (!ignoreErrors)
  6006. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  6007. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6008. return false;
  6009. }
  6010. }
  6011. else
  6012. {
  6013. if (checkArgType->IsConstExprValue())
  6014. {
  6015. if (!ignoreErrors)
  6016. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  6017. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6018. return false;
  6019. }
  6020. }
  6021. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6022. {
  6023. bool canDelete = false;
  6024. if (checkArgType->IsPointer())
  6025. canDelete = true;
  6026. else if (checkArgType->IsObjectOrInterface())
  6027. canDelete = true;
  6028. else if ((checkGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6029. canDelete = true;
  6030. if (!canDelete)
  6031. {
  6032. if (!ignoreErrors)
  6033. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  6034. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6035. return false;
  6036. }
  6037. }
  6038. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  6039. {
  6040. bool canAlloc = false;
  6041. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  6042. {
  6043. if (checkTypeInst->IsObjectOrStruct())
  6044. {
  6045. checkTypeInst->mTypeDef->PopulateMemberSets();
  6046. BfMemberSetEntry* entry = NULL;
  6047. BfMethodDef* checkMethodDef = NULL;
  6048. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  6049. if (entry != NULL)
  6050. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  6051. bool hadProtected = false;
  6052. while (checkMethodDef != NULL)
  6053. {
  6054. if (checkMethodDef->mProtection == BfProtection_Public)
  6055. {
  6056. canAlloc = true;
  6057. break;
  6058. }
  6059. if (checkMethodDef->mProtection == BfProtection_Protected)
  6060. hadProtected = true;
  6061. checkMethodDef = checkMethodDef->mNextWithSameName;
  6062. }
  6063. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  6064. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  6065. }
  6066. }
  6067. else
  6068. {
  6069. // Any primitive types and stuff can be allocated
  6070. canAlloc = true;
  6071. }
  6072. if (!canAlloc)
  6073. {
  6074. if (!ignoreErrors)
  6075. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  6076. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6077. return false;
  6078. }
  6079. }
  6080. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  6081. return true;
  6082. if (checkArgType->IsPointer())
  6083. {
  6084. auto ptrType = (BfPointerType*)checkArgType;
  6085. checkArgType = ptrType->mElementType;
  6086. }
  6087. if (genericParamInst->mTypeConstraint != NULL)
  6088. {
  6089. bool constraintMatched = false;
  6090. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6091. {
  6092. if (checkArgType->IsConstExprValue())
  6093. {
  6094. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  6095. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  6096. {
  6097. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  6098. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  6099. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  6100. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  6101. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  6102. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  6103. {
  6104. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  6105. {
  6106. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6107. {
  6108. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  6109. {
  6110. if (!ignoreErrors)
  6111. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6112. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6113. return false;
  6114. }
  6115. }
  6116. else
  6117. {
  6118. if (!ignoreErrors)
  6119. *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(),
  6120. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6121. return false;
  6122. }
  6123. }
  6124. else
  6125. {
  6126. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6127. {
  6128. char valStr[64];
  6129. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  6130. if (!ignoreErrors)
  6131. *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(),
  6132. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6133. return false;
  6134. }
  6135. }
  6136. }
  6137. }
  6138. }
  6139. }
  6140. else
  6141. {
  6142. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  6143. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  6144. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6145. if (convCheckConstraint == NULL)
  6146. return false;
  6147. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  6148. {
  6149. auto methodRefType = (BfMethodRefType*)checkArgType;
  6150. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  6151. BfExprEvaluator exprEvaluator(this);
  6152. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  6153. constraintMatched = true;
  6154. }
  6155. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  6156. {
  6157. constraintMatched = true;
  6158. }
  6159. else if (origCheckArgType->IsWrappableType())
  6160. {
  6161. if (origCheckArgType->IsSizedArray())
  6162. {
  6163. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  6164. if (convCheckConstraint->IsGenericTypeInstance())
  6165. {
  6166. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  6167. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  6168. {
  6169. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  6170. {
  6171. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  6172. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  6173. constraintMatched = true;
  6174. }
  6175. }
  6176. }
  6177. }
  6178. if (!constraintMatched)
  6179. {
  6180. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6181. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  6182. constraintMatched = true;
  6183. }
  6184. }
  6185. if (!constraintMatched)
  6186. {
  6187. if (!ignoreErrors)
  6188. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  6189. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  6190. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  6191. return false;
  6192. }
  6193. }
  6194. }
  6195. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  6196. {
  6197. PopulateType(origCheckArgType);
  6198. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  6199. if (checkTypeInst->mTypeDef->mIsConcrete)
  6200. {
  6201. if (!ignoreErrors)
  6202. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  6203. TypeToString(origCheckArgType).c_str()), checkArgTypeRef);
  6204. return false;
  6205. }
  6206. }
  6207. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  6208. {
  6209. BfType* convCheckConstraint = checkConstraint;
  6210. if (convCheckConstraint->IsUnspecializedType())
  6211. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6212. if (convCheckConstraint == NULL)
  6213. return false;
  6214. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  6215. bool implementsInterface = false;
  6216. if (origCheckArgType != checkArgType)
  6217. {
  6218. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  6219. }
  6220. if (!implementsInterface)
  6221. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  6222. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  6223. {
  6224. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6225. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6226. implementsInterface = true;
  6227. }
  6228. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  6229. {
  6230. auto underlyingType = origCheckArgType->GetUnderlyingType();
  6231. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  6232. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6233. implementsInterface = true;
  6234. }
  6235. if (!implementsInterface)
  6236. {
  6237. if (!ignoreErrors)
  6238. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  6239. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), _TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  6240. return false;
  6241. }
  6242. }
  6243. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  6244. {
  6245. auto leftType = checkOpConstraint.mLeftType;
  6246. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  6247. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  6248. if (leftType != NULL)
  6249. leftType = FixIntUnknown(leftType);
  6250. auto rightType = checkOpConstraint.mRightType;
  6251. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  6252. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  6253. if (rightType != NULL)
  6254. rightType = FixIntUnknown(rightType);
  6255. BfConstraintState constraintSet;
  6256. constraintSet.mPrevState = mContext->mCurConstraintState;
  6257. constraintSet.mGenericParamInstance = genericParamInst;
  6258. constraintSet.mLeftType = leftType;
  6259. constraintSet.mRightType = rightType;
  6260. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  6261. if (!CheckConstraintState(NULL))
  6262. return false;
  6263. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  6264. {
  6265. BfExprEvaluator exprEvaluator(this);
  6266. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  6267. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6268. //
  6269. {
  6270. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6271. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6272. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  6273. }
  6274. if ((!exprEvaluator.mResult) ||
  6275. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  6276. {
  6277. if (!ignoreErrors)
  6278. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  6279. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6280. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6281. ), checkArgTypeRef);
  6282. return false;
  6283. }
  6284. }
  6285. else
  6286. {
  6287. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6288. StringT<128> failedOpName;
  6289. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  6290. {
  6291. if (!CanCast(rightValue, origCheckArgType, BfCastFlags_SilentFail))
  6292. failedOpName = "implicit conversion from '";
  6293. }
  6294. else
  6295. {
  6296. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6297. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6298. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  6299. {
  6300. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  6301. failedOpName = "explicit conversion from '";
  6302. }
  6303. else
  6304. {
  6305. BfExprEvaluator exprEvaluator(this);
  6306. exprEvaluator.mResult = rightValue;
  6307. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL);
  6308. if ((!exprEvaluator.mResult) ||
  6309. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  6310. {
  6311. failedOpName += "unary operation '";
  6312. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  6313. }
  6314. }
  6315. }
  6316. if (!failedOpName.IsEmpty())
  6317. {
  6318. if (!ignoreErrors)
  6319. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  6320. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6321. failedOpName.c_str(), TypeToString(rightType).c_str()
  6322. ), checkArgTypeRef);
  6323. return false;
  6324. }
  6325. }
  6326. }
  6327. return true;
  6328. }
  6329. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  6330. {
  6331. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  6332. {
  6333. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  6334. return genericParamType;
  6335. }
  6336. auto genericParamType = new BfGenericParamType();
  6337. genericParamType->mContext = mContext;
  6338. genericParamType->mGenericParamKind = paramKind;
  6339. genericParamType->mGenericParamIdx = paramIdx;
  6340. PopulateType(genericParamType);
  6341. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  6342. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  6343. BfResolvedTypeSet::LookupContext lookupCtx;
  6344. lookupCtx.mModule = this;
  6345. BfResolvedTypeSet::Entry* typeEntry = NULL;
  6346. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  6347. BF_ASSERT(inserted);
  6348. typeEntry->mValue = genericParamType;
  6349. return genericParamType;
  6350. }
  6351. static int sValueFromExprIdx = 0;
  6352. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  6353. {
  6354. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  6355. if ((result) && (!ignoreNullable))
  6356. {
  6357. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  6358. //TODO: Make this work, needed for 'void' and such
  6359. BfType* nullableType = NULL;
  6360. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  6361. {
  6362. BfTypeVector typeVec;
  6363. typeVec.push_back(result.mType);
  6364. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  6365. BF_ASSERT(nullableType != NULL);
  6366. }
  6367. // Go back to start and do any setup we need
  6368. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6369. BfTypedValue nullableTypedValue;
  6370. if (nullableType != NULL)
  6371. {
  6372. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  6373. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  6374. GetConstValue(nullableType->mSize), nullableType->mAlign);
  6375. }
  6376. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6377. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  6378. mBfIRBuilder->SetInsertPoint(notNullBB);
  6379. result = LoadValue(result);
  6380. if (nullableTypedValue)
  6381. {
  6382. auto elementType = nullableType->GetUnderlyingType();
  6383. if (elementType->IsVar())
  6384. {
  6385. // Do nothing
  6386. }
  6387. else if (elementType->IsValuelessType())
  6388. {
  6389. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  6390. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6391. }
  6392. else
  6393. {
  6394. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  6395. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  6396. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  6397. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6398. }
  6399. result = nullableTypedValue;
  6400. }
  6401. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6402. AddBasicBlock(pendingNullCond->mDoneBB);
  6403. if (nullableType == NULL)
  6404. {
  6405. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  6406. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  6407. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  6408. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  6409. {
  6410. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  6411. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  6412. }
  6413. result.mValue = phi;
  6414. }
  6415. }
  6416. else
  6417. {
  6418. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6419. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6420. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6421. AddBasicBlock(pendingNullCond->mDoneBB);
  6422. }
  6423. delete mCurMethodState->mPendingNullConditional;
  6424. mCurMethodState->mPendingNullConditional = NULL;
  6425. return result;
  6426. }
  6427. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  6428. {
  6429. BfScopeData newScope;
  6430. newScope.mOuterIsConditional = true;
  6431. newScope.mAllowTargeting = false;
  6432. mCurMethodState->AddScope(&newScope);
  6433. NewScopeState();
  6434. exprEvaluator.mBfEvalExprFlags = flags;
  6435. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6436. RestoreScopeState();
  6437. }
  6438. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6439. {
  6440. //
  6441. {
  6442. BP_ZONE("CreateValueFromExpression:CheckStack");
  6443. StackHelper stackHelper;
  6444. if (!stackHelper.CanStackExpand(64 * 1024))
  6445. {
  6446. BfTypedValue result;
  6447. if (!stackHelper.Execute([&]()
  6448. {
  6449. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6450. }))
  6451. {
  6452. Fail("Expression too complex to compile", expr);
  6453. }
  6454. return result;
  6455. }
  6456. }
  6457. BP_ZONE("BfModule::CreateValueFromExpression");
  6458. if (outOrigType != NULL)
  6459. *outOrigType = NULL;
  6460. exprEvaluator.mExpectingType = wantTypeRef;
  6461. exprEvaluator.mBfEvalExprFlags = flags;
  6462. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  6463. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  6464. {
  6465. EvaluateWithNewScope(exprEvaluator, expr, flags);
  6466. }
  6467. else
  6468. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6469. if (!exprEvaluator.mResult)
  6470. {
  6471. if (!mCompiler->mPassInstance->HasFailed())
  6472. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  6473. return BfTypedValue();
  6474. }
  6475. auto typedVal = exprEvaluator.mResult;
  6476. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6477. {
  6478. BF_ASSERT(typedVal.mType->IsGenericParam());
  6479. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  6480. bool handled = false;
  6481. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6482. {
  6483. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  6484. if (genericTypeConstraint != NULL)
  6485. {
  6486. auto primType = genericTypeConstraint->ToPrimitiveType();
  6487. if (primType != NULL)
  6488. {
  6489. BfTypedValue result;
  6490. result.mKind = BfTypedValueKind_Value;
  6491. result.mType = genericTypeConstraint;
  6492. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  6493. typedVal = result;
  6494. handled = true;
  6495. }
  6496. }
  6497. }
  6498. if (!handled)
  6499. {
  6500. //Fail("Only const generic parameters can be used as values", expr);
  6501. AssertErrorState();
  6502. return BfTypedValue();
  6503. }
  6504. }
  6505. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6506. FixIntUnknown(typedVal);
  6507. exprEvaluator.CheckResultForReading(typedVal);
  6508. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6509. {
  6510. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6511. {
  6512. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6513. bool allowRef = false;
  6514. BfExpression* checkExpr = expr;
  6515. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6516. checkExpr = parenExpr->mExpression;
  6517. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6518. {
  6519. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6520. allowRef = true;
  6521. }
  6522. if (!allowRef)
  6523. typedVal = RemoveRef(typedVal);
  6524. }
  6525. }
  6526. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  6527. {
  6528. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  6529. {
  6530. BF_ASSERT(!typedVal.mValue.IsFake());
  6531. }
  6532. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6533. }
  6534. if (wantTypeRef != NULL)
  6535. {
  6536. if (outOrigType != NULL)
  6537. *outOrigType = typedVal.mType;
  6538. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6539. {
  6540. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6541. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6542. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6543. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6544. if (!typedVal)
  6545. return typedVal;
  6546. }
  6547. //WTF- why did we have this?
  6548. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6549. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6550. if (exprEvaluator.mIsVolatileReference)
  6551. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6552. }
  6553. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6554. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6555. return typedVal;
  6556. }
  6557. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6558. {
  6559. BfExprEvaluator exprEvaluator(this);
  6560. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6561. }
  6562. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6563. {
  6564. BfExprEvaluator exprEvaluator(this);
  6565. exprEvaluator.Evaluate(expr);
  6566. if (!exprEvaluator.mResult)
  6567. {
  6568. Fail("Invalid expression type", expr);
  6569. return BfTypedValue();
  6570. }
  6571. if (!exprEvaluator.mResult.IsAddr())
  6572. {
  6573. Fail("Cannot assign to value", expr);
  6574. return BfTypedValue();
  6575. }
  6576. return exprEvaluator.mResult;
  6577. }
  6578. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6579. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6580. {
  6581. auto typeInstance = typedValue.mType->ToTypeInstance();
  6582. if (zeroMemory)
  6583. {
  6584. int zeroAlign = typedValue.mType->mAlign;
  6585. if (typeInstance != NULL)
  6586. zeroAlign = typeInstance->mInstAlign;
  6587. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6588. }
  6589. if (!typedValue.mType->IsObject())
  6590. {
  6591. return;
  6592. }
  6593. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6594. return; // Handled in heap alloc funcs
  6595. auto typeDef = typeInstance->mTypeDef;
  6596. mBfIRBuilder->PopulateType(typedValue.mType);
  6597. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6598. bool isAutocomplete = mCompiler->IsAutocomplete();
  6599. BfIRValue vDataRef;
  6600. if (!isAutocomplete)
  6601. {
  6602. vDataRef = GetClassVDataPtr(typeInstance);
  6603. }
  6604. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6605. auto ptrType = CreatePointerType(i8Type);
  6606. auto ptrPtrType = CreatePointerType(ptrType);
  6607. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6608. PopulateType(ptrType, BfPopulateType_Declaration);
  6609. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6610. if (!isAutocomplete)
  6611. {
  6612. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6613. {
  6614. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6615. SizedArray<BfIRValue, 4> llvmArgs;
  6616. llvmArgs.push_back(objectPtr);
  6617. llvmArgs.push_back(vDataRef);
  6618. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6619. if (objectStackInitMethod)
  6620. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6621. }
  6622. else
  6623. {
  6624. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6625. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6626. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6627. }
  6628. }
  6629. }
  6630. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6631. {
  6632. BfIRValue result;
  6633. BfType* ptrType;
  6634. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6635. ptrType = type;
  6636. else
  6637. ptrType = CreatePointerType(type);
  6638. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6639. {
  6640. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6641. SizedArray<BfExpression*, 2> argExprs;
  6642. BfTypedValueExpression typedValueExpr;
  6643. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6644. typedValueExpr.mRefNode = refNode;
  6645. argExprs.push_back(&typedValueExpr);
  6646. BfTypedValueExpression appendSizeValueExpr;
  6647. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6648. appendSizeValueExpr.mRefNode = refNode;
  6649. argExprs.push_back(&appendSizeValueExpr);
  6650. BfExprEvaluator exprEvaluator(this);
  6651. BfTypedValue allocResult;
  6652. if (allocTarget.mScopedInvocationTarget != NULL)
  6653. {
  6654. SizedArray<BfTypeReference*, 2> genericArgs;
  6655. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6656. allocResult = LoadValue(exprEvaluator.mResult);
  6657. }
  6658. else if (allocTarget.mCustomAllocator)
  6659. {
  6660. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6661. if (customTypeInst != NULL)
  6662. {
  6663. BfTypedValueExpression typeValueExpr;
  6664. String allocMethodName = "Alloc";
  6665. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6666. {
  6667. allocMethodName = "AllocTyped";
  6668. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6669. auto typeRefVal = CreateTypeDataRef(type);
  6670. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6671. typeValueExpr.mRefNode = refNode;
  6672. argExprs.Insert(0, &typeValueExpr);
  6673. }
  6674. if (HasMixin(customTypeInst, allocMethodName, 2))
  6675. {
  6676. BfSizedArray<BfExpression*> argExprArr;
  6677. argExprArr.mSize = (int)argExprs.size();
  6678. argExprArr.mVals = &argExprs[0];
  6679. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6680. allocResult = exprEvaluator.GetResult();
  6681. }
  6682. else
  6683. {
  6684. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6685. BfResolvedArgs argValues(&sizedArgExprs);
  6686. exprEvaluator.ResolveArgValues(argValues);
  6687. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6688. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6689. }
  6690. }
  6691. }
  6692. if (allocResult)
  6693. {
  6694. if (allocResult.mType->IsVoidPtr())
  6695. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6696. else
  6697. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6698. return result;
  6699. }
  6700. }
  6701. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6702. return result;
  6703. if (mCompiler->mOptions.mDebugAlloc)
  6704. {
  6705. BfIRValue allocData = GetDbgRawAllocData(type);
  6706. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6707. SizedArray<BfIRValue, 2> llvmArgs;
  6708. llvmArgs.push_back(sizeValue);
  6709. llvmArgs.push_back(allocData);
  6710. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6711. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6712. }
  6713. BfModuleMethodInstance moduleMethodInstance;
  6714. moduleMethodInstance = GetInternalMethod("Malloc");
  6715. SizedArray<BfIRValue, 1> llvmArgs;
  6716. llvmArgs.push_back(sizeValue);
  6717. auto func = moduleMethodInstance.mFunc;
  6718. if ((!func) || (func.IsFake()))
  6719. {
  6720. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6721. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6722. }
  6723. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6724. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6725. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6726. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6727. return result;
  6728. }
  6729. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6730. {
  6731. if (type->IsStruct())
  6732. {
  6733. auto typeInstance = type->ToTypeInstance();
  6734. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6735. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6736. }
  6737. else if (type->IsObjectOrInterface())
  6738. {
  6739. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6740. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6741. BF_ASSERT(moduleMethodInst.mFunc);
  6742. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6743. }
  6744. else
  6745. {
  6746. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6747. BfExprEvaluator exprEvaluator(this);
  6748. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6749. BfResolvedArg resolvedArg;
  6750. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6751. resolvedArgs.Add(resolvedArg);
  6752. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6753. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6754. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6755. BF_ASSERT(moduleMethodInst.mFunc);
  6756. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6757. }
  6758. return BfIRValue();
  6759. }
  6760. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6761. {
  6762. BfIRValue allocDataValue;
  6763. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6764. return allocDataValue;
  6765. BfIRValue markFuncPtr;
  6766. if (type->WantsGCMarking())
  6767. markFuncPtr = GetMarkFuncPtr(type);
  6768. else
  6769. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6770. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6771. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6772. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6773. if (typeInstance == NULL)
  6774. {
  6775. typeInstance = GetWrappedStructType(type);
  6776. if (typeInstance != NULL)
  6777. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6778. }
  6779. if (typeInstance != NULL)
  6780. PopulateType(typeInstance);
  6781. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6782. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6783. {
  6784. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6785. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6786. }
  6787. SizedArray<BfIRValue, 2> dataValues;
  6788. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6789. dataValues.Add(typeDataRef);
  6790. dataValues.Add(markFuncPtr);
  6791. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6792. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6793. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6794. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6795. return allocDataValue;
  6796. }
  6797. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6798. {
  6799. BP_ZONE("AllocFromType");
  6800. BfScopeData* scopeData = allocTarget.mScopeData;
  6801. BF_ASSERT(!type->IsVar());
  6802. auto typeInstance = type->ToTypeInstance();
  6803. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6804. typeInstance = mContext->mBfObjectType;
  6805. bool isHeapAlloc = scopeData == NULL;
  6806. bool isScopeAlloc = scopeData != NULL;
  6807. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6808. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6809. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6810. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6811. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6812. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6813. {
  6814. BfPointerType* ptrType = CreatePointerType(type);
  6815. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6816. return val;
  6817. }
  6818. if (typeInstance != NULL)
  6819. mBfIRBuilder->PopulateType(typeInstance);
  6820. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6821. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6822. {
  6823. if (arraySize)
  6824. {
  6825. if (isRawArrayAlloc)
  6826. {
  6827. BfPointerType* ptrType = CreatePointerType(type);
  6828. return GetDefaultValue(ptrType);
  6829. }
  6830. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6831. return GetDefaultValue(arrayType);
  6832. }
  6833. if (type->IsValueType())
  6834. {
  6835. BfPointerType* ptrType = CreatePointerType(type);
  6836. return GetDefaultValue(ptrType);
  6837. }
  6838. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6839. }
  6840. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6841. BfIRValue sizeValue;
  6842. BfIRType allocType = mBfIRBuilder->MapType(type);
  6843. int allocSize = type->mSize;
  6844. int allocAlign = type->mAlign;
  6845. if (typeInstance != NULL)
  6846. {
  6847. if (!mBfIRBuilder->mIgnoreWrites)
  6848. typeInstance->mHasBeenInstantiated = true;
  6849. allocSize = typeInstance->mInstSize;
  6850. allocAlign = typeInstance->mInstAlign;
  6851. //if (typeInstance->IsEnum())
  6852. //allocType = typeInstance->mIRType;
  6853. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6854. }
  6855. if (alignOverride != -1)
  6856. allocAlign = alignOverride;
  6857. // The "dynSize" cases:
  6858. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6859. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6860. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6861. // though we'd expect their stack space to be released
  6862. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6863. {
  6864. MarkDynStack(scopeData);
  6865. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6866. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6867. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6868. BfType* voidPtrType = CreatePointerType(voidType);
  6869. if (!mCurMethodState->mDynStackRevIdx)
  6870. {
  6871. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6872. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6873. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6874. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6875. mBfIRBuilder->ClearDebugLocation(storeInst);
  6876. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6877. }
  6878. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6879. auto bytePtrType = CreatePointerType(byteType);
  6880. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6881. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6882. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6883. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6884. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6885. mBfIRBuilder->ClearDebugLocation(storeInst);
  6886. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6887. mBfIRBuilder->ClearDebugLocation(storeInst);
  6888. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6889. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6890. if (IsTargetingBeefBackend())
  6891. {
  6892. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6893. // to ensure there isn't any register collision during looping is just to not allow it to
  6894. // bind to a register at all
  6895. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6896. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6897. }
  6898. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6899. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6900. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6901. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6902. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6903. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6904. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6905. mBfIRBuilder->AddBlock(verCheckBB);
  6906. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6907. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6908. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6909. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6910. mBfIRBuilder->AddBlock(resizeBB);
  6911. mBfIRBuilder->SetInsertPoint(resizeBB);
  6912. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6913. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6914. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6915. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6916. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6917. mBfIRBuilder->CreateBr(endBB);
  6918. mBfIRBuilder->AddBlock(endBB);
  6919. mBfIRBuilder->SetInsertPoint(endBB);
  6920. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6921. };
  6922. if (isScopeAlloc)
  6923. {
  6924. if (arraySize)
  6925. {
  6926. bool isConstantArraySize = arraySize.IsConst();
  6927. if (isRawArrayAlloc)
  6928. {
  6929. BfPointerType* ptrType = CreatePointerType(type);
  6930. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6931. {
  6932. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6933. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6934. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6935. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6936. }
  6937. else
  6938. {
  6939. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6940. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6941. if (!isDynAlloc)
  6942. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6943. else
  6944. {
  6945. MarkDynStack(scopeData);
  6946. SaveStackState(scopeData);
  6947. }
  6948. int typeSize = type->GetStride();
  6949. BfIRValue allocaInst;
  6950. BfIRValue result;
  6951. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6952. {
  6953. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6954. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6955. result = allocaInst;
  6956. }
  6957. else
  6958. {
  6959. if (typeInstance->IsStruct())
  6960. typeSize = typeInstance->GetInstStride();
  6961. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6962. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6963. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6964. auto ptrType = CreatePointerType(typeInstance);
  6965. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6966. if (!isDynAlloc)
  6967. mBfIRBuilder->ClearDebugLocation(result);
  6968. }
  6969. if (!isDynAlloc)
  6970. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6971. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6972. if (!isDynAlloc)
  6973. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6974. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6975. if (arraySize.IsConst())
  6976. {
  6977. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6978. if (constant->mInt64 == 0)
  6979. noDtorCall = true;
  6980. }
  6981. if (!noDtorCall)
  6982. {
  6983. bool isConstSize = arraySize.IsConst();
  6984. BfIRBlock clearBlock;
  6985. BfIRBlock contBlock;
  6986. if (!isConstSize)
  6987. {
  6988. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6989. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6990. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6991. mBfIRBuilder->AddBlock(clearBlock);
  6992. mBfIRBuilder->SetInsertPoint(clearBlock);
  6993. }
  6994. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  6995. if (!isConstSize)
  6996. {
  6997. mBfIRBuilder->CreateBr(contBlock);
  6998. mBfIRBuilder->AddBlock(contBlock);
  6999. mBfIRBuilder->SetInsertPoint(contBlock);
  7000. }
  7001. }
  7002. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7003. return result;
  7004. }
  7005. }
  7006. else
  7007. {
  7008. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7009. {
  7010. // Generate and check new size
  7011. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7012. auto firstElementField = &arrayType->mFieldInstances.back();
  7013. int arrayClassSize = firstElementField->mDataOffset;
  7014. sizeValue = GetConstValue(arrayClassSize);
  7015. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7016. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7017. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  7018. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  7019. if (!noDtorCall)
  7020. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7021. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7022. return typedVal.mValue;
  7023. }
  7024. else
  7025. {
  7026. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7027. auto firstElementField = &arrayType->mFieldInstances.back();
  7028. if (!type->IsValuelessType())
  7029. {
  7030. int arrayClassSize = firstElementField->mDataOffset;
  7031. sizeValue = GetConstValue(arrayClassSize);
  7032. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7033. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7034. }
  7035. else
  7036. sizeValue = GetConstValue(arrayType->mInstSize);
  7037. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7038. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7039. if (!isDynAlloc)
  7040. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7041. else
  7042. {
  7043. MarkDynStack(scopeData);
  7044. SaveStackState(scopeData);
  7045. }
  7046. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  7047. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7048. if (!isDynAlloc)
  7049. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7050. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7051. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  7052. mBfIRBuilder->ClearDebugLocation_Last();
  7053. if (!isDynAlloc)
  7054. mBfIRBuilder->SetInsertPoint(prevBlock);
  7055. if (!noDtorCall)
  7056. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7057. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7058. return typedVal.mValue;
  7059. }
  7060. }
  7061. }
  7062. else if (appendSizeValue)
  7063. {
  7064. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  7065. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  7066. // use the "dynSize" version conservatively
  7067. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7068. {
  7069. // Generate and check new size
  7070. sizeValue = GetConstValue(typeInstance->mInstSize);
  7071. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7072. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  7073. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  7074. if (!noDtorCall)
  7075. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  7076. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7077. return typedVal.mValue;
  7078. }
  7079. else // stack alloc, unlooped, with append
  7080. {
  7081. sizeValue = GetConstValue(typeInstance->mInstSize);
  7082. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7083. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7084. bool wasDynAlloc = isDynAlloc;
  7085. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7086. if (!isDynAlloc)
  7087. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7088. else
  7089. {
  7090. MarkDynStack(scopeData);
  7091. SaveStackState(scopeData);
  7092. }
  7093. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  7094. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  7095. if (!isDynAlloc)
  7096. {
  7097. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7098. }
  7099. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7100. bool mayBeLarge = false;
  7101. if (sizeValue.IsConst())
  7102. {
  7103. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  7104. if (constantInt->mInt64 >= 4096)
  7105. mayBeLarge = true;
  7106. }
  7107. else
  7108. mayBeLarge = true;
  7109. if (((type->IsObject() && (!mayBeLarge))) ||
  7110. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7111. ((zeroMemory) && (!mayBeLarge)))
  7112. {
  7113. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7114. }
  7115. BfIRValue castedVal;
  7116. if (!isDynAlloc)
  7117. {
  7118. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7119. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7120. mBfIRBuilder->ClearDebugLocation(castedVal);
  7121. mBfIRBuilder->SetInsertPoint(prevBlock);
  7122. if (WantsLifetimes())
  7123. {
  7124. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7125. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7126. }
  7127. }
  7128. else
  7129. {
  7130. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7131. }
  7132. auto typedVal = BfTypedValue(castedVal, typeInstance);
  7133. if (!noDtorCall)
  7134. {
  7135. bool doCondAlloca = false;
  7136. if (!IsTargetingBeefBackend())
  7137. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  7138. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  7139. }
  7140. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7141. return typedVal.mValue;
  7142. }
  7143. }
  7144. else // "Normal" stack alloc
  7145. {
  7146. BF_ASSERT(!sizeValue);
  7147. //TODO: If sizeValue is a constant then do this in the head IR builder
  7148. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7149. if (!isLoopedAlloc)
  7150. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7151. else
  7152. {
  7153. MarkDynStack(scopeData);
  7154. SaveStackState(scopeData);
  7155. }
  7156. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  7157. if (!isLoopedAlloc)
  7158. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7159. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7160. bool mayBeLarge = allocSize >= 4096;
  7161. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  7162. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7163. ((zeroMemory) && (!mayBeLarge)))
  7164. {
  7165. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  7166. // and memset is always safe
  7167. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7168. }
  7169. auto typedVal = BfTypedValue(allocaInst, type);
  7170. if (!isLoopedAlloc)
  7171. {
  7172. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7173. mBfIRBuilder->SetInsertPoint(prevBlock);
  7174. if (WantsLifetimes())
  7175. {
  7176. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7177. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7178. }
  7179. }
  7180. if (!noDtorCall)
  7181. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7182. if (typeInstance != NULL)
  7183. {
  7184. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  7185. }
  7186. else
  7187. {
  7188. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  7189. }
  7190. return allocaInst;
  7191. }
  7192. }
  7193. else if (arraySize)
  7194. {
  7195. if (isRawArrayAlloc)
  7196. {
  7197. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7198. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  7199. }
  7200. else
  7201. {
  7202. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7203. typeInstance = arrayType;
  7204. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7205. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7206. appendSizeValue = elementDataSize;
  7207. if (!type->IsSizeAligned())
  7208. {
  7209. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  7210. }
  7211. }
  7212. }
  7213. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  7214. {
  7215. auto vDataRef = GetClassVDataPtr(typeInstance);
  7216. BfIRValue result;
  7217. bool isResultInitialized = false;
  7218. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7219. if (typeInstance->mTypeOptionsIdx != -1)
  7220. {
  7221. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7222. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7223. }
  7224. if (!sizeValue)
  7225. sizeValue = GetConstValue(typeInstance->mInstSize);
  7226. if (appendSizeValue)
  7227. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7228. BfIRValue origSizeValue = sizeValue;
  7229. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  7230. if (isAllocEx)
  7231. {
  7232. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  7233. if (prepareStackTraceMethod)
  7234. {
  7235. SizedArray<BfIRValue, 2> irArgs;
  7236. irArgs.Add(sizeValue);
  7237. irArgs.Add(GetConstValue(stackCount));
  7238. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  7239. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  7240. }
  7241. }
  7242. if (allocTarget.mCustomAllocator)
  7243. {
  7244. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7245. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  7246. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  7247. {
  7248. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7249. mBfIRBuilder->PopulateType(classVDataType);
  7250. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7251. mBfIRBuilder->PopulateType(typeInstType);
  7252. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  7253. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  7254. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  7255. BfTypedValueExpression typedValueExpr;
  7256. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  7257. typedValueExpr.mRefNode = allocTarget.mRefNode;
  7258. BfExprEvaluator exprEvaluator(this);
  7259. SizedArray<BfExpression*, 2> argExprs;
  7260. argExprs.push_back(&typedValueExpr);
  7261. BfTypedValueExpression sizeValueExpr;
  7262. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  7263. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  7264. argExprs.push_back(&sizeValueExpr);
  7265. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7266. BfResolvedArgs argValues(&sizedArgExprs);
  7267. exprEvaluator.ResolveArgValues(argValues);
  7268. exprEvaluator.mNoBind = true;
  7269. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  7270. if (allocResult)
  7271. {
  7272. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  7273. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  7274. else
  7275. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  7276. isResultInitialized = true;
  7277. }
  7278. }
  7279. }
  7280. bool wasAllocated = false;
  7281. if (!result)
  7282. {
  7283. if (hasCustomAllocator)
  7284. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  7285. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc))
  7286. {
  7287. SizedArray<BfIRValue, 4> llvmArgs;
  7288. llvmArgs.push_back(sizeValue);
  7289. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7290. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7291. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7292. wasAllocated = true;
  7293. }
  7294. }
  7295. if (result)
  7296. {
  7297. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7298. {
  7299. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  7300. SizedArray<BfIRValue, 4> llvmArgs;
  7301. llvmArgs.push_back(objectPtr);
  7302. llvmArgs.push_back(origSizeValue);
  7303. llvmArgs.push_back(vDataRef);
  7304. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  7305. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  7306. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  7307. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  7308. if (wasAllocated)
  7309. {
  7310. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  7311. auto bytePtrType = CreatePointerType(byteType);
  7312. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  7313. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  7314. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  7315. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  7316. }
  7317. }
  7318. else
  7319. {
  7320. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  7321. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7322. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  7323. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  7324. }
  7325. }
  7326. else
  7327. {
  7328. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  7329. return GetDefaultValue(typeInstance);
  7330. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7331. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  7332. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7333. {
  7334. SizedArray<BfIRValue, 4> llvmArgs;
  7335. llvmArgs.push_back(vData);
  7336. llvmArgs.push_back(sizeValue);
  7337. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  7338. llvmArgs.push_back(GetConstValue(stackCount));
  7339. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  7340. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  7341. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7342. }
  7343. else
  7344. {
  7345. SizedArray<BfIRValue, 4> llvmArgs;
  7346. llvmArgs.push_back(sizeValue);
  7347. BfIRFunction irFunc;
  7348. if (mCompiler->mOptions.mDebugAlloc)
  7349. {
  7350. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  7351. irFunc = moduleMethodInstance.mFunc;
  7352. }
  7353. if (!irFunc)
  7354. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7355. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7356. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  7357. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  7358. mBfIRBuilder->CreateStore(vData, vdataPtr);
  7359. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7360. }
  7361. }
  7362. if ((zeroMemory) && (arraySize))
  7363. {
  7364. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7365. typeInstance = arrayType;
  7366. auto firstElementField = &arrayType->mFieldInstances.back();
  7367. int arrayClassSize = firstElementField->mDataOffset;
  7368. BfIRValue elementDataSize;
  7369. bool skipZero = false;
  7370. if (arraySize.IsConst())
  7371. {
  7372. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7373. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7374. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  7375. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  7376. if (constVal->mInt64 <= 0)
  7377. skipZero = true;
  7378. }
  7379. else
  7380. {
  7381. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  7382. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7383. }
  7384. if (!skipZero)
  7385. {
  7386. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7387. auto ptrType = CreatePointerType(i8Type);
  7388. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  7389. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  7390. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  7391. appendSizeValue = elementDataSize;
  7392. }
  7393. }
  7394. return result;
  7395. }
  7396. else
  7397. {
  7398. if (!sizeValue)
  7399. sizeValue = GetConstValue(allocSize);
  7400. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  7401. }
  7402. }
  7403. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  7404. {
  7405. if ((type == NULL) || (refNode == NULL))
  7406. return;
  7407. auto typeInstance = type->ToTypeInstance();
  7408. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  7409. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  7410. }
  7411. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  7412. {
  7413. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7414. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7415. }
  7416. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  7417. {
  7418. if (sizeMultiple == 0)
  7419. sizeMultiple = align;
  7420. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  7421. {
  7422. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  7423. {
  7424. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7425. BF_ASSERT(localVar->mName == "appendIdx");
  7426. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  7427. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7428. if (align > 1)
  7429. {
  7430. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7431. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7432. }
  7433. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  7434. }
  7435. else
  7436. {
  7437. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  7438. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  7439. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  7440. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7441. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7442. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  7443. }
  7444. }
  7445. if (mCurMethodState->mCurAppendAlign == 0)
  7446. mCurMethodState->mCurAppendAlign = sizeMultiple;
  7447. else
  7448. {
  7449. if (sizeMultiple % align == 0)
  7450. mCurMethodState->mCurAppendAlign = align;
  7451. else
  7452. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  7453. }
  7454. }
  7455. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  7456. {
  7457. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7458. BF_ASSERT(localVar->mName == "appendIdx");
  7459. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  7460. BfIRValue retValue;
  7461. BfTypeInstance* retTypeInstance = NULL;
  7462. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  7463. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  7464. if (arraySize)
  7465. {
  7466. if (isRawArrayAlloc)
  7467. {
  7468. EmitAppendAlign(type->mAlign);
  7469. BfPointerType* ptrType = CreatePointerType(type);
  7470. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7471. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7472. if (mSystem->mPtrSize != 4)
  7473. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7474. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7475. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7476. if (zeroMemory)
  7477. {
  7478. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  7479. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  7480. }
  7481. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  7482. }
  7483. else
  7484. {
  7485. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7486. EmitAppendAlign(arrayType->mAlign, type->mSize);
  7487. auto firstElementField = &arrayType->mFieldInstances.back();
  7488. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  7489. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  7490. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7491. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7492. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7493. if (mSystem->mPtrSize != 4)
  7494. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7495. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7496. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7497. if (zeroMemory)
  7498. {
  7499. // Only zero out the actual elements
  7500. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  7501. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  7502. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  7503. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  7504. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  7505. }
  7506. retTypeInstance = arrayType;
  7507. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  7508. }
  7509. }
  7510. else
  7511. {
  7512. auto typeInst = type->ToTypeInstance();
  7513. BfIRValue sizeValue;
  7514. BfIRType toType;
  7515. if (typeInst != NULL)
  7516. {
  7517. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  7518. sizeValue = GetConstValue(typeInst->mInstSize);
  7519. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  7520. }
  7521. else
  7522. {
  7523. EmitAppendAlign(type->mAlign, type->mSize);
  7524. sizeValue = GetConstValue(type->mSize);
  7525. auto toPtrType = CreatePointerType(type);
  7526. toType = mBfIRBuilder->MapType(toPtrType);
  7527. }
  7528. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7529. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7530. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7531. retTypeInstance = typeInst;
  7532. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7533. }
  7534. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7535. {
  7536. mBfIRBuilder->PopulateType(retTypeInstance);
  7537. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7538. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7539. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7540. auto curThis = GetThis();
  7541. BfIRValue newFlags;
  7542. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7543. {
  7544. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7545. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7546. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7547. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7548. }
  7549. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7550. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7551. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7552. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7553. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7554. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7555. {
  7556. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7557. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7558. }
  7559. }
  7560. if (appendSizeValue)
  7561. {
  7562. EmitAppendAlign(appendAllocAlign);
  7563. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7564. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7565. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7566. }
  7567. return retValue;
  7568. }
  7569. bool BfModule::IsOptimized()
  7570. {
  7571. if (mProject == NULL)
  7572. return false;
  7573. int optLevel = GetModuleOptions().mOptLevel;
  7574. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7575. }
  7576. bool BfModule::IsTargetingBeefBackend()
  7577. {
  7578. if (mProject == NULL)
  7579. return false;
  7580. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7581. }
  7582. bool BfModule::WantsLifetimes()
  7583. {
  7584. if (mProject == NULL)
  7585. return false;
  7586. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7587. }
  7588. bool BfModule::HasCompiledOutput()
  7589. {
  7590. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7591. }
  7592. // We will skip the object access check for any occurances of this value
  7593. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7594. {
  7595. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7596. return;
  7597. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7598. return;
  7599. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7600. return;
  7601. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7602. }
  7603. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7604. {
  7605. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7606. return;
  7607. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7608. return;
  7609. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7610. auto typeOptions = GetTypeOptions();
  7611. if (typeOptions != NULL)
  7612. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  7613. if (!emitObjectAccessCheck)
  7614. return;
  7615. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7616. {
  7617. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7618. return;
  7619. }
  7620. if (typedVal.IsAddr())
  7621. typedVal = LoadValue(typedVal);
  7622. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7623. }
  7624. void BfModule::EmitEnsureInstructionAt()
  7625. {
  7626. if (mProject == NULL)
  7627. return;
  7628. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7629. return;
  7630. mBfIRBuilder->CreateEnsureInstructionAt();
  7631. }
  7632. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7633. {
  7634. if (mBfIRBuilder->mIgnoreWrites)
  7635. return; // Nothing needed here
  7636. auto irb = mBfIRBuilder;
  7637. auto checkBB = irb->CreateBlock("as.check");
  7638. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7639. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7640. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7641. auto intPtrType = CreatePointerType(intType);
  7642. auto intPtrPtrType = CreatePointerType(intPtrType);
  7643. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7644. auto int32PtrType = CreatePointerType(int32Type);
  7645. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7646. if (mCompiler->mOptions.mAllowHotSwapping)
  7647. {
  7648. BfExprEvaluator exprEvaluator(this);
  7649. AddBasicBlock(checkBB);
  7650. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7651. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7652. SizedArray<BfIRValue, 4> irArgs;
  7653. irArgs.push_back(objectParam);
  7654. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7655. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7656. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7657. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7658. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7659. }
  7660. else
  7661. {
  7662. AddBasicBlock(checkBB);
  7663. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7664. vDataPtr = irb->CreateLoad(vDataPtr);
  7665. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7666. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7667. if (targetType->IsInterface())
  7668. {
  7669. auto targetTypeInst = targetType->ToTypeInstance();
  7670. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7671. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7672. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7673. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7674. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7675. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7676. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7677. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7678. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7679. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7680. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7681. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7682. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7683. }
  7684. else
  7685. {
  7686. if (!targetType->IsTypeInstance())
  7687. targetType = GetWrappedStructType(targetType);
  7688. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7689. int inheritanceIdOfs = mSystem->mPtrSize;
  7690. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7691. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7692. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7693. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7694. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7695. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7696. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7697. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7698. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7699. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7700. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7701. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7702. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7703. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7704. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7705. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7706. }
  7707. }
  7708. }
  7709. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7710. {
  7711. if (mBfIRBuilder->mIgnoreWrites)
  7712. return;
  7713. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7714. auto typeOptions = GetTypeOptions();
  7715. if (typeOptions != NULL)
  7716. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  7717. if (emitDynamicCastCheck)
  7718. {
  7719. int wantTypeId = 0;
  7720. if (!type->IsGenericParam())
  7721. wantTypeId = type->mTypeId;
  7722. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7723. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7724. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7725. AddBasicBlock(failBlock);
  7726. SizedArray<BfIRValue, 8> llvmArgs;
  7727. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7728. llvmArgs.push_back(bitAddr);
  7729. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7730. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7731. BF_ASSERT(objDynCheck);
  7732. if (objDynCheck)
  7733. {
  7734. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7735. }
  7736. mBfIRBuilder->CreateBr(endBlock);
  7737. AddBasicBlock(endBlock);
  7738. }
  7739. }
  7740. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7741. {
  7742. if (mBfIRBuilder->mIgnoreWrites)
  7743. {
  7744. if (toType == mContext->mBfObjectType)
  7745. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  7746. if (toType->IsBoxed())
  7747. {
  7748. BfBoxedType* boxedType = (BfBoxedType*)toType;
  7749. if (boxedType->mElementType->IsGenericParam())
  7750. {
  7751. if (typedVal.mType == boxedType->mElementType)
  7752. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  7753. else
  7754. return BfTypedValue();
  7755. }
  7756. }
  7757. }
  7758. BP_ZONE("BoxValue");
  7759. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7760. if (typedVal.mType->IsNullable())
  7761. {
  7762. typedVal = MakeAddressable(typedVal);
  7763. auto innerType = typedVal.mType->GetUnderlyingType();
  7764. if (!innerType->IsValueType())
  7765. {
  7766. if (!mIgnoreErrors)
  7767. Fail("Only value types can be boxed", srcNode);
  7768. return BfTypedValue();
  7769. }
  7770. auto boxedType = CreateBoxedType(innerType);
  7771. auto resultType = toType;
  7772. if (resultType == NULL)
  7773. resultType = boxedType;
  7774. if (mBfIRBuilder->mIgnoreWrites)
  7775. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  7776. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7777. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7778. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7779. mBfIRBuilder->PopulateType(typedVal.mType);
  7780. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7781. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7782. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7783. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7784. mBfIRBuilder->AddBlock(boxBB);
  7785. mBfIRBuilder->SetInsertPoint(boxBB);
  7786. BfScopeData newScope;
  7787. newScope.mOuterIsConditional = true;
  7788. mCurMethodState->AddScope(&newScope);
  7789. NewScopeState();
  7790. BfIRValue nullableValueAddr;
  7791. BfIRValue loadedVal;
  7792. if (innerType->IsValuelessType())
  7793. {
  7794. loadedVal = mBfIRBuilder->GetFakeVal();
  7795. }
  7796. else
  7797. {
  7798. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7799. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7800. }
  7801. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7802. RestoreScopeState();
  7803. if (!boxedVal)
  7804. return BfTypedValue();
  7805. mBfIRBuilder->CreateBr(endBB);
  7806. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7807. mBfIRBuilder->AddBlock(endBB);
  7808. mBfIRBuilder->SetInsertPoint(endBB);
  7809. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7810. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7811. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7812. return BfTypedValue(phi, resultType);
  7813. }
  7814. bool alreadyCheckedCast = false;
  7815. BfTypeInstance* toTypeInstance = NULL;
  7816. if (toType != NULL)
  7817. toTypeInstance = toType->ToTypeInstance();
  7818. bool isStructPtr = typedVal.mType->IsStructPtr();
  7819. if (fromStructTypeInstance == NULL)
  7820. {
  7821. auto primType = (BfPrimitiveType*)typedVal.mType;
  7822. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  7823. {
  7824. // Can always do IHashable
  7825. alreadyCheckedCast = true;
  7826. }
  7827. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  7828. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7829. if (isStructPtr)
  7830. {
  7831. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7832. alreadyCheckedCast = true;
  7833. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7834. }
  7835. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  7836. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7837. }
  7838. if (fromStructTypeInstance == NULL)
  7839. return BfTypedValue();
  7840. // Need to box it
  7841. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  7842. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7843. {
  7844. if (mBfIRBuilder->mIgnoreWrites)
  7845. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  7846. auto boxedType = CreateBoxedType(typedVal.mType);
  7847. mBfIRBuilder->PopulateType(boxedType);
  7848. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7849. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7850. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7851. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7852. if (boxedType->IsUnspecializedType())
  7853. {
  7854. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  7855. }
  7856. else
  7857. {
  7858. PopulateType(fromStructTypeInstance);
  7859. if (!fromStructTypeInstance->IsValuelessType())
  7860. {
  7861. typedVal = LoadValue(typedVal);
  7862. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7863. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7864. {
  7865. auto ptrType = CreatePointerType(typedVal.mType);
  7866. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7867. }
  7868. if (typedVal.IsSplat())
  7869. {
  7870. AggregateSplatIntoAddr(typedVal, valPtr);
  7871. }
  7872. else
  7873. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7874. }
  7875. }
  7876. if (toType == NULL)
  7877. {
  7878. return BfTypedValue(allocaInst, boxedType);
  7879. }
  7880. else
  7881. {
  7882. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7883. return BfTypedValue(castedValue, toType);
  7884. }
  7885. }
  7886. return BfTypedValue();
  7887. }
  7888. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7889. {
  7890. BfTypeInstance* checkTypeInst = typeInst;
  7891. while (checkTypeInst != NULL)
  7892. {
  7893. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7894. {
  7895. if (checkProp->mName == propDef->mName)
  7896. {
  7897. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7898. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7899. {
  7900. propDef = checkProp;
  7901. typeInst = checkTypeInst;
  7902. return true;
  7903. }
  7904. }
  7905. }
  7906. checkTypeInst = checkTypeInst->mBaseType;
  7907. }
  7908. return false;
  7909. }
  7910. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7911. {
  7912. if (!typeInstance->mResolvingVarField)
  7913. {
  7914. if (typeInstance->IsIncomplete())
  7915. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7916. }
  7917. else
  7918. {
  7919. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7920. {
  7921. AssertErrorState();
  7922. return NULL;
  7923. }
  7924. }
  7925. if (assertName != NULL)
  7926. {
  7927. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7928. }
  7929. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7930. if (methodGroup.mDefault == NULL)
  7931. {
  7932. if (!mCompiler->mIsResolveOnly)
  7933. {
  7934. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) || (typeInstance->mTypeFailed));
  7935. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  7936. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7937. // Get it from the owning module so we don't create a reference prematurely...
  7938. auto declModule = typeInstance->mModule;
  7939. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7940. }
  7941. else
  7942. {
  7943. auto declModule = typeInstance->mModule;
  7944. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7945. }
  7946. }
  7947. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7948. //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
  7949. // be from a call to the NON-raw version
  7950. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7951. // {
  7952. // methodInstance->mIsReified = mIsReified;
  7953. // if (methodInstance->mMethodProcessRequest == NULL)
  7954. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7955. // }
  7956. return methodInstance;
  7957. }
  7958. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7959. {
  7960. if (methodDef->mIsLocalMethod)
  7961. {
  7962. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7963. }
  7964. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7965. }
  7966. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7967. {
  7968. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7969. while (typeInstance != NULL)
  7970. {
  7971. typeInstance->mTypeDef->PopulateMemberSets();
  7972. BfMemberSetEntry* entry = NULL;
  7973. BfMethodDef* methodDef = NULL;
  7974. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7975. methodDef = (BfMethodDef*)entry->mMemberDef;
  7976. while (methodDef != NULL)
  7977. {
  7978. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7979. (methodDef->mGenericParams.size() == 0) &&
  7980. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7981. return GetRawMethodInstance(typeInstance, methodDef);
  7982. methodDef = methodDef->mNextWithSameName;
  7983. }
  7984. if (!checkBase)
  7985. break;
  7986. typeInstance = typeInstance->mBaseType;
  7987. }
  7988. return NULL;
  7989. }
  7990. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7991. {
  7992. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7993. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7994. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7995. if (!owner->IsGenericTypeInstance())
  7996. return methodInstance;
  7997. BF_ASSERT(!owner->IsDelegateFromTypeRef());
  7998. BF_ASSERT(!owner->IsTuple());
  7999. auto genericType = (BfTypeInstance*)owner;
  8000. if (genericType->IsUnspecializedType())
  8001. return methodInstance;
  8002. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  8003. if (unspecializedType == NULL)
  8004. {
  8005. AssertErrorState();
  8006. return methodInstance;
  8007. }
  8008. if (unspecializedType == NULL)
  8009. return methodInstance;
  8010. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  8011. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  8012. }
  8013. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  8014. {
  8015. int genericCount = 0;
  8016. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  8017. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  8018. {
  8019. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  8020. if (param->IsGenericParam())
  8021. genericCount++;
  8022. }
  8023. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  8024. genericCount++;
  8025. return genericCount;
  8026. }
  8027. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  8028. {
  8029. BF_ASSERT(!mIsScratchModule);
  8030. BF_ASSERT(mIsReified);
  8031. BfModule* mainModule = this;
  8032. if (mParentModule != NULL)
  8033. mainModule = mParentModule;
  8034. BfModule* specModule = NULL;
  8035. BfModule** specModulePtr = NULL;
  8036. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  8037. {
  8038. return *specModulePtr;
  8039. }
  8040. else
  8041. {
  8042. String specModuleName = mModuleName;
  8043. for (auto bfProject : projectList)
  8044. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  8045. specModule = new BfModule(mContext, specModuleName);
  8046. specModule->mProject = mainModule->mProject;
  8047. specModule->mParentModule = mainModule;
  8048. specModule->mIsSpecializedMethodModuleRoot = true;
  8049. specModule->Init();
  8050. Array<BfProject*> projList;
  8051. for (auto project : projectList)
  8052. projList.Add(project);
  8053. mainModule->mSpecializedMethodModules[projList] = specModule;
  8054. }
  8055. return specModule;
  8056. }
  8057. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  8058. {
  8059. if (mCompiler->IsSkippingExtraResolveChecks())
  8060. return BfIRValue();
  8061. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  8062. {
  8063. //BF_ASSERT(!methodInstance->mIRFunction);
  8064. return BfIRValue();
  8065. }
  8066. auto methodDef = methodInstance->mMethodDef;
  8067. StringT<128> methodName;
  8068. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  8069. if (isInlined != methodInstance->mAlwaysInline)
  8070. {
  8071. if (isInlined)
  8072. methodName += "__INLINE";
  8073. else
  8074. methodName += "__NOINLINE";
  8075. }
  8076. if (tryExisting)
  8077. {
  8078. auto func = mBfIRBuilder->GetFunction(methodName);
  8079. if (func)
  8080. return func;
  8081. }
  8082. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  8083. {
  8084. if (methodDeclaration->mExternSpecifier != NULL)
  8085. {
  8086. auto intrinsic = GetIntrinsic(methodInstance);
  8087. if (intrinsic)
  8088. return intrinsic;
  8089. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  8090. /*auto func = mBfIRBuilder->GetFunction(methodName);
  8091. if (func)
  8092. return func;*/
  8093. }
  8094. }
  8095. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  8096. {
  8097. return CreateDllImportGlobalVar(methodInstance, false);
  8098. }
  8099. BfIRType returnType;
  8100. SizedArray<BfIRType, 8> paramTypes;
  8101. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  8102. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  8103. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  8104. auto callingConv = GetIRCallingConvention(methodInstance);
  8105. if (callingConv != BfIRCallingConv_CDecl)
  8106. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  8107. SetupIRMethod(methodInstance, func, isInlined);
  8108. // auto srcModule = methodInstance->GetOwner()->GetModule();
  8109. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  8110. // {
  8111. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  8112. // {
  8113. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  8114. // }
  8115. // }
  8116. return func;
  8117. }
  8118. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  8119. {
  8120. if (assertName != NULL)
  8121. {
  8122. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8123. }
  8124. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8125. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8126. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  8127. {
  8128. // Can't use it, not reified
  8129. methodInstance = NULL;
  8130. }
  8131. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  8132. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  8133. {
  8134. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  8135. return BfModuleMethodInstance(methodInstance, func);
  8136. }
  8137. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  8138. }
  8139. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8140. {
  8141. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8142. while (typeInstance != NULL)
  8143. {
  8144. typeInstance->mTypeDef->PopulateMemberSets();
  8145. BfMemberSetEntry* entry = NULL;
  8146. BfMethodDef* methodDef = NULL;
  8147. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8148. methodDef = (BfMethodDef*)entry->mMemberDef;
  8149. while (methodDef != NULL)
  8150. {
  8151. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8152. (methodDef->mGenericParams.size() == 0) &&
  8153. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8154. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8155. methodDef = methodDef->mNextWithSameName;
  8156. }
  8157. if (!checkBase)
  8158. break;
  8159. typeInstance = typeInstance->mBaseType;
  8160. }
  8161. return BfModuleMethodInstance();
  8162. }
  8163. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  8164. {
  8165. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8166. while (typeInstance != NULL)
  8167. {
  8168. typeInstance->mTypeDef->PopulateMemberSets();
  8169. BfMemberSetEntry* entry = NULL;
  8170. BfMethodDef* methodDef = NULL;
  8171. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8172. methodDef = (BfMethodDef*)entry->mMemberDef;
  8173. while (methodDef != NULL)
  8174. {
  8175. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8176. (methodDef->mGenericParams.size() == 0) &&
  8177. (paramTypes.size() == methodDef->mParams.size()))
  8178. {
  8179. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8180. if (moduleMethodInstance.mMethodInstance != NULL)
  8181. {
  8182. bool matches = true;
  8183. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8184. {
  8185. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  8186. matches = false;
  8187. }
  8188. if (matches)
  8189. return moduleMethodInstance;
  8190. }
  8191. }
  8192. methodDef = methodDef->mNextWithSameName;
  8193. }
  8194. if (!checkBase)
  8195. break;
  8196. typeInstance = typeInstance->mBaseType;
  8197. }
  8198. return BfModuleMethodInstance();
  8199. }
  8200. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  8201. {
  8202. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  8203. PopulateType(internalType);
  8204. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  8205. if (!moduleMethodInstance)
  8206. {
  8207. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  8208. }
  8209. return moduleMethodInstance;
  8210. }
  8211. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8212. {
  8213. while (typeInstance != NULL)
  8214. {
  8215. typeInstance->mTypeDef->PopulateMemberSets();
  8216. BfMemberSetEntry* entry = NULL;
  8217. BfMethodDef* methodDef = NULL;
  8218. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8219. methodDef = (BfMethodDef*)entry->mMemberDef;
  8220. while (methodDef != NULL)
  8221. {
  8222. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8223. (methodDef->mGenericParams.size() == 0) &&
  8224. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8225. {
  8226. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  8227. if (!methodInstanceGroup.IsImplemented())
  8228. return false;
  8229. if (methodInstanceGroup.mDefault == NULL)
  8230. return false;
  8231. return methodInstanceGroup.mDefault->mIsReified;
  8232. }
  8233. methodDef = methodDef->mNextWithSameName;
  8234. }
  8235. if (!checkBase)
  8236. break;
  8237. typeInstance = typeInstance->mBaseType;
  8238. }
  8239. return false;
  8240. }
  8241. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8242. {
  8243. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8244. while (typeInstance != NULL)
  8245. {
  8246. typeInstance->mTypeDef->PopulateMemberSets();
  8247. BfMemberSetEntry* entry = NULL;
  8248. BfMethodDef* methodDef = NULL;
  8249. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8250. methodDef = (BfMethodDef*)entry->mMemberDef;
  8251. while (methodDef != NULL)
  8252. {
  8253. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  8254. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8255. return true;
  8256. methodDef = methodDef->mNextWithSameName;
  8257. }
  8258. if (!checkBase)
  8259. break;
  8260. typeInstance = typeInstance->mBaseType;
  8261. }
  8262. return BfModuleMethodInstance();
  8263. }
  8264. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  8265. {
  8266. auto methodDef = methodInst->mMethodDef;
  8267. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  8268. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8269. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  8270. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8271. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8272. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  8273. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8274. String methodName;
  8275. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  8276. {
  8277. methodName = TypeToString(type, typeNameFlags);
  8278. if (methodName == "$")
  8279. methodName = "";
  8280. else if (!methodName.IsEmpty())
  8281. methodName += ".";
  8282. }
  8283. String accessorString;
  8284. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  8285. if (methodInst->mMethodDef->mIsLocalMethod)
  8286. {
  8287. int atPos = (int)methodDefName.IndexOf('$');
  8288. methodDefName.RemoveToEnd(atPos);
  8289. methodDefName.Replace("@", ".");
  8290. }
  8291. else
  8292. {
  8293. int atPos = (int)methodDefName.IndexOf('$');
  8294. if (atPos != -1)
  8295. {
  8296. accessorString = methodDefName.Substring(0, atPos);
  8297. if ((accessorString == "get") || (accessorString == "set"))
  8298. {
  8299. methodDefName = methodDefName.Substring(atPos + 1);
  8300. }
  8301. else
  8302. accessorString = "";
  8303. }
  8304. }
  8305. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  8306. {
  8307. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8308. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8309. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8310. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  8311. methodName += ".";
  8312. }
  8313. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  8314. {
  8315. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8316. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8317. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8318. methodName += "[";
  8319. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  8320. methodName += "].";
  8321. }
  8322. if (methodDef->mMethodType == BfMethodType_Operator)
  8323. {
  8324. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  8325. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  8326. {
  8327. // Don't add explicit/implicit part, since that's not available in GCC mangling
  8328. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  8329. {
  8330. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8331. methodName += "explicit ";
  8332. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8333. methodName += "explicit ";
  8334. }*/
  8335. methodName += "operator ";
  8336. if (methodInst->mReturnType != NULL)
  8337. methodName += TypeToString(methodInst->mReturnType);
  8338. }
  8339. else
  8340. {
  8341. methodName += "operator";
  8342. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  8343. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  8344. }
  8345. }
  8346. else if (methodDef->mMethodType == BfMethodType_Ctor)
  8347. {
  8348. if (methodDef->mIsStatic)
  8349. methodName += "__BfStaticCtor";
  8350. else
  8351. methodName += "this";
  8352. accessorString = "";
  8353. }
  8354. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  8355. {
  8356. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8357. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8358. propertyDecl->mNameNode->ToString(methodName);
  8359. methodName += " get accessor";
  8360. return methodName;
  8361. }
  8362. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8363. {
  8364. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8365. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8366. propertyDecl->mNameNode->ToString(methodName);
  8367. methodName += " set accessor";
  8368. return methodName;
  8369. }
  8370. else
  8371. methodName += methodDefName;
  8372. BfTypeVector newMethodGenericArgs;
  8373. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8374. {
  8375. methodName += "<";
  8376. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  8377. {
  8378. if (i > 0)
  8379. methodName += ", ";
  8380. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8381. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  8382. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8383. if (allowResolveGenericParamNames)
  8384. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8385. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  8386. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8387. {
  8388. bool hasEmpty = false;
  8389. for (auto arg : *methodGenericArgs)
  8390. {
  8391. if (arg == NULL)
  8392. hasEmpty = true;
  8393. }
  8394. if (hasEmpty)
  8395. {
  8396. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  8397. {
  8398. auto arg = (*methodGenericArgs)[genericIdx];
  8399. if (arg != NULL)
  8400. newMethodGenericArgs.push_back(arg);
  8401. else
  8402. {
  8403. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  8404. if (genericParamInst->mTypeConstraint != NULL)
  8405. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  8406. else
  8407. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  8408. }
  8409. }
  8410. methodGenericArgs = &newMethodGenericArgs;
  8411. }
  8412. if (type->IsUnspecializedType())
  8413. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8414. }
  8415. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  8416. {
  8417. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  8418. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  8419. methodName += TypeToString(type, typeNameFlags);
  8420. }
  8421. else
  8422. methodName += TypeToString(type, typeNameFlags);
  8423. }
  8424. methodName += ">";
  8425. }
  8426. if (accessorString.length() == 0)
  8427. {
  8428. int dispParamIdx = 0;
  8429. methodName += "(";
  8430. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  8431. {
  8432. int paramKind = methodInst->GetParamKind(paramIdx);
  8433. if (paramKind == BfParamKind_ImplicitCapture)
  8434. continue;
  8435. if (dispParamIdx > 0)
  8436. methodName += ", ";
  8437. if (paramKind == BfParamKind_Params)
  8438. methodName += "params ";
  8439. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8440. BfType* type = methodInst->GetParamType(paramIdx);
  8441. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8442. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8443. methodName += TypeToString(type, typeNameFlags);
  8444. methodName += " ";
  8445. methodName += methodInst->GetParamName(paramIdx);
  8446. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  8447. if (paramInitializer != NULL)
  8448. {
  8449. methodName += " = ";
  8450. methodName += paramInitializer->ToString();
  8451. }
  8452. dispParamIdx++;
  8453. }
  8454. methodName += ")";
  8455. }
  8456. if (accessorString.length() != 0)
  8457. {
  8458. methodName += " " + accessorString;
  8459. }
  8460. return methodName;
  8461. }
  8462. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  8463. {
  8464. if ((flagsLeft & checkFlag) == 0)
  8465. return;
  8466. if (!str.empty())
  8467. {
  8468. if (flagsLeft == checkFlag)
  8469. {
  8470. if ((int)str.IndexOf(',') != -1)
  8471. str += ", and ";
  8472. else
  8473. str += " and ";
  8474. }
  8475. else
  8476. str += ", ";
  8477. }
  8478. str += addString;
  8479. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  8480. }
  8481. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  8482. {
  8483. String resultStr;
  8484. auto flagsLeft = attrTarget;
  8485. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  8486. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  8487. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  8488. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  8489. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  8490. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  8491. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  8492. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  8493. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  8494. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  8495. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  8496. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  8497. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  8498. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  8499. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  8500. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  8501. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  8502. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  8503. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  8504. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  8505. if (resultStr.IsEmpty())
  8506. return "<nothing>";
  8507. return resultStr;
  8508. }
  8509. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  8510. {
  8511. auto constant = mBfIRBuilder->GetConstant(irVal);
  8512. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  8513. if (stringPoolIdx != -1)
  8514. {
  8515. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  8516. return;
  8517. }
  8518. if (constant->mConstType == BfConstType_Array)
  8519. {
  8520. auto constArray = (BfConstantArray*)constant;
  8521. SizedArray<BfIRValue, 8> newVals;
  8522. for (auto val : constArray->mValues)
  8523. {
  8524. auto newVal = val;
  8525. CurrentAddToConstHolder(newVal);
  8526. newVals.push_back(newVal);
  8527. }
  8528. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  8529. return;
  8530. }
  8531. if (constant->mConstType == BfConstType_GlobalVar)
  8532. {
  8533. NOP;
  8534. }
  8535. auto origConst = irVal;
  8536. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  8537. {
  8538. auto bitcast = (BfConstantBitCast*)constant;
  8539. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  8540. }
  8541. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8542. }
  8543. void BfModule::ClearConstData()
  8544. {
  8545. mBfIRBuilder->ClearConstData();
  8546. mStringObjectPool.Clear();
  8547. mStringCharPtrPool.Clear();
  8548. mStringPoolRefs.Clear();
  8549. }
  8550. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8551. {
  8552. switch (constant->mTypeCode)
  8553. {
  8554. case BfTypeCode_StringId:
  8555. case BfTypeCode_Boolean:
  8556. case BfTypeCode_Int8:
  8557. case BfTypeCode_UInt8:
  8558. case BfTypeCode_Int16:
  8559. case BfTypeCode_UInt16:
  8560. case BfTypeCode_Int32:
  8561. case BfTypeCode_UInt32:
  8562. case BfTypeCode_Int64:
  8563. case BfTypeCode_UInt64:
  8564. case BfTypeCode_IntPtr:
  8565. case BfTypeCode_UIntPtr:
  8566. case BfTypeCode_IntUnknown:
  8567. case BfTypeCode_UIntUnknown:
  8568. case BfTypeCode_Char8:
  8569. case BfTypeCode_Char16:
  8570. case BfTypeCode_Char32:
  8571. case BfTypeCode_Float:
  8572. case BfTypeCode_Double:
  8573. {
  8574. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8575. BfTypedValue typedValue;
  8576. if (constant->mTypeCode == BfTypeCode_StringId)
  8577. {
  8578. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8579. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8580. {
  8581. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType), wantType);
  8582. return typedValue;
  8583. }
  8584. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  8585. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType), stringType);
  8586. }
  8587. if (!typedValue)
  8588. {
  8589. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8590. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8591. }
  8592. if (typedValue.mType == wantType)
  8593. return typedValue;
  8594. if (wantType->IsTypedPrimitive())
  8595. {
  8596. if (typedValue.mType == wantType->GetUnderlyingType())
  8597. {
  8598. typedValue.mType = wantType;
  8599. return typedValue;
  8600. }
  8601. }
  8602. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8603. if (!castedTypedValue)
  8604. return BfTypedValue();
  8605. return castedTypedValue;
  8606. }
  8607. break;
  8608. default: break;
  8609. }
  8610. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8611. BF_ASSERT(irValue);
  8612. if (!irValue)
  8613. return BfTypedValue();
  8614. return BfTypedValue(irValue, wantType, false);
  8615. }
  8616. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8617. {
  8618. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8619. {
  8620. return GetDefaultValue(wantType);
  8621. }
  8622. if (constant->mTypeCode == BfTypeCode_StringId)
  8623. {
  8624. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8625. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8626. {
  8627. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8628. BfIRValue stringObjConst = GetStringObjectValue(str);
  8629. if (wantType->IsPointer())
  8630. return GetStringCharPtr(stringObjConst);
  8631. return stringObjConst;
  8632. }
  8633. }
  8634. if (constant->mConstType == BfConstType_Array)
  8635. {
  8636. auto elementType = wantType->GetUnderlyingType();
  8637. auto constArray = (BfConstantArray*)constant;
  8638. SizedArray<BfIRValue, 8> newVals;
  8639. for (auto val : constArray->mValues)
  8640. {
  8641. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8642. }
  8643. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8644. }
  8645. return mBfIRBuilder->CreateConst(constant, constHolder);
  8646. }
  8647. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  8648. {
  8649. if (attrTarget == BfAttributeTargets_SkipValidate)
  8650. return;
  8651. for (auto& customAttribute : customAttributes->mAttributes)
  8652. {
  8653. if (!customAttribute.mAwaitingValidation)
  8654. continue;
  8655. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  8656. {
  8657. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  8658. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  8659. }
  8660. customAttribute.mAwaitingValidation = false;
  8661. }
  8662. }
  8663. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  8664. {
  8665. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  8666. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  8667. {
  8668. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  8669. }
  8670. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  8671. if (mCompiler->IsAutocomplete())
  8672. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  8673. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  8674. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  8675. BfAutoComplete* autoComplete = NULL;
  8676. if (mCompiler->mResolvePassData != NULL)
  8677. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8678. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  8679. {
  8680. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  8681. {
  8682. if (captureInfo == NULL)
  8683. {
  8684. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  8685. continue;
  8686. }
  8687. BfCaptureInfo::Entry captureEntry;
  8688. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  8689. if (!attributesDirective->mArguments.IsEmpty())
  8690. {
  8691. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  8692. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  8693. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  8694. }
  8695. captureInfo->mCaptures.Add(captureEntry);
  8696. continue;
  8697. }
  8698. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  8699. BfCustomAttribute customAttribute;
  8700. customAttribute.mAwaitingValidation = true;
  8701. customAttribute.mRef = attributesDirective;
  8702. if (attributesDirective->mAttrOpenToken != NULL)
  8703. targetOverride = (BfAttributeTargets)0;
  8704. if (attributesDirective->mAttributeTypeRef == NULL)
  8705. {
  8706. AssertErrorState();
  8707. continue;
  8708. }
  8709. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  8710. BfTypeDef* attrTypeDef = NULL;
  8711. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  8712. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  8713. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8714. {
  8715. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8716. if (attrTypeDef != NULL)
  8717. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8718. }
  8719. bool isBypassedAttr = false;
  8720. if (attrTypeDef != NULL)
  8721. {
  8722. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8723. // We solve it by having a 'bypass' for known attributes that Object depends on
  8724. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8725. {
  8726. //if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8727. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  8728. {
  8729. for (auto methodDef : attrTypeDef->mMethods)
  8730. {
  8731. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8732. {
  8733. customAttribute.mType = attrType->ToTypeInstance();
  8734. customAttribute.mCtor = methodDef;
  8735. isBypassedAttr = true;
  8736. break;
  8737. }
  8738. }
  8739. }
  8740. }
  8741. if (isBypassedAttr)
  8742. {
  8743. customAttribute.mAwaitingValidation = false;
  8744. customAttributes->mAttributes.push_back(customAttribute);
  8745. continue;
  8746. }
  8747. if (mContext->mCurTypeState != NULL)
  8748. {
  8749. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8750. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8751. }
  8752. else
  8753. {
  8754. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8755. }
  8756. }
  8757. BfTypeInstance* attrTypeInst = NULL;
  8758. if (attrType == NULL)
  8759. continue;
  8760. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8761. attrTypeInst = attrType->ToTypeInstance();
  8762. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8763. {
  8764. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8765. continue;
  8766. }
  8767. if (mCurTypeInstance != NULL)
  8768. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8769. customAttribute.mType = attrTypeInst;
  8770. BfConstResolver constResolver(this);
  8771. if (allowNonConstArgs)
  8772. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  8773. bool inPropSet = false;
  8774. SizedArray<BfResolvedArg, 2> argValues;
  8775. for (BfExpression* arg : attributesDirective->mArguments)
  8776. {
  8777. if (arg == NULL)
  8778. {
  8779. continue;
  8780. }
  8781. if (autoComplete != NULL)
  8782. autoComplete->mShowAttributeProperties = attrTypeInst;
  8783. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8784. {
  8785. inPropSet = true;
  8786. if (autoComplete != NULL)
  8787. autoComplete->CheckNode(assignExpr->mLeft);
  8788. String findName = assignExpr->mLeft->ToString();
  8789. BfPropertyDef* bestProp = NULL;
  8790. BfTypeInstance* bestPropTypeInst = NULL;
  8791. BfFieldDef* bestField = NULL;
  8792. BfTypeInstance* bestFieldTypeInst = NULL;
  8793. auto checkTypeInst = attrTypeInst;
  8794. while (checkTypeInst != NULL)
  8795. {
  8796. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8797. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8798. {
  8799. if (prop->mName == findName)
  8800. {
  8801. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8802. {
  8803. bestProp = prop;
  8804. bestPropTypeInst = checkTypeInst;
  8805. }
  8806. }
  8807. }
  8808. for (auto field : checkTypeInst->mTypeDef->mFields)
  8809. {
  8810. if (field->mName == findName)
  8811. {
  8812. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8813. {
  8814. bestField = field;
  8815. bestFieldTypeInst = checkTypeInst;
  8816. }
  8817. }
  8818. }
  8819. if ((bestProp != NULL) || (bestField != NULL))
  8820. break;
  8821. checkTypeInst = checkTypeInst->mBaseType;
  8822. }
  8823. bool handledExpr = false;
  8824. if (bestField != NULL)
  8825. {
  8826. handledExpr = true;
  8827. if (mCompiler->mResolvePassData != NULL)
  8828. {
  8829. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8830. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8831. {
  8832. autoComplete->mDefField = bestField;
  8833. autoComplete->mDefType = attrTypeDef;
  8834. }
  8835. }
  8836. if (bestField->mProtection != BfProtection_Public)
  8837. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8838. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8839. BfCustomAttributeSetField setField;
  8840. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8841. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8842. if (assignExpr->mRight != NULL)
  8843. {
  8844. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8845. if (result)
  8846. {
  8847. CurrentAddToConstHolder(result.mValue);
  8848. setField.mParam = result;
  8849. customAttribute.mSetField.push_back(setField);
  8850. }
  8851. }
  8852. }
  8853. else if (bestProp == NULL)
  8854. {
  8855. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8856. }
  8857. else
  8858. {
  8859. BfMethodDef* setMethod = NULL;
  8860. for (auto methodDef : bestProp->mMethods)
  8861. {
  8862. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8863. {
  8864. setMethod = methodDef;
  8865. break;
  8866. }
  8867. }
  8868. if (setMethod == NULL)
  8869. {
  8870. Fail("Property has no setter", assignExpr->mLeft);
  8871. }
  8872. else
  8873. {
  8874. if (mCompiler->mResolvePassData != NULL)
  8875. {
  8876. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8877. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8878. {
  8879. autoComplete->mDefProp = bestProp;
  8880. autoComplete->mDefType = attrTypeDef;
  8881. }
  8882. }
  8883. handledExpr = true;
  8884. if (bestProp->mProtection != BfProtection_Public)
  8885. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8886. BfResolvedArg resolvedArg;
  8887. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8888. BfCustomAttributeSetProperty setProperty;
  8889. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8890. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8891. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8892. if (methodInstance.mMethodInstance != NULL)
  8893. {
  8894. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8895. if (assignExpr->mRight != NULL)
  8896. {
  8897. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8898. if (result)
  8899. {
  8900. BF_ASSERT(result.mType == propType);
  8901. CurrentAddToConstHolder(result.mValue);
  8902. setProperty.mParam = result;
  8903. customAttribute.mSetProperties.push_back(setProperty);
  8904. }
  8905. }
  8906. }
  8907. }
  8908. }
  8909. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8910. constResolver.Resolve(assignExpr->mRight);
  8911. }
  8912. else
  8913. {
  8914. if (inPropSet)
  8915. {
  8916. Fail("Named attribute argument expected", arg); // CS1016
  8917. }
  8918. BfDeferEvalChecker deferEvalChecker;
  8919. arg->Accept(&deferEvalChecker);
  8920. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8921. BfResolvedArg resolvedArg;
  8922. resolvedArg.mExpression = arg;
  8923. if (deferParamEval)
  8924. {
  8925. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8926. }
  8927. else
  8928. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8929. if (!inPropSet)
  8930. {
  8931. argValues.push_back(resolvedArg);
  8932. }
  8933. }
  8934. if (autoComplete != NULL)
  8935. autoComplete->mShowAttributeProperties = NULL;
  8936. }
  8937. auto wasCapturingMethodInfo = false;
  8938. if (autoComplete != NULL)
  8939. {
  8940. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8941. if (attributesDirective->mCtorOpenParen != NULL)
  8942. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8943. }
  8944. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8945. attrTypeDef = attrTypeInst->mTypeDef;
  8946. bool success = true;
  8947. bool isFailurePass = false;
  8948. for (int pass = 0; pass < 2; pass++)
  8949. {
  8950. bool isFailurePass = pass == 1;
  8951. for (auto checkMethod : attrTypeDef->mMethods)
  8952. {
  8953. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8954. continue; // Don't match private default ctor if there's a user-defined one
  8955. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8956. continue;
  8957. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8958. continue;
  8959. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  8960. }
  8961. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8962. break;
  8963. }
  8964. if (autoComplete != NULL)
  8965. {
  8966. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8967. {
  8968. autoComplete->mIsCapturingMethodMatchInfo = true;
  8969. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8970. }
  8971. else
  8972. autoComplete->mIsCapturingMethodMatchInfo = false;
  8973. }
  8974. if (methodMatcher.mBestMethodDef == NULL)
  8975. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8976. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8977. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8978. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8979. {
  8980. Fail("Custom attribute circular reference", attributesDirective);
  8981. }
  8982. if (mCurTypeInstance != NULL)
  8983. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8984. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8985. success = false;
  8986. for (auto& arg : argValues)
  8987. {
  8988. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8989. {
  8990. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8991. constResolver.Resolve(expr);
  8992. }
  8993. }
  8994. // Move all those to the constHolder
  8995. for (auto& ctorArg : customAttribute.mCtorArgs)
  8996. {
  8997. if (ctorArg.IsConst())
  8998. CurrentAddToConstHolder(ctorArg);
  8999. }
  9000. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  9001. {
  9002. targetOverride = BfAttributeTargets_ReturnValue;
  9003. if (attrTarget != BfAttributeTargets_Method)
  9004. {
  9005. 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.",
  9006. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  9007. }
  9008. success = false;
  9009. }
  9010. if ((success) && (targetOverride != (BfAttributeTargets)0))
  9011. {
  9012. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  9013. {
  9014. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  9015. if (methodInfoEx->mMethodCustomAttributes == NULL)
  9016. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  9017. if (success)
  9018. {
  9019. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  9020. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  9021. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  9022. }
  9023. }
  9024. else
  9025. {
  9026. // Failed - ignore
  9027. success = false;
  9028. }
  9029. }
  9030. if (success)
  9031. {
  9032. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  9033. {
  9034. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  9035. {
  9036. if (prevCustomAttribute.mType == attrTypeInst)
  9037. {
  9038. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  9039. }
  9040. }
  9041. }
  9042. }
  9043. if (success)
  9044. {
  9045. customAttributes->mAttributes.push_back(customAttribute);
  9046. }
  9047. }
  9048. ValidateCustomAttributes(customAttributes, attrTarget);
  9049. }
  9050. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9051. {
  9052. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  9053. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  9054. return customAttributes;
  9055. }
  9056. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  9057. {
  9058. if (mCurTypeInstance->mCustomAttributes != NULL)
  9059. {
  9060. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9061. {
  9062. String typeName = TypeToString(customAttribute.mType);
  9063. if (typeName == "System.PackedAttribute")
  9064. {
  9065. isPacked = true;
  9066. }
  9067. else if (typeName == "System.UnionAttribute")
  9068. {
  9069. isUnion = true;
  9070. }
  9071. else if (typeName == "System.CReprAttribute")
  9072. {
  9073. isCRepr = true;
  9074. isOrdered = true;
  9075. }
  9076. else if (typeName == "System.OrderedAttribute")
  9077. {
  9078. isOrdered = true;
  9079. }
  9080. else if (typeName == "System.AlwaysIncludeAttribute")
  9081. {
  9082. for (auto setProp : customAttribute.mSetProperties)
  9083. {
  9084. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  9085. if (propertyDef->mName == "AssumeInstantiated")
  9086. {
  9087. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9088. if ((constant != NULL) && (constant->mBool))
  9089. mCurTypeInstance->mHasBeenInstantiated = true;
  9090. }
  9091. else if (propertyDef->mName == "IncludeAllMethods")
  9092. {
  9093. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9094. if ((constant != NULL) && (constant->mBool))
  9095. mCurTypeInstance->mIncludeAllMethods = true;
  9096. }
  9097. }
  9098. }
  9099. }
  9100. }
  9101. }
  9102. // Checking to see if we're an attribute or not
  9103. void BfModule::ProcessCustomAttributeData()
  9104. {
  9105. bool isAttribute = false;
  9106. auto checkTypeInst = mCurTypeInstance->mBaseType;
  9107. while (checkTypeInst != NULL)
  9108. {
  9109. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  9110. isAttribute = true;
  9111. checkTypeInst = checkTypeInst->mBaseType;
  9112. }
  9113. if (!isAttribute)
  9114. return;
  9115. auto attributeData = new BfAttributeData();
  9116. bool hasCustomAttribute = false;
  9117. if (mCurTypeInstance->mCustomAttributes != NULL)
  9118. {
  9119. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9120. {
  9121. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  9122. {
  9123. if (customAttribute.mCtorArgs.size() > 0)
  9124. {
  9125. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9126. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  9127. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9128. }
  9129. for (auto& setProp : customAttribute.mSetProperties)
  9130. {
  9131. BfPropertyDef* propDef = setProp.mPropertyRef;
  9132. if (propDef->mName == "AllowMultiple")
  9133. {
  9134. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9135. if (constant != NULL)
  9136. attributeData->mAllowMultiple = constant->mBool;
  9137. }
  9138. else if (propDef->mName == "Inherited")
  9139. {
  9140. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9141. if (constant != NULL)
  9142. attributeData->mInherited = constant->mBool;
  9143. }
  9144. else if (propDef->mName == "ValidOn")
  9145. {
  9146. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9147. if (constant != NULL)
  9148. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9149. }
  9150. }
  9151. hasCustomAttribute = true;
  9152. }
  9153. }
  9154. }
  9155. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  9156. {
  9157. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  9158. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  9159. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  9160. }
  9161. mCurTypeInstance->mAttributeData = attributeData;
  9162. }
  9163. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  9164. {
  9165. auto constant = constHolder->GetConstant(irValue);
  9166. if (constant == NULL)
  9167. return false;
  9168. if (constant->mTypeCode != BfTypeCode_StringId)
  9169. return false;
  9170. int stringId = constant->mInt32;
  9171. BfStringPoolEntry* entry = NULL;
  9172. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  9173. {
  9174. str = entry->mString;
  9175. }
  9176. else
  9177. {
  9178. BF_DBG_FATAL("Failed to find string by id");
  9179. }
  9180. return true;
  9181. }
  9182. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  9183. {
  9184. BfVariant variant;
  9185. variant.mTypeCode = BfTypeCode_None;
  9186. BfType* primType = NULL;
  9187. if (value.mType->IsPrimitiveType())
  9188. primType = (BfPrimitiveType*)value.mType;
  9189. else if (value.mType->IsTypedPrimitive())
  9190. primType = value.mType->GetUnderlyingType();
  9191. if (primType)
  9192. {
  9193. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  9194. if (constant != NULL)
  9195. {
  9196. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  9197. {
  9198. variant.mTypeCode = BfTypeCode_Let;
  9199. return variant;
  9200. }
  9201. switch (constant->mTypeCode)
  9202. {
  9203. case BfTypeCode_Int8:
  9204. case BfTypeCode_UInt8:
  9205. case BfTypeCode_Int16:
  9206. case BfTypeCode_UInt16:
  9207. case BfTypeCode_Int32:
  9208. case BfTypeCode_UInt32:
  9209. case BfTypeCode_Int64:
  9210. case BfTypeCode_UInt64:
  9211. case BfTypeCode_IntPtr:
  9212. case BfTypeCode_UIntPtr:
  9213. case BfTypeCode_IntUnknown:
  9214. case BfTypeCode_UIntUnknown:
  9215. case BfTypeCode_Float:
  9216. case BfTypeCode_Double:
  9217. case BfTypeCode_Char8:
  9218. case BfTypeCode_Char16:
  9219. case BfTypeCode_Char32:
  9220. variant.mTypeCode = constant->mTypeCode;
  9221. variant.mInt64 = constant->mInt64;
  9222. break;
  9223. default:
  9224. if (refNode != NULL)
  9225. Fail("Invalid const expression type", refNode);
  9226. break;
  9227. }
  9228. }
  9229. }
  9230. return variant;
  9231. }
  9232. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  9233. {
  9234. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  9235. {
  9236. auto elementType = typedValue.mType->GetUnderlyingType();
  9237. if (typedValue.IsAddr())
  9238. {
  9239. if (elementType->IsValuelessType())
  9240. {
  9241. BF_ASSERT(!typedValue.mValue);
  9242. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9243. }
  9244. else
  9245. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  9246. }
  9247. else
  9248. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9249. if (typedValue.mType->IsValuelessType())
  9250. {
  9251. BF_ASSERT(typedValue.mValue.IsFake());
  9252. }
  9253. }
  9254. return typedValue;
  9255. }
  9256. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  9257. {
  9258. if (!typedValue.IsAddr())
  9259. return typedValue;
  9260. PopulateType(typedValue.mType);
  9261. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  9262. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  9263. BfIRValue loadedVal = typedValue.mValue;
  9264. if (loadedVal)
  9265. {
  9266. if (typedValue.mType->IsVar())
  9267. {
  9268. return BfTypedValue(loadedVal, typedValue.mType, false);
  9269. }
  9270. /*if (isVolatile)
  9271. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  9272. PopulateType(typedValue.mType, BfPopulateType_Data);
  9273. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  9274. }
  9275. return BfTypedValue(loadedVal, typedValue.mType, false);
  9276. }
  9277. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  9278. {
  9279. if (typedValue.IsSplat())
  9280. return AggregateSplat(typedValue);
  9281. if (typedValue.IsAddr())
  9282. return LoadValue(typedValue);
  9283. return typedValue;
  9284. }
  9285. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  9286. {
  9287. if (!typedValue.IsSplat())
  9288. return typedValue;
  9289. if (typedValue.mType->IsValuelessType())
  9290. return typedValue;
  9291. int elementIdx = 0;
  9292. auto _ExtractValue = [&](BfType* checkType)
  9293. {
  9294. if (valueArrPtr != NULL)
  9295. return valueArrPtr[elementIdx++];
  9296. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  9297. };
  9298. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9299. {
  9300. if (checkType->IsStruct())
  9301. {
  9302. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9303. auto checkTypeInstance = checkType->ToTypeInstance();
  9304. if (checkTypeInstance->mBaseType != NULL)
  9305. {
  9306. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  9307. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  9308. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  9309. }
  9310. if (checkTypeInstance->mIsUnion)
  9311. {
  9312. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9313. if (!unionInnerType->IsValuelessType())
  9314. {
  9315. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  9316. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  9317. }
  9318. if (checkTypeInstance->IsEnum())
  9319. {
  9320. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9321. BfIRValue fieldValue = checkTypeLambda(dscrType);
  9322. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  9323. }
  9324. }
  9325. else
  9326. {
  9327. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9328. {
  9329. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9330. if (fieldInstance->mDataIdx >= 0)
  9331. {
  9332. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  9333. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  9334. }
  9335. }
  9336. }
  9337. return curValue;
  9338. }
  9339. else if (checkType->IsMethodRef())
  9340. {
  9341. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9342. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9343. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9344. {
  9345. BfIRValue fieldValue;
  9346. auto checkType = methodRefType->GetCaptureType(dataIdx);
  9347. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9348. {
  9349. fieldValue = checkTypeLambda(checkType);
  9350. }
  9351. else
  9352. {
  9353. fieldValue = _ExtractValue(checkType);
  9354. }
  9355. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  9356. }
  9357. return curValue;
  9358. }
  9359. else if (!checkType->IsValuelessType())
  9360. {
  9361. return _ExtractValue(checkType);
  9362. }
  9363. return BfIRValue();
  9364. };
  9365. BfIRValue value = checkTypeLambda(typedValue.mType);
  9366. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  9367. }
  9368. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  9369. {
  9370. if (!typedValue.IsSplat())
  9371. return;
  9372. if (typedValue.mType->IsValuelessType())
  9373. return;
  9374. /*static int sCallIdx = 0;
  9375. if (!mCompiler->mIsResolveOnly)
  9376. sCallIdx++;
  9377. int callIdx = sCallIdx;*/
  9378. int elementIdx = 0;
  9379. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  9380. {
  9381. if (checkType->IsStruct())
  9382. {
  9383. auto checkTypeInstance = checkType->ToTypeInstance();
  9384. if (checkTypeInstance->mBaseType != NULL)
  9385. {
  9386. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  9387. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  9388. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  9389. }
  9390. if (checkTypeInstance->mIsUnion)
  9391. {
  9392. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9393. if (!unionInnerType->IsValuelessType())
  9394. {
  9395. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  9396. checkTypeLambda(unionInnerType, fieldAddrVal);
  9397. }
  9398. if (checkTypeInstance->IsEnum())
  9399. {
  9400. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9401. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  9402. checkTypeLambda(dscrType, fieldAddrVal);
  9403. }
  9404. }
  9405. else
  9406. {
  9407. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9408. {
  9409. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9410. if (fieldInstance->mDataIdx >= 0)
  9411. {
  9412. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  9413. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  9414. }
  9415. }
  9416. }
  9417. }
  9418. else if (checkType->IsMethodRef())
  9419. {
  9420. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9421. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9422. {
  9423. auto dataType = methodRefType->GetCaptureType(dataIdx);
  9424. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  9425. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9426. {
  9427. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  9428. }
  9429. else
  9430. {
  9431. // static int sItrCount = 0;
  9432. // sItrCount++;
  9433. // int curItr = sItrCount;
  9434. // if (curItr == 1)
  9435. // {
  9436. // NOP;
  9437. // }
  9438. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  9439. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  9440. }
  9441. }
  9442. }
  9443. else if (!checkType->IsValuelessType())
  9444. {
  9445. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  9446. mBfIRBuilder->CreateStore(val, curAddrVal);
  9447. }
  9448. };
  9449. checkTypeLambda(typedValue.mType, addrVal);
  9450. }
  9451. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  9452. {
  9453. bool wasReadOnly = typedVal.IsReadOnly();
  9454. if ((typedVal.mType->IsValueType()) &&
  9455. (!typedVal.mType->IsValuelessType()))
  9456. {
  9457. wasReadOnly = true; // Any non-addr is implicitly read-only
  9458. //static int gCallIdx = 0;
  9459. if (typedVal.IsAddr())
  9460. return typedVal;
  9461. BfType* type = typedVal.mType;
  9462. PopulateType(type);
  9463. auto tempVar = CreateAlloca(type);
  9464. if (typedVal.IsSplat())
  9465. AggregateSplatIntoAddr(typedVal, tempVar);
  9466. else
  9467. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  9468. return BfTypedValue(tempVar, type,
  9469. typedVal.IsThis() ?
  9470. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  9471. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  9472. }
  9473. return LoadValue(typedVal);
  9474. }
  9475. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  9476. {
  9477. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  9478. typedValue.mKind = BfTypedValueKind_Addr;
  9479. return typedValue;
  9480. }
  9481. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  9482. {
  9483. BfIRValue val;
  9484. if (typedValue.mValue.IsArg())
  9485. {
  9486. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  9487. if (isAddr != NULL)
  9488. {
  9489. if (wantType != NULL)
  9490. *isAddr = wantType->IsComposite();
  9491. else
  9492. *isAddr = false;
  9493. }
  9494. else if (wantType->IsComposite())
  9495. val = mBfIRBuilder->CreateLoad(val);
  9496. }
  9497. if (!val)
  9498. {
  9499. auto checkMethodState = mCurMethodState;
  9500. while (checkMethodState != NULL)
  9501. {
  9502. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  9503. {
  9504. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  9505. if (decompAddr == typedValue.mValue)
  9506. {
  9507. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  9508. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  9509. {
  9510. // This is really backing for a POINTER to a composite inside a methodRef
  9511. val = mBfIRBuilder->CreateLoad(val);
  9512. }
  9513. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  9514. {
  9515. *isAddr = true;
  9516. return val;
  9517. }
  9518. else
  9519. {
  9520. val = mBfIRBuilder->CreateLoad(val);
  9521. break;
  9522. }
  9523. }
  9524. }
  9525. if (val)
  9526. break;
  9527. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  9528. {
  9529. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  9530. return mBfIRBuilder->GetFakeVal();
  9531. }
  9532. checkMethodState = checkMethodState->mPrevMethodState;
  9533. }
  9534. }
  9535. if (val)
  9536. {
  9537. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  9538. {
  9539. BF_ASSERT(wantType != NULL);
  9540. if (wantType != NULL)
  9541. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  9542. }
  9543. return val;
  9544. }
  9545. BFMODULE_FATAL(this, "Splat not found");
  9546. return BfIRValue();
  9547. }
  9548. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  9549. {
  9550. int useFieldIdx = fieldIdx;
  9551. BfType* fieldType = NULL;
  9552. if (fieldInstance != NULL)
  9553. {
  9554. fieldType = fieldInstance->mResolvedType;
  9555. if (typedValue.mType->IsUnion())
  9556. {
  9557. if (fieldIdx == 1)
  9558. {
  9559. if (typedValue.IsSplat())
  9560. {
  9561. BfTypedValue innerVal = typedValue;
  9562. innerVal.mType = fieldType;
  9563. return innerVal;
  9564. }
  9565. }
  9566. }
  9567. }
  9568. else
  9569. {
  9570. if (typedValue.mType->IsPayloadEnum())
  9571. {
  9572. auto typeInst = typedValue.mType->ToTypeInstance();
  9573. if (fieldIdx == 1)
  9574. fieldType = typeInst->GetUnionInnerType();
  9575. else if (fieldIdx == 2)
  9576. {
  9577. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9578. }
  9579. }
  9580. else if (typedValue.mType->IsUnion())
  9581. {
  9582. if (fieldIdx == 1)
  9583. {
  9584. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9585. if (typedValue.IsSplat())
  9586. {
  9587. BfTypedValue innerVal = typedValue;
  9588. innerVal.mType = fieldType;
  9589. return innerVal;
  9590. }
  9591. }
  9592. }
  9593. }
  9594. BF_ASSERT(typedValue.mType->IsStruct());
  9595. if (typedValue.IsSplat())
  9596. {
  9597. if (typedValue.mType->IsPayloadEnum())
  9598. {
  9599. if (fieldIdx == 1)
  9600. {
  9601. // Payload
  9602. auto typeInst = typedValue.mType->ToTypeInstance();
  9603. auto unionInnerType = typeInst->GetUnionInnerType();
  9604. bool isAddr = false;
  9605. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  9606. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  9607. }
  9608. if (fieldIdx == 2)
  9609. {
  9610. // Discriminator
  9611. auto typeInst = typedValue.mType->ToTypeInstance();
  9612. auto unionInnerType = typeInst->GetUnionInnerType();
  9613. auto dscrType = typeInst->GetDiscriminatorType();
  9614. int argIdx = typedValue.mValue.mId;
  9615. int componentIdx = 0;
  9616. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  9617. bool isAddr;
  9618. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  9619. return BfTypedValue(irVal, dscrType, isAddr);
  9620. }
  9621. }
  9622. int componentIdx = 0;
  9623. BfTypedValue retVal;
  9624. BfFieldInstance* wantFieldInstance = fieldInstance;
  9625. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9626. {
  9627. if (checkType->IsStruct())
  9628. {
  9629. auto checkTypeInstance = checkType->ToTypeInstance();
  9630. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  9631. {
  9632. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  9633. fieldType = checkTypeInstance->GetUnionInnerType();
  9634. checkTypeLambda(fieldType);
  9635. if (checkType->IsEnum())
  9636. {
  9637. // Past discriminator...
  9638. componentIdx++;
  9639. }
  9640. return;
  9641. }
  9642. if (checkTypeInstance->mBaseType != NULL)
  9643. checkTypeLambda(checkTypeInstance->mBaseType);
  9644. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9645. {
  9646. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9647. if (fieldInstance == wantFieldInstance)
  9648. {
  9649. bool isAddr = false;
  9650. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  9651. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  9652. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  9653. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  9654. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  9655. {
  9656. retVal = LoadValue(retVal);
  9657. }
  9658. break;
  9659. }
  9660. if (fieldInstance->mDataIdx >= 0)
  9661. checkTypeLambda(fieldInstance->GetResolvedType());
  9662. }
  9663. }
  9664. else if (!checkType->IsValuelessType())
  9665. {
  9666. componentIdx++;
  9667. //argIdx++;
  9668. }
  9669. };
  9670. checkTypeLambda(typedValue.mType);
  9671. BF_ASSERT(retVal);
  9672. return retVal;
  9673. }
  9674. if (typedValue.IsAddr())
  9675. {
  9676. BF_ASSERT(fieldType != NULL);
  9677. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  9678. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  9679. }
  9680. else
  9681. {
  9682. BF_ASSERT(fieldType != NULL);
  9683. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  9684. }
  9685. }
  9686. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  9687. {
  9688. if (typedValue.IsAddr())
  9689. {
  9690. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  9691. return mBfIRBuilder->CreateLoad(addrVal);
  9692. }
  9693. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  9694. }
  9695. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  9696. {
  9697. if (elementType->IsSizeAligned())
  9698. {
  9699. if (isElementIndex)
  9700. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  9701. else
  9702. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9703. }
  9704. auto ptrType = CreatePointerType(elementType);
  9705. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  9706. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  9707. auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  9708. BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  9709. BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  9710. return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  9711. }
  9712. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  9713. {
  9714. if (elementType->IsSizeAligned())
  9715. {
  9716. if (isElementIndex)
  9717. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9718. else
  9719. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9720. }
  9721. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9722. }
  9723. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9724. {
  9725. if (modifyType == NULL)
  9726. modifyType = "modify";
  9727. if (typedValue.mType->IsVar())
  9728. return true;
  9729. if (typedValue.IsReadOnly())
  9730. {
  9731. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9732. return false;
  9733. }
  9734. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9735. {
  9736. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9737. return false;
  9738. }
  9739. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  9740. {
  9741. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  9742. return false;
  9743. }
  9744. return true;
  9745. }
  9746. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9747. {
  9748. // If one is an interface and the other is an impl, B is the impl
  9749. auto implOwner = methodB->GetOwner();
  9750. if (methodA->mMethodDef->mIsLocalMethod)
  9751. {
  9752. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9753. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9754. if (sepPosA != sepPosB)
  9755. return false;
  9756. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9757. return false;
  9758. }
  9759. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9760. return false;
  9761. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9762. return false;
  9763. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9764. {
  9765. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9766. return false;
  9767. }
  9768. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9769. {
  9770. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9771. return false;
  9772. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9773. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9774. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9775. return false;
  9776. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9777. return false;
  9778. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  9779. return false;
  9780. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9781. {
  9782. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  9783. return false;
  9784. }
  9785. }
  9786. int implicitParamCountA = methodA->GetImplicitParamCount();
  9787. int implicitParamCountB = methodB->GetImplicitParamCount();
  9788. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9789. return false;
  9790. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9791. return false;
  9792. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9793. {
  9794. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  9795. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9796. return false;
  9797. }
  9798. // Compare generic params. Generic params are part of the method signature here
  9799. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9800. return false;
  9801. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9802. {
  9803. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9804. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9805. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9806. return false;
  9807. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9808. return false;
  9809. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9810. return false;
  9811. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9812. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9813. return false;
  9814. }
  9815. return true;
  9816. }
  9817. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9818. {
  9819. if (!CompareMethodSignatures(methodA, methodB))
  9820. return false;
  9821. if (methodA->mReturnType != methodB->mReturnType)
  9822. return false;
  9823. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9824. return false;
  9825. return true;
  9826. }
  9827. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9828. {
  9829. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9830. return false;
  9831. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9832. return false;
  9833. if (iMethodInst->mMethodDef->mIsOperator)
  9834. {
  9835. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9836. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9837. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9838. return false;
  9839. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9840. return false;
  9841. }
  9842. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9843. return false;
  9844. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9845. {
  9846. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9847. return false;
  9848. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9849. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9850. if (iParamType->IsSelf())
  9851. {
  9852. if (methodParamType != methodInstance->GetOwner())
  9853. return false;
  9854. }
  9855. else if (!iParamType->IsGenericParam())
  9856. {
  9857. if (methodParamType != iParamType)
  9858. return false;
  9859. }
  9860. else
  9861. {
  9862. if (!methodParamType->IsGenericParam())
  9863. return false;
  9864. auto genericParamType = (BfGenericParamType*)methodParamType;
  9865. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9866. return false;
  9867. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9868. bool hadInterface = false;
  9869. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9870. if (interfaceConstraint == iParamType)
  9871. hadInterface = true;
  9872. if (!hadInterface)
  9873. return false;
  9874. }
  9875. }
  9876. return true;
  9877. }
  9878. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9879. {
  9880. BfMethodInstance* methodInstance = methodRef;
  9881. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9882. {
  9883. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9884. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9885. {
  9886. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9887. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  9888. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  9889. BfMethodRef methodRef = methodInstance;
  9890. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9891. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9892. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9893. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9894. (mIsReified))
  9895. {
  9896. specializedMethodRefInfo->mHasReifiedRef = true;
  9897. }
  9898. }
  9899. }
  9900. }
  9901. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9902. {
  9903. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9904. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9905. if (mBfIRBuilder == NULL)
  9906. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9907. if (methodInstance->GetOwner()->IsFunction())
  9908. {
  9909. // No actual ref needed- not an actual generated function
  9910. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9911. }
  9912. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9913. if (!isGenFunction)
  9914. AddMethodReference(methodInstance, flags);
  9915. if (mBfIRBuilder->mIgnoreWrites)
  9916. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9917. if (mCompiler->IsSkippingExtraResolveChecks())
  9918. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9919. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9920. {
  9921. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9922. }
  9923. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9924. BfMethodRef methodRef = methodInstance;
  9925. if (isInlined)
  9926. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9927. else
  9928. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9929. if (!isGenFunction)
  9930. {
  9931. BfIRValue* irFuncPtr = NULL;
  9932. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9933. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9934. }
  9935. if (mAwaitingInitFinish)
  9936. FinishInit();
  9937. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9938. if (!isGenFunction)
  9939. mFuncReferences[methodRef] = func;
  9940. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9941. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  9942. {
  9943. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9944. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9945. // type instance
  9946. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9947. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9948. for (auto ownedTypeInst : mOwnedTypeInstances)
  9949. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9950. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9951. {
  9952. mIncompleteMethodCount++;
  9953. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9954. inlineMethodRequest->mType = methodInstance->GetOwner();
  9955. inlineMethodRequest->mFromModule = this;
  9956. inlineMethodRequest->mFunc = func;
  9957. inlineMethodRequest->mFromModuleRevision = mRevision;
  9958. inlineMethodRequest->mMethodInstance = methodInstance;
  9959. BF_ASSERT(mIsModuleMutable);
  9960. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9961. }
  9962. }
  9963. return BfModuleMethodInstance(methodInstance, func);
  9964. }
  9965. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9966. {
  9967. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9968. if (mBfIRBuilder == NULL)
  9969. {
  9970. // To allow for custom attribute data
  9971. PrepareForIRWriting(typeInst);
  9972. }
  9973. BfModule* declareModule = this;
  9974. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9975. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9976. declareModule = declareModule->mParentModule;
  9977. // Check for attributes
  9978. if (typeInst == mContext->mBfObjectType)
  9979. {
  9980. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9981. if (methodDecl != NULL)
  9982. {
  9983. auto attributesDirective = methodDecl->mAttributes;
  9984. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9985. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9986. {
  9987. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9988. }
  9989. }
  9990. }
  9991. else
  9992. {
  9993. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9994. GetMethodCustomAttributes(methodInstance);
  9995. }
  9996. BF_ASSERT(mModuleOptions == NULL);
  9997. if (methodInstance->GetCustomAttributes() != NULL)
  9998. {
  9999. auto project = typeInst->mTypeDef->mProject;
  10000. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  10001. BfModuleOptions wantOptions = moduleOptions;
  10002. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  10003. if (typeOptions != NULL)
  10004. {
  10005. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  10006. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  10007. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  10008. }
  10009. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  10010. {
  10011. StringT<128> attrName;
  10012. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  10013. {
  10014. attrName.Clear();
  10015. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  10016. Array<int>* arrPtr;
  10017. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  10018. {
  10019. for (auto optionsIdx : *arrPtr)
  10020. {
  10021. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  10022. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  10023. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  10024. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  10025. }
  10026. }
  10027. }
  10028. }
  10029. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  10030. {
  10031. auto lastCheckModule = this;
  10032. auto checkModule = this->mNextAltModule;
  10033. while (checkModule != NULL)
  10034. {
  10035. if (*checkModule->mModuleOptions == wantOptions)
  10036. {
  10037. declareModule = checkModule;
  10038. break;
  10039. }
  10040. lastCheckModule = checkModule;
  10041. checkModule = checkModule->mNextAltModule;
  10042. }
  10043. // Not found?
  10044. if (declareModule == this)
  10045. {
  10046. String specModuleName = mModuleName + "@@";
  10047. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  10048. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  10049. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  10050. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  10051. declareModule = new BfModule(mContext, specModuleName);
  10052. declareModule->mProject = project;
  10053. declareModule->mModuleOptions = new BfModuleOptions();
  10054. *declareModule->mModuleOptions = wantOptions;
  10055. declareModule->mParentModule = lastCheckModule;
  10056. declareModule->Init();
  10057. lastCheckModule->mNextAltModule = declareModule;
  10058. }
  10059. }
  10060. }
  10061. declareModule->PrepareForIRWriting(typeInst);
  10062. return declareModule;
  10063. }
  10064. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  10065. {
  10066. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  10067. {
  10068. // Don't bother inlining for resolve-only
  10069. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10070. }
  10071. bool processNow = false;
  10072. bool keepInCurrentModule = false;
  10073. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  10074. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  10075. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  10076. {
  10077. return BfModuleMethodInstance();
  10078. }
  10079. if (methodDef->mIsLocalMethod)
  10080. {
  10081. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10082. BfLocalMethod* localMethod;
  10083. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  10084. {
  10085. // Handle the def in the correct method state
  10086. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  10087. }
  10088. BFMODULE_FATAL(this, "Cannot find local method");
  10089. return BfModuleMethodInstance();
  10090. }
  10091. #ifdef _DEBUG
  10092. for (auto arg : methodGenericArguments)
  10093. BF_ASSERT(!arg->IsVar());
  10094. #endif
  10095. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  10096. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  10097. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  10098. // a FinishInit
  10099. if ((typeInst->IsIncomplete()) &&
  10100. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  10101. {
  10102. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  10103. // for resolve-only because we don't differentiate between reified/unreified there
  10104. PopulateType(typeInst, BfPopulateType_Full);
  10105. }
  10106. bool tryModuleMethodLookup = false;
  10107. BfModuleMethodInstance moduleMethodInst;
  10108. BfModule* instModule = typeInst->mModule;
  10109. if (keepInCurrentModule)
  10110. {
  10111. // Stay here
  10112. instModule = this;
  10113. }
  10114. if (this == mContext->mUnreifiedModule)
  10115. {
  10116. // Stay in this 'resolve only' module here
  10117. }
  10118. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  10119. {
  10120. BF_ASSERT(this == mContext->mUnreifiedModule);
  10121. }
  10122. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  10123. {
  10124. BF_ASSERT(instModule == mParentModule);
  10125. }
  10126. else if (instModule != this)
  10127. {
  10128. if ((!mIsReified) && (instModule->mIsReified))
  10129. {
  10130. BF_ASSERT(!mCompiler->mIsResolveOnly);
  10131. // A resolve-only module is specializing a method from a type in a reified module,
  10132. // we need to take care that this doesn't cause anything new to become reified
  10133. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  10134. }
  10135. else
  10136. {
  10137. if ((mIsReified) && (!instModule->mIsReified))
  10138. {
  10139. if (!typeInst->IsUnspecializedTypeVariation())
  10140. {
  10141. if (!instModule->mReifyQueued)
  10142. {
  10143. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  10144. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  10145. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  10146. mContext->mReifyModuleWorkList.Add(instModule);
  10147. instModule->mReifyQueued = true;
  10148. }
  10149. // This ensures that the method will actually be created when it gets reified
  10150. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  10151. specializationRequest->mFromModule = typeInst->mModule;
  10152. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  10153. specializationRequest->mMethodDef = methodDef;
  10154. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  10155. specializationRequest->mType = typeInst;
  10156. specializationRequest->mFlags = flags;
  10157. }
  10158. }
  10159. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10160. // Not extern
  10161. // Create the instance in the proper module and then create a reference in this one
  10162. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  10163. tryModuleMethodLookup = true;
  10164. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  10165. {
  10166. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  10167. }
  10168. }
  10169. }
  10170. if (tryModuleMethodLookup)
  10171. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  10172. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  10173. {
  10174. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  10175. if (moduleMethodInstance)
  10176. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  10177. return moduleMethodInst;
  10178. }
  10179. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  10180. bool hadConcreteInterfaceGenericArgument = false;
  10181. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  10182. isReified = false;
  10183. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  10184. {
  10185. isReified = false;
  10186. }
  10187. BfTypeVector sanitizedMethodGenericArguments;
  10188. SizedArray<BfProject*, 4> projectList;
  10189. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  10190. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  10191. isUnspecializedPass = false;
  10192. // 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
  10193. bool isExternalExtensionMethod = false;
  10194. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  10195. {
  10196. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  10197. {
  10198. auto specProject = methodDef->mDeclaringType->mProject;
  10199. isExternalExtensionMethod = true;
  10200. if (typeInst->IsGenericTypeInstance())
  10201. {
  10202. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10203. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10204. genericTypeInst->GenerateProjectsReferenced();
  10205. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  10206. {
  10207. // This is a generic type where a generic param is already confined to the project in question
  10208. isExternalExtensionMethod = false;
  10209. }
  10210. }
  10211. if (isExternalExtensionMethod)
  10212. {
  10213. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  10214. projectList.push_back(methodDef->mDeclaringType->mProject);
  10215. }
  10216. }
  10217. }
  10218. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  10219. {
  10220. int typeProjectsCounts = 0;
  10221. if (typeInst->IsGenericTypeInstance())
  10222. {
  10223. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10224. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10225. genericTypeInst->GenerateProjectsReferenced();
  10226. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  10227. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  10228. }
  10229. else
  10230. {
  10231. typeProjectsCounts = 1;
  10232. projectList.Insert(0, typeInst->mTypeDef->mProject);
  10233. }
  10234. isUnspecializedPass = true;
  10235. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  10236. {
  10237. auto genericArgType = methodGenericArguments[genericArgIdx];
  10238. //BF_ASSERT(!genericArgType->IsRef());
  10239. if (genericArgType->IsConcreteInterfaceType())
  10240. {
  10241. hadConcreteInterfaceGenericArgument = true;
  10242. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  10243. genericArgType = concreteInterfaceType->mInterface;
  10244. }
  10245. if (genericArgType->IsGenericParam())
  10246. {
  10247. auto genericParam = (BfGenericParamType*) genericArgType;
  10248. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  10249. isUnspecializedPass = false;
  10250. }
  10251. else
  10252. {
  10253. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  10254. isUnspecializedPass = false;
  10255. }
  10256. sanitizedMethodGenericArguments.push_back(genericArgType);
  10257. }
  10258. if ((int)projectList.size() > typeProjectsCounts)
  10259. {
  10260. // Just leave the new items
  10261. projectList.RemoveRange(0, typeProjectsCounts);
  10262. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  10263. {
  10264. return lhs->mName < rhs->mName;
  10265. });
  10266. }
  10267. else
  10268. {
  10269. projectList.Clear();
  10270. }
  10271. }
  10272. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  10273. BfMethodInstanceGroup* methodInstGroup = NULL;
  10274. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10275. {
  10276. BF_ASSERT(!typeInst->IsInterface());
  10277. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  10278. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  10279. {
  10280. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  10281. // if (checkGroup.mDefault == NULL)
  10282. // {
  10283. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  10284. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  10285. // methodInstGroup = &checkGroup;
  10286. // break;
  10287. // }
  10288. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  10289. {
  10290. methodInstGroup = &checkGroup;
  10291. break;
  10292. }
  10293. }
  10294. if (methodInstGroup == NULL)
  10295. {
  10296. // Allocate a new entry
  10297. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  10298. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  10299. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  10300. methodInstGroup->mOwner = typeInst;
  10301. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10302. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10303. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  10304. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10305. else
  10306. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  10307. }
  10308. }
  10309. else
  10310. {
  10311. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  10312. }
  10313. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10314. {
  10315. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  10316. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10317. }
  10318. BfIRFunction prevIRFunc;
  10319. bool doingRedeclare = false;
  10320. BfMethodInstance* methodInstance = NULL;
  10321. auto _SetReified = [&]()
  10322. {
  10323. methodInstance->mIsReified = true;
  10324. };
  10325. if (lookupMethodGenericArguments.size() == 0)
  10326. {
  10327. methodInstance = methodInstGroup->mDefault;
  10328. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  10329. {
  10330. MarkDerivedDirty(typeInst);
  10331. if (mIsScratchModule)
  10332. {
  10333. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  10334. _SetReified();
  10335. CheckHotMethod(methodInstance, "");
  10336. }
  10337. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  10338. {
  10339. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  10340. // the specializations to handle that for us
  10341. return BfModuleMethodInstance(methodInstance);
  10342. }
  10343. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  10344. {
  10345. if (methodDef->mIsAbstract)
  10346. {
  10347. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10348. _SetReified();
  10349. }
  10350. else
  10351. {
  10352. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10353. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  10354. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  10355. doingRedeclare = true;
  10356. mOnDemandMethodCount++;
  10357. }
  10358. }
  10359. else
  10360. {
  10361. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  10362. // We haven't processed it yet
  10363. _SetReified();
  10364. CheckHotMethod(methodInstance, "");
  10365. if (methodInstance->mDeclModule == this)
  10366. {
  10367. if (methodInstance->mMethodProcessRequest != NULL)
  10368. {
  10369. // Disconnect method process request
  10370. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  10371. }
  10372. }
  10373. else
  10374. {
  10375. if (methodInstance->mMethodProcessRequest != NULL)
  10376. {
  10377. // Disconnect method process request
  10378. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  10379. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  10380. methodInstance->mMethodProcessRequest = NULL;
  10381. }
  10382. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  10383. {
  10384. // Add new request in proper module
  10385. methodInstance->mDeclModule = this;
  10386. }
  10387. else
  10388. {
  10389. if (methodInstance->mDeclModule == NULL)
  10390. {
  10391. //
  10392. }
  10393. else if (methodInstance->mDeclModule != this)
  10394. {
  10395. // Is from specialized module?
  10396. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  10397. }
  10398. }
  10399. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10400. {
  10401. methodInstance->mIRFunction = BfIRFunction();
  10402. if (!mIsModuleMutable)
  10403. StartExtension();
  10404. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  10405. {
  10406. StringT<128> mangledName;
  10407. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  10408. bool isIntrinsic = false;
  10409. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  10410. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  10411. }
  10412. }
  10413. AddMethodToWorkList(methodInstance);
  10414. }
  10415. }
  10416. }
  10417. }
  10418. else
  10419. {
  10420. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  10421. if (methodInstGroup->mMethodSpecializationMap == NULL)
  10422. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  10423. BfMethodInstance** methodInstancePtr = NULL;
  10424. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  10425. {
  10426. methodInstance = *methodInstancePtr;
  10427. if ((isReified) && (!methodInstance->mIsReified))
  10428. {
  10429. MarkDerivedDirty(typeInst);
  10430. if (methodInstance->mHasBeenProcessed)
  10431. {
  10432. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  10433. delete methodInstance;
  10434. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10435. methodInstance = NULL;
  10436. }
  10437. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10438. {
  10439. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  10440. delete methodInstance;
  10441. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10442. methodInstance = NULL;
  10443. }
  10444. else
  10445. {
  10446. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  10447. // We haven't processed it yet
  10448. _SetReified();
  10449. CheckHotMethod(methodInstance, "");
  10450. }
  10451. }
  10452. }
  10453. }
  10454. if ((methodInstance != NULL) && (!doingRedeclare))
  10455. {
  10456. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  10457. {
  10458. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  10459. BF_ASSERT(!methodInstance->mIsReified);*/
  10460. if (methodInstance->mIsReified != isReified)
  10461. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  10462. if ((!isReified) &&
  10463. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  10464. {
  10465. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  10466. methodInstance->mIRFunction = BfIRFunction();
  10467. }
  10468. methodInstance->mIsReified = isReified;
  10469. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  10470. {
  10471. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  10472. }
  10473. if (!methodInstance->mMethodDef->mIsAbstract)
  10474. {
  10475. AddMethodToWorkList(methodInstance);
  10476. }
  10477. else
  10478. {
  10479. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  10480. }
  10481. }
  10482. if (mExtensionCount > 0)
  10483. {
  10484. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  10485. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  10486. {
  10487. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  10488. if (mAwaitingInitFinish)
  10489. FinishInit();
  10490. // We need to refer to a function that was defined in a prior module
  10491. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10492. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  10493. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  10494. methodInstance->mDeclModule = this;
  10495. // Add this inlined def to ourselves
  10496. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  10497. {
  10498. mIncompleteMethodCount++;
  10499. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10500. inlineMethodRequest->mType = typeInst;
  10501. inlineMethodRequest->mFromModule = this;
  10502. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  10503. inlineMethodRequest->mFromModuleRevision = mRevision;
  10504. inlineMethodRequest->mMethodInstance = methodInstance;
  10505. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10506. BF_ASSERT(mIsModuleMutable);
  10507. }
  10508. }
  10509. }
  10510. if (mCompiler->IsSkippingExtraResolveChecks())
  10511. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10512. else
  10513. {
  10514. if (methodInstance->mDeclModule != this)
  10515. return ReferenceExternalMethodInstance(methodInstance, flags);
  10516. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  10517. {
  10518. auto importKind = methodInstance->GetImportCallKind();
  10519. if (importKind != BfImportCallKind_None)
  10520. {
  10521. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  10522. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  10523. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  10524. }
  10525. }
  10526. return BfModuleMethodInstance(methodInstance);
  10527. }
  10528. }
  10529. if (!doingRedeclare)
  10530. {
  10531. BfModule* specModule = NULL;
  10532. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  10533. {
  10534. specModule = GetSpecializedMethodModule(projectList);
  10535. }
  10536. if ((specModule != NULL) && (specModule != this))
  10537. {
  10538. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  10539. if (mAwaitingInitFinish)
  10540. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  10541. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  10542. }
  10543. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  10544. {
  10545. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  10546. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  10547. }
  10548. }
  10549. if (methodInstance == NULL)
  10550. {
  10551. if (lookupMethodGenericArguments.size() == 0)
  10552. {
  10553. BF_ASSERT(methodInstGroup->mDefault == NULL);
  10554. methodInstance = new BfMethodInstance();
  10555. methodInstGroup->mDefault = methodInstance;
  10556. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  10557. }
  10558. else
  10559. {
  10560. BfMethodInstance** methodInstancePtr = NULL;
  10561. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  10562. BF_ASSERT(added);
  10563. methodInstance = new BfMethodInstance();
  10564. *methodInstancePtr = methodInstance;
  10565. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  10566. }
  10567. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  10568. methodInstance->mIRFunction = prevIRFunc; // Take it over
  10569. }
  10570. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  10571. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  10572. if (methodInstGroup->mMethodSpecializationMap != NULL)
  10573. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  10574. methodInstance->mMethodDef = methodDef;
  10575. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  10576. methodInstance->mMethodInstanceGroup = methodInstGroup;
  10577. methodInstance->mIsReified = isReified;
  10578. SetupMethodIdHash(methodInstance);
  10579. if (hadConcreteInterfaceGenericArgument)
  10580. methodInstance->mIgnoreBody = true;
  10581. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10582. {
  10583. methodInstance->mIsForeignMethodDef = true;
  10584. BF_ASSERT(foreignType != NULL);
  10585. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  10586. }
  10587. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  10588. {
  10589. if (!lookupMethodGenericArguments.empty())
  10590. {
  10591. auto compareType = lookupMethodGenericArguments[0];
  10592. PopulateType(compareType, BfPopulateType_Data);
  10593. if (compareType->IsSplattable())
  10594. methodInstance->mAlwaysInline = true;
  10595. }
  10596. }
  10597. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  10598. {
  10599. // With extensions we can have multiple definitions of the same method
  10600. //methodInstance->mMangleWithIdx = true;
  10601. }
  10602. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  10603. BF_ASSERT(typeInst == methodInstance->GetOwner());
  10604. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10605. if (isUnspecializedPass)
  10606. {
  10607. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  10608. {
  10609. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  10610. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  10611. }
  10612. }
  10613. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  10614. {
  10615. if (!sanitizedMethodGenericArguments.IsEmpty())
  10616. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  10617. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  10618. {
  10619. Fail("Internal error");
  10620. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  10621. return NULL;
  10622. }
  10623. for (auto genericArg : sanitizedMethodGenericArguments)
  10624. {
  10625. if (genericArg->IsPrimitiveType())
  10626. genericArg = GetWrappedStructType(genericArg);
  10627. if (genericArg != NULL)
  10628. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  10629. }
  10630. }
  10631. // Generic constraints
  10632. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  10633. {
  10634. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  10635. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10636. }
  10637. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  10638. {
  10639. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  10640. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10641. }
  10642. bool addToWorkList = !processNow;
  10643. if (mCompiler->GetAutoComplete() != NULL)
  10644. {
  10645. if (typeInst->IsSpecializedByAutoCompleteMethod())
  10646. addToWorkList = false;
  10647. }
  10648. BF_ASSERT(declareModule != NULL);
  10649. methodInstance->mDeclModule = declareModule;
  10650. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  10651. {
  10652. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  10653. // of a reified module -
  10654. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  10655. // BUT if we don't reify it then we have to remove the body after processing.
  10656. // 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
  10657. // the proper reified module.
  10658. declareModule = mContext->mUnreifiedModule;
  10659. }
  10660. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  10661. {
  10662. BF_ASSERT(!methodInstance->mIsReified);
  10663. declareModule = mContext->mUnreifiedModule;
  10664. }
  10665. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  10666. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  10667. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  10668. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  10669. {
  10670. // For mixins we only process the unspecialized version
  10671. addToWorkList = false;
  10672. }
  10673. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  10674. if (processNow)
  10675. {
  10676. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  10677. ProcessMethod(methodInstance);
  10678. }
  10679. if (mCompiler->IsSkippingExtraResolveChecks())
  10680. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10681. return BfModuleMethodInstance(methodInstance);
  10682. }
  10683. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10684. {
  10685. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  10686. if (methodInstance->mIsForeignMethodDef)
  10687. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10688. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  10689. }
  10690. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  10691. {
  10692. if (!methodInstance->mMethodDef->mIsLocalMethod)
  10693. return NULL;
  10694. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  10695. if (outerLocal == NULL)
  10696. return NULL;
  10697. BfTypeVector genericArgs;
  10698. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  10699. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  10700. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  10701. }
  10702. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  10703. {
  10704. HashContext hashCtx;
  10705. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  10706. {
  10707. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  10708. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  10709. if (methodInstance->GetNumGenericArguments() != 0)
  10710. {
  10711. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  10712. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  10713. hashCtx.Mixin(methodGenericArg->mTypeId);
  10714. }
  10715. };
  10716. _MixinMethodInstance(methodInstance);
  10717. if (methodInstance->mMethodDef->mIsLocalMethod)
  10718. {
  10719. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  10720. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  10721. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  10722. }
  10723. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  10724. }
  10725. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  10726. {
  10727. BfIRValue globalValue;
  10728. BfIRValue* globalValuePtr = NULL;
  10729. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  10730. {
  10731. globalValue = *globalValuePtr;
  10732. }
  10733. if (!globalValue)
  10734. {
  10735. // This is necessary to reify the interface type
  10736. PopulateType(ifaceType);
  10737. StringT<128> slotVarName;
  10738. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  10739. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  10740. BfIRValue value;
  10741. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  10742. {
  10743. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10744. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10745. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10746. value = GetConstValue32(virtSlotIdx);*/
  10747. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10748. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10749. }
  10750. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10751. mInterfaceSlotRefs[ifaceType] = globalValue;
  10752. }
  10753. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10754. }
  10755. void BfModule::HadSlotCountDependency()
  10756. {
  10757. if (mCompiler->mIsResolveOnly)
  10758. return;
  10759. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10760. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10761. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10762. }
  10763. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10764. {
  10765. if (mIsScratchModule)
  10766. {
  10767. // Just fake it for the extern and unspecialized modules
  10768. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10769. return BfTypedValue(mBfIRBuilder->GetFakeVal(), fieldInstance->GetResolvedType(), true);
  10770. }
  10771. BfIRValue globalValue;
  10772. auto fieldDef = fieldInstance->GetFieldDef();
  10773. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10774. {
  10775. if (fieldInstance->mConstIdx != -1)
  10776. {
  10777. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10778. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10779. }
  10780. else
  10781. {
  10782. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10783. }
  10784. }
  10785. BfIRValue* globalValuePtr = NULL;
  10786. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10787. {
  10788. globalValue = *globalValuePtr;
  10789. BF_ASSERT(globalValue);
  10790. }
  10791. else
  10792. {
  10793. StringT<128> staticVarName;
  10794. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10795. auto typeType = fieldInstance->GetResolvedType();
  10796. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10797. {
  10798. typeType = typeType->GetUnderlyingType();
  10799. }
  10800. PopulateType(typeType);
  10801. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10802. {
  10803. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10804. mBfIRBuilder->MapType(typeType),
  10805. false,
  10806. BfIRLinkageType_External,
  10807. BfIRValue(),
  10808. staticVarName,
  10809. IsThreadLocal(fieldInstance));
  10810. if (!mBfIRBuilder->mIgnoreWrites)
  10811. {
  10812. // Only store this if we actually did the creation
  10813. BF_ASSERT(globalValue);
  10814. mStaticFieldRefs[fieldInstance] = globalValue;
  10815. }
  10816. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10817. }
  10818. }
  10819. auto type = fieldInstance->GetResolvedType();
  10820. if (type->IsValuelessType())
  10821. return BfTypedValue(globalValue, type);
  10822. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10823. }
  10824. BfTypedValue BfModule::GetThis()
  10825. {
  10826. auto useMethodState = mCurMethodState;
  10827. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10828. {
  10829. useMethodState = useMethodState->mPrevMethodState;
  10830. }
  10831. if (useMethodState != NULL)
  10832. {
  10833. // Fake a 'this' for var field resolution
  10834. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10835. {
  10836. auto thisType = mCurTypeInstance;
  10837. if (thisType->IsValueType())
  10838. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10839. else
  10840. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10841. }
  10842. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10843. {
  10844. return BfTypedValue();
  10845. }
  10846. }
  10847. else
  10848. {
  10849. //TODO: Do we allow useMethodState to be NULL anymore?
  10850. return BfTypedValue();
  10851. }
  10852. // if (useMethodState->HasNonStaticMixin())
  10853. // {
  10854. // auto checkMethodState = useMethodState;
  10855. // while (checkMethodState != NULL)
  10856. // {
  10857. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10858. // {
  10859. // auto varDecl = checkMethodState->mLocals[localIdx];
  10860. // if (varDecl->mName == "this")
  10861. // {
  10862. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10863. // if (varDecl->mIsSplat)
  10864. // {
  10865. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10866. // }
  10867. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10868. // {
  10869. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10870. // }
  10871. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10872. // }
  10873. // }
  10874. //
  10875. // checkMethodState = checkMethodState->mPrevMethodState;
  10876. // }
  10877. // }
  10878. // Check mixin state for 'this'
  10879. {
  10880. auto checkMethodState = useMethodState;
  10881. while (checkMethodState != NULL)
  10882. {
  10883. if (checkMethodState->mMixinState != NULL)
  10884. {
  10885. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10886. if (thisValue.HasType())
  10887. {
  10888. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10889. if (!thisValue.mType->IsValueType())
  10890. thisValue = LoadValue(thisValue);
  10891. return thisValue;
  10892. }
  10893. }
  10894. checkMethodState = checkMethodState->mPrevMethodState;
  10895. }
  10896. }
  10897. auto curMethodInstance = mCurMethodInstance;
  10898. if (useMethodState->mMethodInstance != NULL)
  10899. curMethodInstance = useMethodState->mMethodInstance;
  10900. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10901. {
  10902. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10903. {
  10904. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10905. if (constLocal.mIsThis)
  10906. {
  10907. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10908. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10909. }
  10910. }
  10911. return BfTypedValue();
  10912. }
  10913. if (useMethodState->mLocals.IsEmpty())
  10914. {
  10915. // 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
  10916. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10917. return BfTypedValue();
  10918. }
  10919. auto thisLocal = useMethodState->mLocals[0];
  10920. BF_ASSERT(thisLocal->mIsThis);
  10921. bool preferValue = !IsTargetingBeefBackend();
  10922. if (!thisLocal->mAddr)
  10923. preferValue = true;
  10924. bool usedVal = false;
  10925. BfIRValue thisValue;
  10926. if ((preferValue) && (!thisLocal->mIsLowered))
  10927. {
  10928. thisValue = thisLocal->mValue;
  10929. usedVal = true;
  10930. }
  10931. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10932. thisValue = thisLocal->mAddr;
  10933. else
  10934. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10935. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10936. if (useMethodState->mClosureState != NULL)
  10937. {
  10938. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10939. if (closureTypeInst != NULL)
  10940. {
  10941. if (closureTypeInst->mFieldInstances.size() > 0)
  10942. {
  10943. auto& field = closureTypeInst->mFieldInstances[0];
  10944. auto fieldDef = field.GetFieldDef();
  10945. if (fieldDef->mName == "__this")
  10946. {
  10947. if (mCurMethodState->mClosureState->mCapturing)
  10948. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10949. // This is a captured 'this'
  10950. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10951. if (field.mResolvedType->IsRef())
  10952. {
  10953. auto refType = (BfRefType*)field.mResolvedType;
  10954. auto underlyingType = refType->GetUnderlyingType();
  10955. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10956. }
  10957. if (field.mResolvedType->IsObject())
  10958. {
  10959. result = LoadValue(result);
  10960. result.mKind = BfTypedValueKind_ThisValue;
  10961. }
  10962. else
  10963. {
  10964. if (fieldDef->mIsReadOnly)
  10965. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10966. else
  10967. result.mKind = BfTypedValueKind_ThisAddr;
  10968. }
  10969. return result;
  10970. }
  10971. }
  10972. return BfTypedValue();
  10973. }
  10974. if (useMethodState->mClosureState->mCapturing)
  10975. {
  10976. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10977. if (thisType->IsValueType())
  10978. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10979. else
  10980. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10981. }
  10982. }
  10983. auto localDef = useMethodState->mLocals[0];
  10984. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10985. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10986. {
  10987. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10988. {
  10989. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10990. }
  10991. if (localDef->mIsSplat)
  10992. {
  10993. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10994. }
  10995. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10996. }
  10997. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10998. }
  10999. BfLocalVariable* BfModule::GetThisVariable()
  11000. {
  11001. if (mCurMethodState == NULL)
  11002. return NULL;
  11003. auto methodState = mCurMethodState->GetNonCaptureState();
  11004. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  11005. return methodState->mLocals[0];
  11006. return NULL;
  11007. }
  11008. bool BfModule::IsInGeneric()
  11009. {
  11010. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  11011. }
  11012. bool BfModule::InDefinitionSection()
  11013. {
  11014. if (mCurTypeInstance != NULL)
  11015. {
  11016. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11017. return false;
  11018. }
  11019. return !IsInSpecializedSection();
  11020. }
  11021. bool BfModule::IsInSpecializedGeneric()
  11022. {
  11023. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  11024. return false;
  11025. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  11026. }
  11027. bool BfModule::IsInSpecializedSection()
  11028. {
  11029. return IsInSpecializedGeneric() ||
  11030. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  11031. }
  11032. bool BfModule::IsInUnspecializedGeneric()
  11033. {
  11034. if (mCurMethodInstance != NULL)
  11035. return mCurMethodInstance->mIsUnspecialized;
  11036. return false;
  11037. }
  11038. //////////////////////////////////////////////////////////////////////////
  11039. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  11040. {
  11041. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  11042. if (type->IsValuelessType())
  11043. return mBfIRBuilder->GetFakeVal();
  11044. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  11045. if ((!doLifetimeEnd) && (WantsLifetimes()))
  11046. {
  11047. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  11048. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  11049. }
  11050. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  11051. auto typeOptions = GetTypeOptions();
  11052. if (typeOptions != NULL)
  11053. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  11054. // Local variable inits are implicitly handled in the Beef Backend
  11055. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  11056. {
  11057. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11058. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11059. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  11060. mBfIRBuilder->ClearDebugLocation(storeInst);
  11061. mBfIRBuilder->SetInsertPoint(prevBlock);
  11062. }
  11063. return allocaInst;
  11064. }
  11065. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  11066. {
  11067. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  11068. mCurMethodState->mLocals.push_back(localVar);
  11069. BfLocalVarEntry* localVarEntryPtr;
  11070. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  11071. {
  11072. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  11073. localVarEntryPtr->mLocalVar = localVar;
  11074. }
  11075. }
  11076. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11077. {
  11078. if ((mBfIRBuilder->DbgHasInfo()) &&
  11079. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  11080. (mHasFullDebugInfo) &&
  11081. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  11082. {
  11083. auto varType = localVarDef->mResolvedType;
  11084. if (localVarDef->mResolvedType->IsValuelessType())
  11085. {
  11086. }
  11087. else
  11088. {
  11089. bool isByAddr = false;
  11090. auto diValue = localVarDef->mValue;
  11091. if (localVarDef->mConstValue)
  11092. diValue = localVarDef->mConstValue;
  11093. else if (localVarDef->mAddr)
  11094. {
  11095. diValue = localVarDef->mAddr;
  11096. isByAddr = true;
  11097. }
  11098. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  11099. bool didConstToMem = false;
  11100. bool isConstant = false;
  11101. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  11102. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11103. else if (localVarDef->mConstValue)
  11104. {
  11105. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  11106. isConstant =
  11107. (constant->mConstType < BfConstType_GlobalVar) ||
  11108. (constant->mConstType == BfConstType_AggZero) ||
  11109. (constant->mConstType == BfConstType_Array);
  11110. if (isConstant)
  11111. {
  11112. if (localVarDef->mResolvedType->IsComposite())
  11113. {
  11114. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  11115. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  11116. if (IsTargetingBeefBackend())
  11117. {
  11118. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  11119. didConstToMem = true;
  11120. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11121. }
  11122. else
  11123. {
  11124. isByAddr = true;
  11125. mBfIRBuilder->SaveDebugLocation();
  11126. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11127. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11128. mBfIRBuilder->ClearDebugLocation();
  11129. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  11130. auto addrVal = CreateAlloca(ptrType);
  11131. mBfIRBuilder->CreateStore(constMem, addrVal);
  11132. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11133. diValue = addrVal;
  11134. didConstToMem = true;
  11135. mBfIRBuilder->SetInsertPoint(prevBlock);
  11136. mBfIRBuilder->RestoreDebugLocation();
  11137. }
  11138. }
  11139. if (mCompiler->mOptions.IsCodeView())
  11140. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11141. }
  11142. }
  11143. if (!mBfIRBuilder->mIgnoreWrites)
  11144. {
  11145. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11146. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  11147. localVarDef->mDbgVarInst = diVariable;
  11148. if (mBfIRBuilder->HasDebugLocation())
  11149. {
  11150. if ((isConstant) && (!didConstToMem))
  11151. {
  11152. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  11153. }
  11154. else
  11155. {
  11156. if ((IsTargetingBeefBackend()) && (doAliasValue))
  11157. {
  11158. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  11159. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  11160. }
  11161. if (isByAddr)
  11162. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  11163. else if (diValue)
  11164. {
  11165. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  11166. }
  11167. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  11168. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  11169. }
  11170. }
  11171. }
  11172. }
  11173. }
  11174. }
  11175. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11176. {
  11177. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  11178. {
  11179. if ((!localVarDef->mValue.IsConst()) &&
  11180. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  11181. {
  11182. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  11183. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  11184. }
  11185. }
  11186. if (addDebugInfo)
  11187. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  11188. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  11189. DoAddLocalVariable(localVarDef);
  11190. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11191. if (localVarDef->mLocalVarId == -1)
  11192. {
  11193. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  11194. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  11195. }
  11196. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  11197. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  11198. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  11199. {
  11200. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  11201. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  11202. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  11203. }
  11204. return localVarDef;
  11205. }
  11206. void BfModule::CreateDIRetVal()
  11207. {
  11208. if (!WantsDebugInfo())
  11209. return;
  11210. /*if (!mCurMethodState->mRetVal)
  11211. {
  11212. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  11213. return;
  11214. }*/
  11215. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  11216. {
  11217. BfType* dbgType = mCurMethodInstance->mReturnType;
  11218. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  11219. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11220. {
  11221. BF_ASSERT(mCurMethodState->mRetValAddr);
  11222. dbgType = CreatePointerType(dbgType);
  11223. dbgValue = mCurMethodState->mRetValAddr;
  11224. }
  11225. else
  11226. {
  11227. BF_ASSERT(!mCurMethodState->mRetValAddr);
  11228. }
  11229. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11230. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  11231. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  11232. }
  11233. }
  11234. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  11235. {
  11236. if (variableDef->mName.IsEmpty())
  11237. return;
  11238. BfLocalVarEntry* localVarEntryPtr = NULL;
  11239. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  11240. {
  11241. auto checkLocal = localVarEntryPtr->mLocalVar;
  11242. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  11243. {
  11244. BfError* error;
  11245. if (checkLocal->mIsImplicitParam)
  11246. return; // Ignore 'redefinition'
  11247. if (checkLocal->IsParam())
  11248. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  11249. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  11250. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11251. else
  11252. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11253. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  11254. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  11255. return;
  11256. }
  11257. }
  11258. }
  11259. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  11260. {
  11261. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  11262. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  11263. {
  11264. if (tokenNode->GetToken() == BfToken_Colon)
  11265. {
  11266. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  11267. {
  11268. Fail("Cannot access method scope across deferred block boundary", scopeName);
  11269. return NULL;
  11270. }
  11271. return &mCurMethodState->mHeadScope;
  11272. }
  11273. else if (tokenNode->GetToken() == BfToken_Mixin)
  11274. {
  11275. if (fromMixinState == NULL)
  11276. {
  11277. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  11278. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  11279. return mCurMethodState->mCurScope;
  11280. }
  11281. fromMixinState->mUsedInvocationScope = true;
  11282. return fromMixinState->mTargetScope;
  11283. }
  11284. else if (tokenNode->GetToken() == BfToken_New)
  11285. return NULL;
  11286. }
  11287. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  11288. {
  11289. auto findLabel = scopeName->ToString();
  11290. bool crossedDeferredBlock = false;
  11291. auto checkScope = mCurMethodState->mCurScope;
  11292. while (checkScope != NULL)
  11293. {
  11294. if (checkScope->mIsDeferredBlock)
  11295. crossedDeferredBlock = true;
  11296. if (checkScope->mLabel == findLabel)
  11297. {
  11298. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  11299. {
  11300. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  11301. return NULL;
  11302. }
  11303. return checkScope;
  11304. }
  11305. checkScope = checkScope->mPrevScope;
  11306. }
  11307. if (!inMixinDecl)
  11308. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  11309. }
  11310. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  11311. {
  11312. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  11313. }
  11314. return mCurMethodState->mCurScope;
  11315. }
  11316. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  11317. {
  11318. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  11319. }
  11320. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  11321. {
  11322. auto scopeData = FindScope(scopeName, false);
  11323. if (scopeData == NULL)
  11324. return NULL;
  11325. int scopeDepth = scopeData->GetDepth();
  11326. // Find the first break data that is at or below the depth of our requested scope
  11327. auto breakData = mCurMethodState->mBreakData;
  11328. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  11329. {
  11330. if (breakData->mScope->mIsConditional)
  11331. return NULL;
  11332. breakData = breakData->mPrevBreakData;
  11333. }
  11334. return breakData;
  11335. }
  11336. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  11337. {
  11338. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  11339. if (!IsTargetingBeefBackend())
  11340. return;
  11341. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  11342. {
  11343. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11344. }
  11345. }
  11346. void BfModule::ClearLifetimeEnds()
  11347. {
  11348. auto scopeData = mCurMethodState->mCurScope;
  11349. while (scopeData != NULL)
  11350. {
  11351. scopeData->mDeferredLifetimeEnds.Clear();
  11352. scopeData = scopeData->mPrevScope;
  11353. }
  11354. }
  11355. bool BfModule::WantsDebugInfo()
  11356. {
  11357. if ((mCurMethodInstance != NULL) &&
  11358. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  11359. return false;
  11360. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  11361. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  11362. }
  11363. BfTypeOptions* BfModule::GetTypeOptions()
  11364. {
  11365. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  11366. return mCurMethodState->mMethodTypeOptions;
  11367. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  11368. }
  11369. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  11370. {
  11371. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11372. while (checkScope != NULL)
  11373. {
  11374. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  11375. return true;
  11376. if (checkScope == scope)
  11377. break;
  11378. checkScope = checkScope->mPrevScope;
  11379. }
  11380. return false;
  11381. }
  11382. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  11383. {
  11384. // Is there anything we need to do here?
  11385. if (mBfIRBuilder->mIgnoreWrites)
  11386. {
  11387. // Just visit deferred blocks
  11388. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11389. while (checkScope != NULL)
  11390. {
  11391. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  11392. while (deferredCallEntry != NULL)
  11393. {
  11394. if (deferredCallEntry->mDeferredBlock != NULL)
  11395. {
  11396. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  11397. }
  11398. deferredCallEntry = deferredCallEntry->mNext;
  11399. }
  11400. if (checkScope == scopeData)
  11401. break;
  11402. checkScope = checkScope->mPrevScope;
  11403. }
  11404. return;
  11405. }
  11406. // Why did we want to do SetIllegalSrcPos here?
  11407. // Don't we always want to step onto these instances?
  11408. // Find a case where we don't and perhaps only do it there.
  11409. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  11410. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  11411. //SetIllegalSrcPos();
  11412. bool setSrcPos = false;
  11413. bool wantsNop = true;
  11414. BfAstNode* deferCloseNode = NULL;
  11415. if (mCurMethodState->mInPostReturn)
  11416. {
  11417. // These won't get used, they are post-return
  11418. return;
  11419. }
  11420. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  11421. BfScopeData* scopeJumpBlock = NULL;
  11422. bool hadExtraDeferredLifetimeEnds = false;
  11423. auto _FlushLifetimeEnds = [&]()
  11424. {
  11425. for (auto lifetimeEnd : deferredLifetimeEnds)
  11426. {
  11427. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11428. mBfIRBuilder->ClearDebugLocation_Last();
  11429. }
  11430. deferredLifetimeEnds.clear();
  11431. };
  11432. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11433. while (checkScope != NULL)
  11434. {
  11435. if (checkScope->mCloseNode != NULL)
  11436. deferCloseNode = checkScope->mCloseNode;
  11437. if (doneBlock)
  11438. {
  11439. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  11440. for (auto& checkHandler : checkScope->mDeferredHandlers)
  11441. {
  11442. if (checkHandler.mDoneBlock == doneBlock)
  11443. {
  11444. scopeJumpBlock = checkScope;
  11445. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  11446. mBfIRBuilder->ClearDebugLocation_Last();
  11447. _FlushLifetimeEnds();
  11448. break;
  11449. }
  11450. }
  11451. if (scopeJumpBlock != NULL)
  11452. break;
  11453. }
  11454. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  11455. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  11456. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  11457. if (hasWork)
  11458. {
  11459. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  11460. if (deferCloseNode != NULL)
  11461. {
  11462. UpdateSrcPos(deferCloseNode);
  11463. }
  11464. if (doneBlock)
  11465. {
  11466. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  11467. String blockName = "deferredCalls";
  11468. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  11469. BfDeferredHandler deferredHandler;
  11470. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  11471. {
  11472. mBfIRBuilder->SaveDebugLocation();
  11473. mBfIRBuilder->ClearDebugLocation();
  11474. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  11475. mBfIRBuilder->RestoreDebugLocation();
  11476. }
  11477. else
  11478. {
  11479. // Definitely chain
  11480. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  11481. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  11482. mBfIRBuilder->ClearDebugLocation_Last();
  11483. _FlushLifetimeEnds();
  11484. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  11485. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  11486. }
  11487. deferredHandler.mDoneBlock = doneBlock;
  11488. if (!mBfIRBuilder->mIgnoreWrites)
  11489. checkScope->mDeferredHandlers.push_back(deferredHandler);
  11490. if (checkScope == &mCurMethodState->mHeadScope)
  11491. {
  11492. if (!mCurMethodState->mDIRetVal)
  11493. {
  11494. // 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
  11495. // be scoped to the physical method
  11496. /*if (deferCloseNode != NULL)
  11497. {
  11498. UpdateSrcPos(deferCloseNode);
  11499. }*/
  11500. CreateDIRetVal();
  11501. }
  11502. }
  11503. if (checkScope != mCurMethodState->mTailScope)
  11504. {
  11505. if (deferredHandler.mHandlerBlock.IsFake())
  11506. {
  11507. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11508. }
  11509. if (!mBfIRBuilder->mIgnoreWrites)
  11510. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  11511. }
  11512. }
  11513. std::unordered_set<BfDeferredCallEntry*> handledSet;
  11514. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  11515. while (deferredCallEntry != NULL)
  11516. {
  11517. BfDeferredCallEmitState deferredCallEmitState;
  11518. deferredCallEmitState.mCloseNode = deferCloseNode;
  11519. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  11520. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  11521. if (deferCloseNode != NULL)
  11522. {
  11523. UpdateSrcPos(deferCloseNode);
  11524. }
  11525. if (wantsNop)
  11526. EmitEnsureInstructionAt();
  11527. wantsNop = false;
  11528. if (deferredCallEntry->mDeferredBlock != NULL)
  11529. {
  11530. auto itr = handledSet.insert(deferredCallEntry);
  11531. if (!itr.second)
  11532. {
  11533. // Already handled, can happen if we defer again within the block
  11534. deferredCallEntry = deferredCallEntry->mNext;
  11535. continue;
  11536. }
  11537. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  11538. EmitDeferredCall(*deferredCallEntry, true);
  11539. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  11540. {
  11541. // The list changed, start over and ignore anything we've already handled
  11542. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  11543. }
  11544. else
  11545. deferredCallEntry = deferredCallEntry->mNext;
  11546. }
  11547. else
  11548. {
  11549. EmitDeferredCall(*deferredCallEntry, true);
  11550. deferredCallEntry = deferredCallEntry->mNext;
  11551. }
  11552. }
  11553. if (checkScope->mSavedStack)
  11554. {
  11555. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  11556. if (mCurMethodState->mDynStackRevIdx)
  11557. {
  11558. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  11559. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  11560. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  11561. }
  11562. }
  11563. }
  11564. if (!checkScope->mIsScopeHead)
  11565. {
  11566. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  11567. if (!IsTargetingBeefBackend())
  11568. {
  11569. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11570. {
  11571. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11572. }
  11573. }
  11574. else
  11575. {
  11576. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11577. {
  11578. deferredLifetimeEnds.Add(lifetimeEnd);
  11579. }
  11580. }
  11581. }
  11582. if (checkScope == scopeData)
  11583. break;
  11584. checkScope = checkScope->mPrevScope;
  11585. }
  11586. if ((doneBlock) && (scopeJumpBlock == NULL))
  11587. {
  11588. mBfIRBuilder->CreateBr(doneBlock);
  11589. mBfIRBuilder->ClearDebugLocation_Last();
  11590. }
  11591. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  11592. // may have been created when other scope lifetimes were available
  11593. _FlushLifetimeEnds();
  11594. // Emit lifetimeEnds after the branch for Beef
  11595. /*if (IsTargetingBeefBackend())
  11596. {
  11597. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  11598. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11599. while (checkScope != NULL)
  11600. {
  11601. if (checkScope == scopeJumpBlock)
  11602. break;
  11603. if (!checkScope->mIsScopeHead)
  11604. {
  11605. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11606. {
  11607. if (needsEnsureInst)
  11608. {
  11609. needsEnsureInst = false;
  11610. }
  11611. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11612. }
  11613. }
  11614. if (checkScope == scopeData)
  11615. break;
  11616. checkScope = checkScope->mPrevScope;
  11617. }
  11618. }*/
  11619. }
  11620. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  11621. {
  11622. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  11623. {
  11624. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  11625. while (deferredLocalAssignData != NULL)
  11626. {
  11627. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  11628. break;
  11629. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  11630. deferredLocalAssignData->mIsUnconditional = false;
  11631. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11632. }
  11633. }
  11634. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11635. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  11636. // int b;
  11637. // if (cond) return;
  11638. // else b = 1;
  11639. // Use(b);
  11640. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11641. {
  11642. auto localDef = mCurMethodState->mLocals[localIdx];
  11643. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  11644. mCurMethodState->LocalDefined(localDef);
  11645. }
  11646. }
  11647. void BfModule::CreateReturn(BfIRValue val)
  11648. {
  11649. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11650. {
  11651. // Store to sret
  11652. BF_ASSERT(val);
  11653. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  11654. mBfIRBuilder->CreateRetVoid();
  11655. }
  11656. else
  11657. {
  11658. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11659. {
  11660. mBfIRBuilder->CreateRetVoid();
  11661. }
  11662. else if (mCurMethodInstance->mReturnType->IsStruct())
  11663. {
  11664. BfTypeCode loweredReturnType = BfTypeCode_None;
  11665. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  11666. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  11667. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  11668. mBfIRBuilder->CreateStore(val, retVal);
  11669. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  11670. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  11671. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  11672. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  11673. mBfIRBuilder->CreateRet(loadedReturnValue);
  11674. }
  11675. else
  11676. {
  11677. BF_ASSERT(val);
  11678. mBfIRBuilder->CreateRet(val);
  11679. }
  11680. }
  11681. }
  11682. void BfModule::EmitReturn(BfIRValue val)
  11683. {
  11684. if (mCurMethodState->mIRExitBlock)
  11685. {
  11686. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  11687. {
  11688. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  11689. {
  11690. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  11691. if (!mCurMethodState->mRetVal)
  11692. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  11693. mBfIRBuilder->CreateStore(val, retVal);
  11694. }
  11695. }
  11696. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11697. }
  11698. else
  11699. {
  11700. EmitDeferredScopeCalls(false, NULL);
  11701. if (val)
  11702. {
  11703. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11704. mBfIRBuilder->CreateRetVoid();
  11705. else
  11706. mBfIRBuilder->CreateRet(val);
  11707. }
  11708. }
  11709. mCurMethodState->SetHadReturn(true);
  11710. mCurMethodState->mLeftBlockUncond = true;
  11711. }
  11712. void BfModule::EmitDefaultReturn()
  11713. {
  11714. if (mCurMethodState->mInDeferredBlock)
  11715. return;
  11716. if (mCurMethodState->mIRExitBlock)
  11717. {
  11718. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11719. }
  11720. else
  11721. {
  11722. if (mCurMethodInstance->mReturnType->IsVoid())
  11723. mBfIRBuilder->CreateRetVoid();
  11724. else if (mCurMethodInstance->GetStructRetIdx() == -1)
  11725. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  11726. }
  11727. mCurMethodState->SetHadReturn(true);
  11728. mCurMethodState->mLeftBlockUncond = true;
  11729. }
  11730. void BfModule::AssertErrorState()
  11731. {
  11732. if (mIgnoreErrors)
  11733. return;
  11734. if (mHadBuildError)
  11735. return;
  11736. if (mCurTypeInstance != NULL)
  11737. {
  11738. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11739. return;
  11740. }
  11741. if (mCurMethodInstance != NULL)
  11742. {
  11743. if (mCurMethodInstance->mIsUnspecializedVariation)
  11744. return;
  11745. if (mCurMethodInstance->mHasFailed)
  11746. return;
  11747. }
  11748. // We want the module to be marked as failed even if it's just an error in the parser
  11749. if (mCurMethodInstance != NULL)
  11750. mCurMethodInstance->mHasFailed = true;
  11751. mHadBuildError = true;
  11752. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  11753. if (mCurTypeInstance != NULL)
  11754. {
  11755. if (mCurTypeInstance->mTypeFailed)
  11756. return;
  11757. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  11758. return;
  11759. }
  11760. if (mCurMethodInstance != NULL)
  11761. {
  11762. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11763. return;
  11764. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11765. return;
  11766. }
  11767. if (mCompiler->IsAutocomplete())
  11768. return;
  11769. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  11770. }
  11771. void BfModule::AssertParseErrorState()
  11772. {
  11773. if (mCompiler->mRevision == 1)
  11774. AssertErrorState();
  11775. }
  11776. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  11777. {
  11778. BF_ASSERT(delegateType->IsDelegate());
  11779. auto typeInst = delegateType->ToTypeInstance();
  11780. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  11781. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  11782. return invokeMethodInstance->mReturnType;
  11783. }
  11784. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11785. {
  11786. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11787. }
  11788. void BfModule::CreateDelegateInvokeMethod()
  11789. {
  11790. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11791. //mBfIRBuilder->ClearDebugLocation();
  11792. SetIllegalSrcPos();
  11793. auto typeInstance = mCurTypeInstance;
  11794. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11795. SizedArray<BfIRType, 4> staticParamTypes;
  11796. SizedArray<BfIRValue, 4> staticFuncArgs;
  11797. SizedArray<BfIRValue, 4> memberFuncArgs;
  11798. auto multicastDelegateType = typeInstance->mBaseType;
  11799. if (multicastDelegateType->mFieldInstances.size() != 2)
  11800. {
  11801. AssertErrorState();
  11802. return;
  11803. }
  11804. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11805. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11806. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11807. BfExprEvaluator exprEvaluator(this);
  11808. SizedArray<BfIRType, 8> origParamTypes;
  11809. BfIRType origReturnType;
  11810. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11811. if (mCurMethodInstance->mReturnType->IsValueType())
  11812. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11813. if (mCurMethodInstance->GetStructRetIdx() != 0)
  11814. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11815. int thisIdx = 0;
  11816. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11817. {
  11818. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  11819. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  11820. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  11821. }
  11822. if (mCurMethodInstance->GetStructRetIdx() == 0)
  11823. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11824. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11825. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11826. {
  11827. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11828. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11829. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11830. }
  11831. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11832. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11833. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11834. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11835. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11836. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11837. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11838. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11839. BfIRValue nonStaticResult;
  11840. BfIRValue staticResult;
  11841. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  11842. /// Non-static invocation
  11843. {
  11844. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11845. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11846. mBfIRBuilder->SetInsertPoint(trueBB);
  11847. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11848. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11849. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11850. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11851. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11852. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11853. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  11854. if (callingConv != BfIRCallingConv_CDecl)
  11855. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11856. mCurMethodState->SetHadReturn(false);
  11857. mCurMethodState->mLeftBlockUncond = false;
  11858. mCurMethodState->mLeftBlockCond = false;
  11859. mBfIRBuilder->CreateBr(doneBB);
  11860. }
  11861. // Static invocation
  11862. {
  11863. mBfIRBuilder->AddBlock(falseBB);
  11864. mBfIRBuilder->SetInsertPoint(falseBB);
  11865. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11866. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11867. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11868. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11869. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11870. {
  11871. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  11872. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  11873. }
  11874. if (callingConv == BfIRCallingConv_ThisCall)
  11875. callingConv = BfIRCallingConv_CDecl;
  11876. if (callingConv != BfIRCallingConv_CDecl)
  11877. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11878. mCurMethodState->SetHadReturn(false);
  11879. mCurMethodState->mLeftBlockUncond = false;
  11880. mCurMethodState->mLeftBlockCond = false;
  11881. mBfIRBuilder->CreateBr(doneBB);
  11882. }
  11883. mBfIRBuilder->AddBlock(doneBB);
  11884. mBfIRBuilder->SetInsertPoint(doneBB);
  11885. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->GetStructRetIdx() != -1))
  11886. {
  11887. mBfIRBuilder->CreateRetVoid();
  11888. }
  11889. else
  11890. {
  11891. BfIRType loweredIRReturnType;
  11892. BfTypeCode loweredTypeCode = BfTypeCode_None;
  11893. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  11894. if (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2))
  11895. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  11896. else
  11897. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  11898. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  11899. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11900. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11901. mBfIRBuilder->CreateRet(phi);
  11902. }
  11903. }
  11904. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11905. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11906. {
  11907. auto typeDef = typeInstance->mTypeDef;
  11908. auto methodDeclaration = methodDef->mMethodDeclaration;
  11909. if (!mCompiler->mIsResolveOnly)
  11910. return true;
  11911. if (typeInstance->IsGenericTypeInstance())
  11912. {
  11913. // We only really want to process the unspecialized type for autocompletion
  11914. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11915. return false;
  11916. }
  11917. BfAstNode* checkNode = methodDeclaration;
  11918. if (methodDeclaration == NULL)
  11919. checkNode = methodDef->mBody;
  11920. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11921. {
  11922. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11923. return true;
  11924. }
  11925. return false;
  11926. }
  11927. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11928. {
  11929. methodInst->mAppendAllocAlign = 1;
  11930. }
  11931. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11932. {
  11933. BP_ZONE("BfModule::TryConstCalcAppend");
  11934. if (mCompiler->mIsResolveOnly)
  11935. return BfTypedValue();
  11936. // We want to regenerate all ctor calls when the method internals change
  11937. {
  11938. auto checkTypeInst = methodInst->GetOwner();
  11939. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11940. {
  11941. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11942. checkTypeInst = GetBaseType(checkTypeInst);
  11943. }
  11944. }
  11945. if (!methodInst->mMayBeConst)
  11946. return BfTypedValue();
  11947. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11948. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11949. bool wasAllConst = true;
  11950. int argIdx = 0;
  11951. int paramIdx = 0;
  11952. while (true)
  11953. {
  11954. if (argIdx >= (int)args.size())
  11955. break;
  11956. auto paramType = methodInst->GetParamType(paramIdx);
  11957. PopulateType(paramType);
  11958. int argCount = 0;
  11959. if (!paramType->IsValuelessType())
  11960. {
  11961. if (methodInst->GetParamIsSplat(paramIdx))
  11962. argCount = paramType->GetSplatCount();
  11963. else
  11964. argCount = 1;
  11965. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11966. {
  11967. auto arg = args[argIdx + argOfs];
  11968. if (!arg.IsConst())
  11969. {
  11970. wasAllConst = false;
  11971. if (!isFirstRun)
  11972. {
  11973. auto& param = methodInst->mParams[argIdx];
  11974. if (param.mReferencedInConstPass)
  11975. {
  11976. // If this param is required as part of the const calculation then
  11977. // we require that it be const...
  11978. return BfTypedValue();
  11979. }
  11980. }
  11981. }
  11982. }
  11983. }
  11984. paramIdx++;
  11985. argIdx += argCount;
  11986. }
  11987. auto methodDef = methodInst->mMethodDef;
  11988. auto methodDecl = methodDef->GetMethodDeclaration();
  11989. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11990. if (methodDeclBlock == NULL)
  11991. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  11992. BfTypedValue constValue;
  11993. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11994. auto checkState = mCurMethodState->mConstResolveState;
  11995. while (checkState != NULL)
  11996. {
  11997. if (checkState->mMethodInstance == methodInst)
  11998. {
  11999. return BfTypedValue();
  12000. }
  12001. checkState = checkState->mPrevConstResolveState;
  12002. }
  12003. //auto accumValue = GetConstValue(0);
  12004. bool failed = false;
  12005. //
  12006. {
  12007. BfConstResolveState constResolveState;
  12008. constResolveState.mMethodInstance = methodInst;
  12009. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  12010. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12011. BfMethodState methodState;
  12012. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  12013. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  12014. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  12015. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  12016. methodState.mConstResolveState = &constResolveState;
  12017. int argIdx = 0;
  12018. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12019. {
  12020. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  12021. continue;
  12022. auto paramType = methodInst->GetParamType(paramIdx);
  12023. // Fix this after we allow structs to be consts
  12024. //BF_ASSERT(!paramType->IsSplattable());
  12025. BfLocalVariable* localVar = new BfLocalVariable();
  12026. localVar->mName = methodInst->GetParamName(paramIdx);
  12027. localVar->mResolvedType = paramType;
  12028. localVar->mConstValue = args[argIdx];
  12029. localVar->mParamIdx = paramIdx;
  12030. AddLocalVariableDef(localVar);
  12031. argIdx++;
  12032. }
  12033. AppendAllocVisitor appendAllocVisitor;
  12034. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  12035. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  12036. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  12037. if (baseCtorAppendValue)
  12038. {
  12039. if (baseCtorAppendValue.mValue.IsFake())
  12040. appendAllocVisitor.mFailed = true;
  12041. else
  12042. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  12043. }
  12044. appendAllocVisitor.mModule = this;
  12045. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12046. if (!appendAllocVisitor.mFailed)
  12047. constValue = appendAllocVisitor.mConstAccum;
  12048. if (isFirstRun)
  12049. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  12050. if (isFirstRun)
  12051. {
  12052. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12053. {
  12054. auto localVar = mCurMethodState->mLocals[paramIdx];
  12055. if (localVar->mReadFromId != -1)
  12056. {
  12057. auto& param = methodInst->mParams[paramIdx];
  12058. param.mReferencedInConstPass = true;
  12059. }
  12060. }
  12061. }
  12062. }
  12063. mBfIRBuilder->SetInsertPoint(prevBlock);
  12064. if (!constValue)
  12065. {
  12066. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  12067. // all-const args
  12068. if (wasAllConst)
  12069. {
  12070. methodInst->mMayBeConst = false;
  12071. }
  12072. }
  12073. return constValue;
  12074. }
  12075. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  12076. {
  12077. // Any errors should only be shown in the actual CTOR call
  12078. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  12079. auto methodDef = mCurMethodInstance->mMethodDef;
  12080. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  12081. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12082. BfTypeInstance* targetType = NULL;
  12083. if (ctorDeclaration->mInitializer != NULL)
  12084. {
  12085. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12086. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12087. }
  12088. else
  12089. targetType = mCurTypeInstance->mBaseType;
  12090. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  12091. return NULL;
  12092. auto targetRefNode = methodDef->GetRefNode();
  12093. BfType* targetThisType = targetType;
  12094. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  12095. BfExprEvaluator exprEvaluator(this);
  12096. BfResolvedArgs argValues;
  12097. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12098. {
  12099. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12100. }
  12101. //
  12102. {
  12103. }
  12104. BfFunctionBindResult bindResult;
  12105. bindResult.mSkipThis = true;
  12106. bindResult.mWantsArgs = true;
  12107. {
  12108. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12109. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12110. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12111. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12112. }
  12113. if (bindResult.mMethodInstance == NULL)
  12114. {
  12115. AssertErrorState();
  12116. return BfTypedValue();
  12117. }
  12118. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  12119. {
  12120. return BfTypedValue();
  12121. }
  12122. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12123. bindResult.mIRArgs.RemoveAt(0);
  12124. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  12125. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  12126. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  12127. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  12128. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  12129. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  12130. if (appendSizeTypedValue)
  12131. return appendSizeTypedValue;
  12132. if (constOnly)
  12133. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  12134. bool needsRecalc = false;
  12135. for (auto irArg : bindResult.mIRArgs)
  12136. {
  12137. if (irArg.IsFake())
  12138. needsRecalc = true;
  12139. }
  12140. auto calcAppendArgs = bindResult.mIRArgs;
  12141. if (needsRecalc)
  12142. {
  12143. // Do it again, but without mIgnoreWrites set
  12144. BfResolvedArgs argValues;
  12145. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12146. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12147. BfFunctionBindResult bindResult;
  12148. bindResult.mSkipThis = true;
  12149. bindResult.mWantsArgs = true;
  12150. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12151. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12152. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12153. bindResult.mIRArgs.RemoveAt(0);
  12154. calcAppendArgs = bindResult.mIRArgs;
  12155. }
  12156. BF_ASSERT(calcAppendMethodModule.mFunc);
  12157. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  12158. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  12159. return appendSizeTypedValue;
  12160. }
  12161. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  12162. void BfModule::EmitCtorCalcAppend()
  12163. {
  12164. if (mCompiler->mIsResolveOnly)
  12165. return;
  12166. auto methodDef = mCurMethodInstance->mMethodDef;
  12167. auto methodDecl = methodDef->GetMethodDeclaration();
  12168. Array<BfAstNode*> deferredNodeList;
  12169. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  12170. if (methodDeclBlock == NULL)
  12171. return;
  12172. AppendAllocVisitor appendAllocVisitor;
  12173. auto baseCalcAppend = CallBaseCtorCalc(false);
  12174. if (baseCalcAppend)
  12175. {
  12176. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  12177. }
  12178. appendAllocVisitor.mModule = this;
  12179. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12180. }
  12181. void BfModule::CreateStaticCtor()
  12182. {
  12183. auto typeDef = mCurTypeInstance->mTypeDef;
  12184. auto methodDef = mCurMethodInstance->mMethodDef;
  12185. BfIRBlock exitBB;
  12186. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  12187. {
  12188. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  12189. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  12190. mBfIRBuilder->MapType(boolType),
  12191. false,
  12192. BfIRLinkageType_Internal,
  12193. GetDefaultValue(boolType),
  12194. "didStaticInit");
  12195. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  12196. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  12197. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  12198. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  12199. mBfIRBuilder->SetInsertPoint(initBB);
  12200. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  12201. }
  12202. // Do DLL imports
  12203. if (!mDllImportEntries.empty())
  12204. {
  12205. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  12206. PopulateType(internalType);
  12207. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  12208. if (!getSharedProcAddressInstance)
  12209. {
  12210. if (!mCompiler->mPassInstance->HasFailed())
  12211. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  12212. }
  12213. }
  12214. // Fill in initializer values
  12215. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12216. {
  12217. for (auto fieldDef : typeDef->mFields)
  12218. {
  12219. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12220. {
  12221. // For extensions, only handle these fields in the appropriate extension
  12222. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12223. continue;
  12224. UpdateSrcPos(fieldDef->mInitializer);
  12225. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12226. if (!fieldInst->mFieldIncluded)
  12227. continue;
  12228. if (fieldInst->mResolvedType->IsVar())
  12229. {
  12230. continue;
  12231. }
  12232. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  12233. }
  12234. }
  12235. }
  12236. else
  12237. {
  12238. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12239. {
  12240. if (tempTypeDef->mFullName == typeDef->mFullName)
  12241. {
  12242. for (auto fieldDef : tempTypeDef->mFields)
  12243. {
  12244. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  12245. {
  12246. if (fieldDef->mInitializer != NULL)
  12247. {
  12248. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  12249. {
  12250. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12251. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12252. }
  12253. BfType* wantType = NULL;
  12254. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  12255. {
  12256. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12257. }
  12258. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12259. }
  12260. }
  12261. }
  12262. }
  12263. }
  12264. }
  12265. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12266. CallChainedMethods(mCurMethodInstance, false);
  12267. }
  12268. void BfModule::EmitDtorBody()
  12269. {
  12270. if (mCurTypeInstance->IsClosure())
  12271. {
  12272. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  12273. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  12274. auto thisVal = GetThis();
  12275. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  12276. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  12277. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12278. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  12279. SizedArray<BfIRValue, 1> args;
  12280. args.push_back(thisVal.mValue);
  12281. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  12282. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  12283. // Fall through to Object::~this call
  12284. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  12285. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  12286. SizedArray<BfIRValue, 1> vals = { basePtr };
  12287. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  12288. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  12289. mBfIRBuilder->SetTailCall(result);
  12290. return;
  12291. }
  12292. auto typeDef = mCurTypeInstance->mTypeDef;
  12293. auto methodDef = mCurMethodInstance->mMethodDef;
  12294. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12295. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12296. CallChainedMethods(mCurMethodInstance, true);
  12297. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12298. {
  12299. VisitCodeBlock(bodyBlock);
  12300. if (bodyBlock->mCloseBrace != NULL)
  12301. {
  12302. UpdateSrcPos(bodyBlock->mCloseBrace);
  12303. }
  12304. }
  12305. else
  12306. {
  12307. if (methodDeclaration != NULL)
  12308. UpdateSrcPos(methodDeclaration);
  12309. else if (typeDef->mTypeDeclaration != NULL)
  12310. UpdateSrcPos(typeDef->mTypeDeclaration);
  12311. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  12312. {
  12313. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  12314. }
  12315. }
  12316. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12317. {
  12318. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  12319. {
  12320. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  12321. auto fieldDef = fieldInst->GetFieldDef();
  12322. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  12323. {
  12324. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  12325. {
  12326. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  12327. }
  12328. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  12329. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  12330. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  12331. continue;
  12332. UpdateSrcPos(fieldDtor);
  12333. BfScopeData scopeData;
  12334. mCurMethodState->AddScope(&scopeData);
  12335. NewScopeState();
  12336. UpdateSrcPos(fieldDtor);
  12337. bool hasDbgInfo = (!fieldDef->mIsConst);
  12338. if (hasDbgInfo)
  12339. {
  12340. mBfIRBuilder->SaveDebugLocation();
  12341. mBfIRBuilder->ClearDebugLocation();
  12342. }
  12343. BfIRValue value;
  12344. if (fieldDef->mIsStatic)
  12345. {
  12346. value = ReferenceStaticField(fieldInst).mValue;
  12347. }
  12348. else
  12349. {
  12350. if (!mCurTypeInstance->IsValueType())
  12351. {
  12352. auto thisValue = GetThis();
  12353. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  12354. }
  12355. else
  12356. {
  12357. AssertErrorState();
  12358. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  12359. }
  12360. }
  12361. BfIRValue staticVal;
  12362. if (hasDbgInfo)
  12363. {
  12364. BfIRValue dbgShowValue = value;
  12365. BfLocalVariable* localDef = new BfLocalVariable();
  12366. localDef->mName = "_";
  12367. localDef->mResolvedType = fieldInst->mResolvedType;
  12368. localDef->mAddr = value;
  12369. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  12370. {
  12371. // Create another pointer indirection, a ref to the gep
  12372. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  12373. auto allocaInst = CreateAlloca(refFieldType);
  12374. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  12375. localDef->mResolvedType = refFieldType;
  12376. localDef->mAddr = allocaInst;
  12377. }
  12378. mBfIRBuilder->RestoreDebugLocation();
  12379. auto defLocalVar = AddLocalVariableDef(localDef, true);
  12380. // Put back so we actually modify the correct value*/
  12381. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  12382. defLocalVar->mAddr = value;
  12383. }
  12384. while (fieldDtor != NULL)
  12385. {
  12386. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12387. {
  12388. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  12389. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  12390. }
  12391. UpdateSrcPos(fieldDtor);
  12392. VisitEmbeddedStatement(fieldDtor->mBody);
  12393. fieldDtor = fieldDtor->mNextFieldDtor;
  12394. }
  12395. RestoreScopeState();
  12396. }
  12397. }
  12398. if (!methodDef->mIsStatic)
  12399. {
  12400. auto checkBaseType = mCurTypeInstance->mBaseType;
  12401. while (checkBaseType != NULL)
  12402. {
  12403. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12404. {
  12405. if (bodyBlock->mCloseBrace != NULL)
  12406. UpdateSrcPos(bodyBlock->mCloseBrace);
  12407. }
  12408. else
  12409. {
  12410. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  12411. }
  12412. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  12413. {
  12414. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  12415. if (mCompiler->IsSkippingExtraResolveChecks())
  12416. {
  12417. // Nothing
  12418. }
  12419. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  12420. {
  12421. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  12422. {
  12423. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  12424. SizedArray<BfIRValue, 1> vals = { basePtr };
  12425. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  12426. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  12427. }
  12428. }
  12429. else
  12430. {
  12431. // Invalid base dtor declaration
  12432. AssertErrorState();
  12433. }
  12434. break;
  12435. }
  12436. checkBaseType = checkBaseType->mBaseType;
  12437. }
  12438. }
  12439. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  12440. }
  12441. else
  12442. {
  12443. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12444. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12445. // resolve pass, NOT the autocomplete expression
  12446. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12447. {
  12448. if (tempTypeDef->mFullName == typeDef->mFullName)
  12449. {
  12450. for (auto fieldDef : tempTypeDef->mFields)
  12451. {
  12452. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  12453. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12454. {
  12455. BfType* fieldType = NULL;
  12456. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  12457. {
  12458. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  12459. auto curFieldDef = curFieldInstance->GetFieldDef();
  12460. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  12461. fieldType = curFieldInstance->GetResolvedType();
  12462. }
  12463. if (fieldType == NULL)
  12464. fieldType = GetPrimitiveType(BfTypeCode_Var);
  12465. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  12466. BfScopeData scopeData;
  12467. mCurMethodState->AddScope(&scopeData);
  12468. NewScopeState();
  12469. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  12470. if (fieldType != NULL)
  12471. {
  12472. BfLocalVariable* localDef = new BfLocalVariable();
  12473. localDef->mName = "_";
  12474. localDef->mResolvedType = fieldType;
  12475. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  12476. localDef->mIsAssigned = true;
  12477. AddLocalVariableDef(localDef);
  12478. }
  12479. while (fieldDtor != NULL)
  12480. {
  12481. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  12482. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  12483. UpdateSrcPos(fieldDtor);
  12484. VisitEmbeddedStatement(fieldDtor->mBody);
  12485. fieldDtor = fieldDtor->mNextFieldDtor;
  12486. }
  12487. RestoreScopeState();
  12488. }
  12489. }
  12490. }
  12491. }
  12492. }
  12493. }
  12494. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  12495. {
  12496. auto typeInstance = methodInstance->GetOwner();
  12497. bool foundDllImportAttr = false;
  12498. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  12499. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  12500. {
  12501. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  12502. {
  12503. foundDllImportAttr = true;
  12504. }
  12505. }
  12506. if (!foundDllImportAttr)
  12507. {
  12508. AssertErrorState();
  12509. return BfIRValue();
  12510. }
  12511. String name = "bf_hs_preserve@";
  12512. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  12513. name += "__imp";
  12514. BfIRType returnType;
  12515. SizedArray<BfIRType, 8> paramTypes;
  12516. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  12517. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  12518. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  12519. BfIRValue initVal;
  12520. if (define)
  12521. {
  12522. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  12523. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  12524. }
  12525. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  12526. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  12527. {
  12528. auto voidType = GetPrimitiveType(BfTypeCode_None);
  12529. auto ptrType = CreatePointerType(voidType);
  12530. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  12531. }
  12532. return globalVar;
  12533. }
  12534. void BfModule::CreateDllImportMethod()
  12535. {
  12536. if (mBfIRBuilder->mIgnoreWrites)
  12537. return;
  12538. auto globalVar = mFuncReferences[mCurMethodInstance];
  12539. if (!globalVar)
  12540. return;
  12541. bool allowTailCall = true;
  12542. mBfIRBuilder->ClearDebugLocation();
  12543. bool isHotCompile = mCompiler->IsHotCompile();
  12544. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  12545. if (isHotCompile)
  12546. {
  12547. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  12548. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  12549. }
  12550. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  12551. BfIRType returnType;
  12552. SizedArray<BfIRType, 8> paramTypes;
  12553. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  12554. SizedArray<BfIRValue, 8> args;
  12555. for (int i = 0; i < (int)paramTypes.size(); i++)
  12556. args.push_back(mBfIRBuilder->GetArgument(i));
  12557. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  12558. if (isHotCompile)
  12559. {
  12560. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  12561. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  12562. if (callingConvention == BfIRCallingConv_StdCall)
  12563. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  12564. else if (callingConvention == BfIRCallingConv_FastCall)
  12565. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  12566. else
  12567. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  12568. if (allowTailCall)
  12569. mBfIRBuilder->SetTailCall(result);
  12570. CreateReturn(result);
  12571. mCurMethodState->mHadReturn = true;
  12572. }
  12573. if (HasCompiledOutput())
  12574. {
  12575. BfDllImportEntry dllImportEntry;
  12576. dllImportEntry.mFuncVar = globalVar;
  12577. dllImportEntry.mMethodInstance = mCurMethodInstance;
  12578. mDllImportEntries.push_back(dllImportEntry);
  12579. }
  12580. }
  12581. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  12582. {
  12583. auto methodDef = methodInstance->mMethodDef;
  12584. BfTypeInstance* owner = NULL;
  12585. if (!methodDef->mIsStatic)
  12586. owner = methodInstance->GetParamType(-1)->ToTypeInstance();
  12587. if (owner == NULL)
  12588. owner = methodInstance->GetOwner();
  12589. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  12590. return BfIRCallingConv_CDecl;
  12591. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  12592. return BfIRCallingConv_StdCall;
  12593. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  12594. return BfIRCallingConv_FastCall;
  12595. if ((!methodDef->mIsStatic) && (!owner->IsValuelessType()) &&
  12596. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  12597. return BfIRCallingConv_ThisCall;
  12598. return BfIRCallingConv_CDecl;
  12599. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  12600. }
  12601. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  12602. {
  12603. BfMethodDef* methodDef = NULL;
  12604. if (methodInstance != NULL)
  12605. methodDef = methodInstance->mMethodDef;
  12606. if (!func)
  12607. return;
  12608. if (mCompiler->mOptions.mNoFramePointerElim)
  12609. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  12610. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  12611. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  12612. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  12613. if (methodInstance == NULL)
  12614. return;
  12615. if (methodDef->mImportKind == BfImportKind_Export)
  12616. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  12617. if (methodDef->mNoReturn)
  12618. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  12619. auto callingConv = GetIRCallingConvention(methodInstance);
  12620. if (callingConv != BfIRCallingConv_CDecl)
  12621. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  12622. if (isInlined)
  12623. {
  12624. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  12625. }
  12626. int argIdx = 0;
  12627. int paramIdx = 0;
  12628. if (methodInstance->HasThis())
  12629. {
  12630. paramIdx = -1;
  12631. }
  12632. int argCount = methodInstance->GetIRFunctionParamCount(this);
  12633. while (argIdx < argCount)
  12634. {
  12635. if (argIdx == methodInstance->GetStructRetIdx())
  12636. {
  12637. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  12638. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  12639. argIdx++;
  12640. continue;
  12641. }
  12642. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  12643. paramIdx++;
  12644. BfType* resolvedTypeRef = NULL;
  12645. BfType* resolvedTypeRef2 = NULL;
  12646. String paramName;
  12647. bool isSplattable = false;
  12648. bool tryLowering = true;
  12649. bool isThis = paramIdx == -1;
  12650. if (isThis)
  12651. {
  12652. paramName = "this";
  12653. if (methodInstance->mIsClosure)
  12654. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  12655. else
  12656. resolvedTypeRef = methodInstance->GetOwner();
  12657. isSplattable = (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsThisSplatting());
  12658. tryLowering = methodInstance->AllowsThisSplatting();
  12659. }
  12660. else
  12661. {
  12662. paramName = methodInstance->GetParamName(paramIdx);
  12663. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  12664. if (resolvedTypeRef->IsMethodRef())
  12665. isSplattable = true;
  12666. else if ((resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting()))
  12667. {
  12668. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  12669. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  12670. {
  12671. // crepr splat is always splattable
  12672. isSplattable = true;
  12673. }
  12674. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  12675. isSplattable = true;
  12676. }
  12677. }
  12678. if (tryLowering)
  12679. {
  12680. BfTypeCode loweredTypeCode = BfTypeCode_None;
  12681. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  12682. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  12683. {
  12684. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  12685. argIdx++;
  12686. if (loweredTypeCode2 != BfTypeCode_None)
  12687. {
  12688. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  12689. argIdx++;
  12690. }
  12691. paramIdx++;
  12692. continue;
  12693. }
  12694. }
  12695. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  12696. {
  12697. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  12698. int addDeref = -1;
  12699. if (resolvedTypeRef->IsRef())
  12700. {
  12701. auto refType = (BfRefType*)resolvedTypeRef;
  12702. auto elementType = refType->mElementType;
  12703. PopulateType(elementType, BfPopulateType_Data);
  12704. addDeref = elementType->mSize;
  12705. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  12706. AssertErrorState();
  12707. }
  12708. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  12709. {
  12710. if (paramIdx == -1)
  12711. {
  12712. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  12713. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  12714. addDeref = resolvedTypeRef->mSize;
  12715. }
  12716. else if (methodInstance->WantsIRStructsByVal())
  12717. {
  12718. mBfIRBuilder->PopulateType(resolvedTypeRef);
  12719. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  12720. }
  12721. }
  12722. else if (resolvedTypeRef->IsPrimitiveType())
  12723. {
  12724. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  12725. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  12726. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  12727. }
  12728. if (addDeref >= 0)
  12729. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  12730. argIdx++;
  12731. };
  12732. if (isSplattable)
  12733. {
  12734. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  12735. {
  12736. if (checkType->IsStruct())
  12737. {
  12738. auto checkTypeInstance = checkType->ToTypeInstance();
  12739. if (checkTypeInstance->mBaseType != NULL)
  12740. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  12741. if (checkTypeInstance->mIsUnion)
  12742. {
  12743. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  12744. checkTypeLambda(unionInnerType, curName + "_data");
  12745. }
  12746. else
  12747. {
  12748. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12749. {
  12750. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12751. auto fieldDef = fieldInstance->GetFieldDef();
  12752. if (fieldInstance->mDataIdx >= 0)
  12753. {
  12754. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  12755. }
  12756. }
  12757. }
  12758. if (checkTypeInstance->IsEnum())
  12759. {
  12760. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  12761. argIdx++;
  12762. }
  12763. }
  12764. else if (checkType->IsMethodRef())
  12765. {
  12766. auto methodRefType = (BfMethodRefType*)checkType;
  12767. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12768. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  12769. {
  12770. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  12771. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12772. {
  12773. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  12774. }
  12775. else
  12776. {
  12777. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  12778. }
  12779. }
  12780. }
  12781. else if (!checkType->IsValuelessType())
  12782. {
  12783. _SetupParam(curName, checkType);
  12784. }
  12785. };
  12786. checkTypeLambda(resolvedTypeRef, paramName);
  12787. paramIdx++;
  12788. continue;
  12789. }
  12790. _SetupParam(paramName, resolvedTypeRef);
  12791. if (resolvedTypeRef2 != NULL)
  12792. _SetupParam(paramName, resolvedTypeRef2);
  12793. paramIdx++;
  12794. }
  12795. }
  12796. void BfModule::EmitCtorBody(bool& skipBody)
  12797. {
  12798. auto methodInstance = mCurMethodInstance;
  12799. auto methodDef = methodInstance->mMethodDef;
  12800. auto methodDeclaration = methodDef->mMethodDeclaration;
  12801. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12802. auto typeDef = mCurTypeInstance->mTypeDef;
  12803. // Prologue
  12804. mBfIRBuilder->ClearDebugLocation();
  12805. bool hadThisInitializer = false;
  12806. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12807. {
  12808. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12809. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12810. if (targetToken->GetToken() == BfToken_This)
  12811. {
  12812. hadThisInitializer = true;
  12813. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  12814. mCurMethodState->LocalDefined(GetThisVariable());
  12815. }
  12816. }
  12817. // Zero out memory for default ctor
  12818. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  12819. {
  12820. if (mCurTypeInstance->IsTypedPrimitive())
  12821. {
  12822. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12823. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12824. }
  12825. else if (mCurTypeInstance->mInstSize > 0)
  12826. {
  12827. BfIRValue fillValue = GetConstValue8(0);
  12828. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12829. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12830. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12831. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12832. }
  12833. }
  12834. BfAstNode* baseCtorNode = NULL;
  12835. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12836. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12837. else if (methodDef->mBody != NULL)
  12838. baseCtorNode = methodDef->mBody;
  12839. else if (ctorDeclaration != NULL)
  12840. baseCtorNode = ctorDeclaration;
  12841. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12842. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12843. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12844. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12845. else
  12846. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12847. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12848. {
  12849. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12850. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12851. {
  12852. BfMethodDef* defaultCtor = NULL;
  12853. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12854. {
  12855. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12856. {
  12857. defaultCtor = methodDef;
  12858. }
  12859. }
  12860. if (defaultCtor != NULL)
  12861. {
  12862. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12863. SetIllegalSrcPos();
  12864. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12865. BfExprEvaluator exprEvaluator(this);
  12866. SizedArray<BfIRValue, 1> irArgs;
  12867. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12868. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12869. }
  12870. }
  12871. }
  12872. // Initialize fields (if applicable)
  12873. if (mCurTypeInstance->IsBoxed())
  12874. {
  12875. skipBody = true;
  12876. }
  12877. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12878. {
  12879. // Field initializers occur in CtorNoBody methods for extensions
  12880. }
  12881. else if (!hadThisInitializer)
  12882. {
  12883. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12884. if ((!mCompiler->mIsResolveOnly) ||
  12885. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12886. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12887. {
  12888. bool hadInlineInitBlock = false;
  12889. BfScopeData scopeData;
  12890. for (auto fieldDef : typeDef->mFields)
  12891. {
  12892. // For extensions, only handle these fields in the appropriate extension
  12893. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12894. continue;
  12895. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12896. {
  12897. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12898. if (!fieldInst->mFieldIncluded)
  12899. continue;
  12900. if (fieldInst->mDataIdx < 0)
  12901. continue;
  12902. if (fieldDef->mInitializer == NULL)
  12903. {
  12904. continue;
  12905. // if (fieldDef->mProtection != BfProtection_Hidden)
  12906. // continue;
  12907. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  12908. // continue;
  12909. }
  12910. if (fieldInst->mResolvedType == NULL)
  12911. {
  12912. BF_ASSERT(mHadBuildError);
  12913. continue;
  12914. }
  12915. if (fieldDef->mInitializer != NULL)
  12916. {
  12917. if (!hadInlineInitBlock)
  12918. {
  12919. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12920. {
  12921. UpdateSrcPos(baseCtorNode);
  12922. if (methodDef->mBody == NULL)
  12923. SetIllegalSrcPos();
  12924. // 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
  12925. EmitEnsureInstructionAt();
  12926. BfType* thisType = mCurTypeInstance;
  12927. if (thisType->IsValueType())
  12928. thisType = CreateRefType(thisType);
  12929. SizedArray<BfIRMDNode, 1> diParamTypes;
  12930. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12931. mCurMethodState->AddScope(&scopeData);
  12932. NewScopeState();
  12933. int flags = 0;
  12934. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12935. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12936. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12937. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12938. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12939. UpdateSrcPos(fieldDef->mInitializer);
  12940. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12941. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12942. //
  12943. {
  12944. auto loadedThis = GetThis();
  12945. // LLVM can't handle two variables pointing to the same value
  12946. BfIRValue copiedThisPtr;
  12947. copiedThisPtr = CreateAlloca(thisType);
  12948. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12949. mBfIRBuilder->ClearDebugLocation(storeInst);
  12950. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12951. }
  12952. hadInlineInitBlock = true;
  12953. }
  12954. }
  12955. UpdateSrcPos(fieldDef->mInitializer);
  12956. }
  12957. BfIRValue fieldAddr;
  12958. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  12959. {
  12960. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12961. }
  12962. else
  12963. {
  12964. // Failed
  12965. }
  12966. auto assignValue = GetFieldInitializerValue(fieldInst);
  12967. if ((fieldAddr) && (assignValue))
  12968. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12969. }
  12970. }
  12971. if (hadInlineInitBlock)
  12972. {
  12973. RestoreScopeState();
  12974. // This gets set to false because of AddScope but we actually are still in the head block
  12975. mCurMethodState->mInHeadScope = true;
  12976. }
  12977. }
  12978. else // Autocomplete case
  12979. {
  12980. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12981. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12982. // resolve pass, NOT the autocomplete expression
  12983. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12984. {
  12985. if (tempTypeDef->mFullName == typeDef->mFullName)
  12986. {
  12987. for (auto fieldDef : tempTypeDef->mFields)
  12988. {
  12989. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12990. {
  12991. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12992. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12993. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12994. if ((wantType != NULL) &&
  12995. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12996. wantType = NULL;
  12997. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12998. }
  12999. }
  13000. }
  13001. }
  13002. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  13003. for (auto fieldDef : typeDef->mFields)
  13004. {
  13005. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  13006. {
  13007. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13008. if (fieldDef->mInitializer != NULL)
  13009. MarkFieldInitialized(fieldInst);
  13010. }
  13011. }
  13012. }
  13013. }
  13014. // Call base ctor (if applicable)
  13015. BfTypeInstance* targetType = NULL;
  13016. BfAstNode* targetRefNode = NULL;
  13017. if (ctorDeclaration != NULL)
  13018. targetRefNode = ctorDeclaration->mInitializer;
  13019. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  13020. targetRefNode = invocationExpr->mTarget;
  13021. if (baseCtorNode != NULL)
  13022. {
  13023. UpdateSrcPos(baseCtorNode);
  13024. if (methodDef->mBody == NULL)
  13025. SetIllegalSrcPos();
  13026. }
  13027. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  13028. {
  13029. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  13030. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13031. }
  13032. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  13033. {
  13034. auto baseType = mCurTypeInstance->mBaseType;
  13035. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  13036. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  13037. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  13038. {
  13039. // Try to find a ctor without any params first
  13040. BfMethodDef* matchedMethod = NULL;
  13041. bool hadCtorWithAllDefaults = false;
  13042. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  13043. for (int pass = 0; pass < 2; pass++)
  13044. {
  13045. baseType->mTypeDef->PopulateMemberSets();
  13046. BfMemberSetEntry* entry = NULL;
  13047. BfMethodDef* checkMethodDef = NULL;
  13048. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  13049. if (entry != NULL)
  13050. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  13051. while (checkMethodDef != NULL)
  13052. {
  13053. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  13054. if (isHiddenGenerated)
  13055. {
  13056. // Allow calling of the default base ctor if it is implicitly defined
  13057. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  13058. allowMethod = true;
  13059. }
  13060. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  13061. {
  13062. if (checkMethodDef->mParams.size() == 0)
  13063. {
  13064. matchedMethod = checkMethodDef;
  13065. }
  13066. else if (isHiddenGenerated)
  13067. {
  13068. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  13069. hadCtorWithAllDefaults = true;
  13070. }
  13071. }
  13072. checkMethodDef = checkMethodDef->mNextWithSameName;
  13073. }
  13074. if (matchedMethod != NULL)
  13075. break;
  13076. }
  13077. if ((HasCompiledOutput()) && (matchedMethod != NULL))
  13078. {
  13079. SizedArray<BfIRValue, 1> args;
  13080. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  13081. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  13082. {
  13083. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  13084. args.push_back(basePtr);
  13085. }
  13086. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  13087. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  13088. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  13089. if (callingConv != BfIRCallingConv_CDecl)
  13090. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  13091. }
  13092. if (matchedMethod == NULL)
  13093. {
  13094. targetType = mCurTypeInstance->mBaseType;
  13095. if (ctorDeclaration != NULL)
  13096. targetRefNode = ctorDeclaration->mThisToken;
  13097. else if (typeDef->mTypeDeclaration != NULL)
  13098. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  13099. }
  13100. }
  13101. }
  13102. if (methodDef->mHasAppend)
  13103. {
  13104. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  13105. }
  13106. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mArguments.size() == 1) && (targetType != NULL))
  13107. {
  13108. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorDeclaration->mInitializer->mArguments[0]))
  13109. {
  13110. if (targetType == mCurTypeInstance)
  13111. {
  13112. auto thisVariable = GetThisVariable();
  13113. if (thisVariable != NULL)
  13114. {
  13115. thisVariable->mUnassignedFieldFlags = 0;
  13116. thisVariable->mIsAssigned = true;
  13117. }
  13118. }
  13119. targetType = NULL;
  13120. }
  13121. }
  13122. if (targetType != NULL)
  13123. {
  13124. BfAstNode* refNode = methodDeclaration;
  13125. if (refNode == NULL)
  13126. refNode = typeDef->mTypeDeclaration;
  13127. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  13128. auto autoComplete = mCompiler->GetAutoComplete();
  13129. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  13130. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  13131. {
  13132. auto invocationExpr = ctorDeclaration->mInitializer;
  13133. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  13134. }
  13135. BfType* targetThisType = targetType;
  13136. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  13137. BfExprEvaluator exprEvaluator(this);
  13138. BfResolvedArgs argValues;
  13139. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  13140. {
  13141. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  13142. if (gDebugStuff)
  13143. {
  13144. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  13145. }
  13146. }
  13147. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  13148. BfTypedValue appendIdxVal;
  13149. if (methodDef->mHasAppend)
  13150. {
  13151. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  13152. BF_ASSERT(localVar->mName == "appendIdx");
  13153. auto intRefType = localVar->mResolvedType;
  13154. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  13155. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  13156. }
  13157. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  13158. if (autoComplete != NULL)
  13159. {
  13160. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  13161. {
  13162. if (autoComplete->mMethodMatchInfo != NULL)
  13163. autoComplete->mIsCapturingMethodMatchInfo = true;
  13164. else
  13165. autoComplete->mIsCapturingMethodMatchInfo = false;
  13166. }
  13167. else
  13168. autoComplete->mIsCapturingMethodMatchInfo = false;
  13169. }
  13170. }
  13171. }
  13172. void BfModule::EmitEnumToStringBody()
  13173. {
  13174. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13175. auto strVal = CreateAlloca(stringType);
  13176. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  13177. BfExprEvaluator exprEvaluator(this);
  13178. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13179. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  13180. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  13181. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  13182. BfType* discriminatorType = NULL;
  13183. BfTypedValue rawPayload;
  13184. BfIRValue enumVal;
  13185. if (mCurTypeInstance->IsPayloadEnum())
  13186. {
  13187. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  13188. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  13189. enumTypedValue = LoadValue(enumTypedValue);
  13190. enumVal = enumTypedValue.mValue;
  13191. rawPayload = ExtractValue(GetThis(), NULL, 1);
  13192. }
  13193. else
  13194. enumVal = mBfIRBuilder->GetArgument(0);
  13195. Array<BfType*> paramTypes;
  13196. paramTypes.Add(stringType);
  13197. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13198. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  13199. HashSet<int64> handledCases;
  13200. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13201. {
  13202. if (fieldInstance.mIsEnumPayloadCase)
  13203. {
  13204. int tagId = -fieldInstance.mDataIdx - 1;
  13205. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13206. mBfIRBuilder->AddBlock(caseBlock);
  13207. mBfIRBuilder->SetInsertPoint(caseBlock);
  13208. BF_ASSERT(discriminatorType->IsPrimitiveType());
  13209. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  13210. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13211. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13212. auto stringDestVal = LoadValue(stringDestAddr);
  13213. SizedArray<BfIRValue, 2> args;
  13214. args.Add(stringDestVal.mValue);
  13215. args.Add(caseStr);
  13216. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13217. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  13218. BF_ASSERT(payloadType->IsTuple());
  13219. if (payloadType->mFieldInstances.size() != 0)
  13220. {
  13221. auto payload = rawPayload;
  13222. if (payload.mType != payloadType)
  13223. {
  13224. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  13225. }
  13226. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  13227. SizedArray<BfIRValue, 2> irArgs;
  13228. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  13229. stringDestVal = LoadValue(stringDestAddr);
  13230. irArgs.Add(stringDestVal.mValue);
  13231. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  13232. }
  13233. mBfIRBuilder->CreateBr(endBlock);
  13234. continue;
  13235. }
  13236. if (fieldInstance.mConstIdx == -1)
  13237. continue;
  13238. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  13239. if (!handledCases.TryAdd(constant->mInt64, NULL))
  13240. {
  13241. // Duplicate
  13242. continue;
  13243. }
  13244. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13245. mBfIRBuilder->AddBlock(caseBlock);
  13246. mBfIRBuilder->SetInsertPoint(caseBlock);
  13247. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  13248. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13249. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13250. mBfIRBuilder->CreateStore(caseStr, strVal);
  13251. mBfIRBuilder->CreateBr(appendBlock);
  13252. }
  13253. mBfIRBuilder->AddBlock(appendBlock);
  13254. mBfIRBuilder->SetInsertPoint(appendBlock);
  13255. SizedArray<BfIRValue, 2> args;
  13256. auto stringDestVal = LoadValue(stringDestAddr);
  13257. args.Add(stringDestVal.mValue);
  13258. args.Add(mBfIRBuilder->CreateLoad(strVal));
  13259. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13260. mBfIRBuilder->CreateBr(endBlock);
  13261. mBfIRBuilder->AddBlock(noMatchBlock);
  13262. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  13263. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  13264. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  13265. args.clear();
  13266. args.Add(int64Val);
  13267. stringDestVal = LoadValue(stringDestAddr);
  13268. args.Add(stringDestVal.mValue);
  13269. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  13270. mBfIRBuilder->CreateBr(endBlock);
  13271. mBfIRBuilder->AddBlock(endBlock);
  13272. mBfIRBuilder->SetInsertPoint(endBlock);
  13273. }
  13274. void BfModule::EmitTupleToStringBody()
  13275. {
  13276. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13277. BfExprEvaluator exprEvaluator(this);
  13278. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13279. Array<BfType*> paramTypes;
  13280. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  13281. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13282. paramTypes.Clear();
  13283. paramTypes.Add(stringType);
  13284. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13285. auto _AppendChar = [&](char c)
  13286. {
  13287. SizedArray<BfIRValue, 2> args;
  13288. auto stringDestVal = LoadValue(stringDestRef);
  13289. args.Add(stringDestVal.mValue);
  13290. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  13291. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  13292. };
  13293. int fieldIdx = 0;
  13294. auto thisValue = GetThis();
  13295. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  13296. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  13297. BfIRValue commaStr;
  13298. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  13299. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  13300. _AppendChar('(');
  13301. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13302. {
  13303. if (fieldInstance.mDataIdx == -1)
  13304. continue;
  13305. if (fieldIdx > 0)
  13306. {
  13307. if (!commaStr)
  13308. commaStr = GetStringObjectValue(", ");
  13309. SizedArray<BfIRValue, 2> args;
  13310. auto stringDestVal = LoadValue(stringDestRef);
  13311. args.Add(stringDestVal.mValue);
  13312. args.Add(commaStr);
  13313. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13314. }
  13315. fieldIdx++;
  13316. if (fieldInstance.mResolvedType->IsValuelessType())
  13317. continue;
  13318. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  13319. if (fieldValue.mType->IsPrimitiveType())
  13320. {
  13321. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  13322. }
  13323. auto typeInstance = fieldValue.mType->ToTypeInstance();
  13324. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  13325. {
  13326. BfExprEvaluator exprEvaluator(this);
  13327. SizedArray<BfResolvedArg, 0> resolvedArgs;
  13328. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  13329. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  13330. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  13331. methodMatcher.TryDevirtualizeCall(fieldValue);
  13332. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  13333. BfResolvedArg resolvedArg;
  13334. auto stringDestVal = LoadValue(stringDestRef);
  13335. resolvedArg.mTypedValue = stringDestVal;
  13336. resolvedArg.mResolvedType = stringDestVal.mType;
  13337. resolvedArgs.Add(resolvedArg);
  13338. exprEvaluator.CreateCall(&methodMatcher, callVal);
  13339. continue;
  13340. }
  13341. if (fieldValue.mType->IsObjectOrInterface())
  13342. {
  13343. BF_ASSERT(!fieldValue.IsAddr());
  13344. SizedArray<BfIRValue, 2> args;
  13345. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  13346. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13347. stringDestVal = LoadValue(stringDestVal);
  13348. args.Add(stringDestVal.mValue);
  13349. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  13350. continue;
  13351. }
  13352. BfExprEvaluator exprEvaluator(this);
  13353. SizedArray<BfResolvedArg, 0> resolvedArgs;
  13354. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  13355. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  13356. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  13357. methodMatcher.TryDevirtualizeCall(fieldValue);
  13358. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  13359. {
  13360. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  13361. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13362. // Just append the type name
  13363. String typeName = TypeToString(fieldInstance.mResolvedType);
  13364. auto strVal = GetStringObjectValue(typeName);
  13365. SizedArray<BfIRValue, 2> args;
  13366. auto stringDestVal = LoadValue(stringDestRef);
  13367. args.Add(stringDestVal.mValue);
  13368. args.Add(strVal);
  13369. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13370. continue;
  13371. }
  13372. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  13373. BfResolvedArg resolvedArg;
  13374. auto stringDestVal = LoadValue(stringDestRef);
  13375. resolvedArg.mTypedValue = stringDestVal;
  13376. resolvedArg.mResolvedType = stringDestVal.mType;
  13377. resolvedArgs.Add(resolvedArg);
  13378. exprEvaluator.CreateCall(&methodMatcher, callVal);
  13379. }
  13380. _AppendChar(')');
  13381. }
  13382. void BfModule::EmitIteratorBlock(bool& skipBody)
  13383. {
  13384. auto methodInstance = mCurMethodInstance;
  13385. auto methodDef = methodInstance->mMethodDef;
  13386. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13387. auto typeDef = mCurTypeInstance->mTypeDef;
  13388. BfType* innerRetType = NULL;
  13389. BfTypeInstance* usingInterface = NULL;
  13390. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  13391. if (retTypeInst != NULL)
  13392. {
  13393. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  13394. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  13395. {
  13396. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  13397. }
  13398. }
  13399. if (innerRetType == NULL)
  13400. {
  13401. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  13402. return;
  13403. }
  13404. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  13405. if (blockBody == NULL)
  13406. return;
  13407. }
  13408. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13409. {
  13410. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  13411. if (fieldTypeInst == NULL)
  13412. return;
  13413. if (!markVal.mType->IsComposite())
  13414. markVal = LoadValue(markVal);
  13415. BfExprEvaluator exprEvaluator(this);
  13416. PopulateType(markVal.mType, BfPopulateType_Data);
  13417. if (markVal.mType->IsObjectOrInterface())
  13418. {
  13419. BfIRValue val = markVal.mValue;
  13420. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  13421. SizedArray<BfIRValue, 1> args;
  13422. args.push_back(val);
  13423. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  13424. }
  13425. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  13426. {
  13427. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  13428. if (markMemberMethodInstance)
  13429. {
  13430. SizedArray<BfIRValue, 1> args;
  13431. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  13432. if (markVal.mType != methodOwner)
  13433. markVal = Cast(NULL, markVal, methodOwner);
  13434. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  13435. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  13436. }
  13437. }
  13438. }
  13439. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  13440. {
  13441. Array<BfMethodInstance*> methodInstances;
  13442. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  13443. {
  13444. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  13445. auto chainedMethodInst = methodInstGroup.mDefault;
  13446. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  13447. {
  13448. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  13449. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  13450. {
  13451. methodInstances.push_back(chainedMethodInst);
  13452. }
  13453. }
  13454. }
  13455. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  13456. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  13457. {
  13458. bool isBetter;
  13459. bool isWorse;
  13460. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  13461. if (isBetter == isWorse)
  13462. {
  13463. return false;
  13464. }
  13465. return isWorse;
  13466. });
  13467. if (reverse)
  13468. std::reverse(methodInstances.begin(), methodInstances.end());
  13469. for (auto chainedMethodInst : methodInstances)
  13470. {
  13471. auto declModule = this;
  13472. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  13473. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  13474. BfExprEvaluator exprEvaluator(this);
  13475. SizedArray<BfIRValue, 1> args;
  13476. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  13477. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  13478. }
  13479. }
  13480. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  13481. {
  13482. BF_ASSERT(mCurMethodInstance->mIsReified);
  13483. if (mCurTypeInstance->mHotTypeData == NULL)
  13484. {
  13485. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  13486. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  13487. }
  13488. auto hotMethod = mCurMethodInstance->mHotMethod;
  13489. for (auto depData : hotMethod->mReferences)
  13490. {
  13491. // Only virtual decls are allowed to already be there
  13492. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  13493. }
  13494. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  13495. int prevSize = (int)hotMethod->mReferences.size();
  13496. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  13497. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  13498. refCount++;
  13499. hotMethod->mReferences.Reserve(refCount);
  13500. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  13501. {
  13502. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  13503. hotThis->mRefCount++;
  13504. hotMethod->mReferences.Insert(0, hotThis);
  13505. prevSize++;
  13506. }
  13507. for (auto val : builder->mAllocatedData)
  13508. {
  13509. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  13510. hotMethod->mReferences.Add(hotAllocation);
  13511. }
  13512. for (auto val : builder->mUsedData)
  13513. hotMethod->mReferences.Add(val);
  13514. for (auto val : builder->mCalledMethods)
  13515. hotMethod->mReferences.Add(val);
  13516. for (auto val : builder->mDevirtualizedCalledMethods)
  13517. {
  13518. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  13519. hotMethod->mReferences.Add(devirtualizedMethod);
  13520. }
  13521. for (auto val : builder->mFunctionPtrs)
  13522. {
  13523. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  13524. hotMethod->mReferences.Add(funcRef);
  13525. }
  13526. for (auto val : builder->mInnerMethods)
  13527. {
  13528. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  13529. hotMethod->mReferences.Add(innerMethod);
  13530. }
  13531. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  13532. {
  13533. auto depData = hotMethod->mReferences[refIdx];
  13534. BF_ASSERT(depData != NULL);
  13535. depData->mRefCount++;
  13536. }
  13537. }
  13538. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  13539. {
  13540. auto methodDef = methodInstance->mMethodDef;
  13541. auto methodDeclaration = methodDef->mMethodDeclaration;
  13542. bool isThisStruct = false;
  13543. if (thisType != NULL)
  13544. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  13545. int argIdx = 0;
  13546. if (argIdx == methodInstance->GetStructRetIdx())
  13547. argIdx++;
  13548. if (!methodDef->mIsStatic)
  13549. {
  13550. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13551. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13552. BfLocalVariable* paramVar = new BfLocalVariable();
  13553. paramVar->mResolvedType = thisType;
  13554. paramVar->mName = "this";
  13555. if (!thisType->IsValuelessType())
  13556. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  13557. else
  13558. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  13559. if ((thisType->IsSplattable()) && (methodInstance->AllowsThisSplatting()))
  13560. {
  13561. if (!thisType->IsTypedPrimitive())
  13562. paramVar->mIsSplat = true;
  13563. }
  13564. else if ((!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  13565. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  13566. auto thisTypeInst = thisType->ToTypeInstance();
  13567. paramVar->mIsStruct = isThisStruct;
  13568. paramVar->mAddr = BfIRValue();
  13569. paramVar->mIsThis = true;
  13570. paramVar->mParamIdx = -1;
  13571. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  13572. {
  13573. paramVar->mIsAssigned = false;
  13574. }
  13575. else
  13576. {
  13577. paramVar->mIsAssigned = true;
  13578. }
  13579. paramVar->mReadFromId = -1;
  13580. paramVar->Init();
  13581. if (methodDeclaration == NULL)
  13582. UseDefaultSrcPos();
  13583. AddLocalVariableDef(paramVar);
  13584. if (!thisType->IsValuelessType())
  13585. {
  13586. if (wantsDIData)
  13587. {
  13588. BfType* thisPtrType = thisType;
  13589. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  13590. if (!thisType->IsValueType())
  13591. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  13592. diParams->push_back(diType);
  13593. }
  13594. if (paramVar->mIsSplat)
  13595. {
  13596. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13597. }
  13598. else
  13599. {
  13600. argIdx++;
  13601. if (loweredTypeCode2 != BfTypeCode_None)
  13602. argIdx++;
  13603. }
  13604. }
  13605. }
  13606. if (argIdx == methodInstance->GetStructRetIdx())
  13607. argIdx++;
  13608. bool hadParams = false;
  13609. bool hasDefault = false;
  13610. int compositeVariableIdx = -1;
  13611. int paramIdx = 0;
  13612. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  13613. {
  13614. // We already issues a type error for this param if we had one in declaration processing
  13615. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  13616. BfLocalVariable* paramVar = new BfLocalVariable();
  13617. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13618. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13619. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  13620. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  13621. if (unresolvedType == NULL)
  13622. {
  13623. AssertErrorState();
  13624. unresolvedType = mContext->mBfObjectType;
  13625. paramVar->mParamFailed = true;
  13626. }
  13627. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  13628. prevIgnoreErrors.Restore();
  13629. PopulateType(resolvedType, BfPopulateType_Declaration);
  13630. paramVar->mResolvedType = resolvedType;
  13631. paramVar->mName = methodInstance->GetParamName(paramIdx);
  13632. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  13633. if (!isParamSkipped)
  13634. {
  13635. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  13636. if (resolvedType->IsMethodRef())
  13637. {
  13638. paramVar->mIsSplat = true;
  13639. }
  13640. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  13641. {
  13642. if (methodInstance->AllowsSplatting())
  13643. {
  13644. int splatCount = resolvedType->GetSplatCount();
  13645. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  13646. paramVar->mIsSplat = true;
  13647. }
  13648. }
  13649. }
  13650. else
  13651. {
  13652. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  13653. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  13654. }
  13655. paramVar->mIsLowered = resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  13656. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  13657. paramVar->mParamIdx = paramIdx;
  13658. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  13659. paramVar->mReadFromId = 0;
  13660. if (resolvedType->IsRef())
  13661. {
  13662. auto refType = (BfRefType*)resolvedType;
  13663. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  13664. }
  13665. else
  13666. {
  13667. paramVar->mIsAssigned = true;
  13668. if (methodDef->mMethodType != BfMethodType_Mixin)
  13669. paramVar->mIsReadOnly = true;
  13670. }
  13671. if (paramVar->mResolvedType->IsGenericParam())
  13672. {
  13673. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  13674. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  13675. {
  13676. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  13677. paramVar->mResolvedType = typedVal.mType;
  13678. paramVar->mConstValue = typedVal.mValue;
  13679. }
  13680. }
  13681. if (paramVar->mResolvedType->IsConstExprValue())
  13682. {
  13683. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  13684. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13685. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  13686. BF_ASSERT(unspecParamType->IsGenericParam());
  13687. if (unspecParamType->IsGenericParam())
  13688. {
  13689. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  13690. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  13691. {
  13692. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  13693. if (genericParamInst->mTypeConstraint != NULL)
  13694. {
  13695. BfExprEvaluator exprEvaluator(this);
  13696. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  13697. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  13698. auto checkType = genericParamInst->mTypeConstraint;
  13699. if (checkType->IsTypedPrimitive())
  13700. checkType = checkType->GetUnderlyingType();
  13701. if (exprEvaluator.mResult.mType == checkType)
  13702. {
  13703. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13704. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  13705. BF_ASSERT(paramVar->mConstValue.IsConst());
  13706. }
  13707. else
  13708. {
  13709. AssertErrorState();
  13710. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13711. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  13712. }
  13713. }
  13714. }
  13715. }
  13716. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  13717. if (paramVar->mResolvedType->IsConstExprValue())
  13718. {
  13719. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  13720. //AssertErrorState();
  13721. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  13722. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  13723. }
  13724. }
  13725. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  13726. {
  13727. if (compositeVariableIdx == -1)
  13728. {
  13729. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  13730. BfLocalVariable* localVar = new BfLocalVariable();
  13731. auto paramInst = &methodInstance->mParams[paramIdx];
  13732. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  13733. localVar->mName = paramDef->mName;
  13734. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13735. localVar->mCompositeCount = 0;
  13736. DoAddLocalVariable(localVar);
  13737. }
  13738. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  13739. }
  13740. CheckVariableDef(paramVar);
  13741. paramVar->Init();
  13742. AddLocalVariableDef(paramVar);
  13743. if (!isParamSkipped)
  13744. {
  13745. if (wantsDIData)
  13746. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  13747. if (paramVar->mIsSplat)
  13748. {
  13749. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13750. }
  13751. else
  13752. {
  13753. argIdx++;
  13754. }
  13755. if (loweredTypeCode2 != BfTypeCode_None)
  13756. argIdx++;
  13757. }
  13758. }
  13759. // Try to find an ending delegate params composite
  13760. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  13761. {
  13762. auto paramDef = methodDef->mParams.back();
  13763. if (paramDef->mParamKind == BfParamKind_Params)
  13764. {
  13765. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13766. if (paramsType == NULL)
  13767. {
  13768. AssertErrorState();
  13769. }
  13770. else if (paramsType->IsGenericParam())
  13771. {
  13772. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  13773. if (genericParamInstance->mTypeConstraint != NULL)
  13774. {
  13775. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  13776. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  13777. ((typeInstConstraint != NULL) &&
  13778. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  13779. {
  13780. BfLocalVariable* localVar = new BfLocalVariable();
  13781. localVar->mName = paramDef->mName;
  13782. localVar->mResolvedType = paramsType;
  13783. localVar->mCompositeCount = 0;
  13784. DoAddLocalVariable(localVar);
  13785. }
  13786. }
  13787. }
  13788. else if (paramsType->IsDelegate())
  13789. {
  13790. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  13791. if (invokeMethodInstance != NULL)
  13792. {
  13793. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  13794. // and wasn't cleared by the preceding loop
  13795. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  13796. BfLocalVariable* localVar = new BfLocalVariable();
  13797. localVar->mName = paramDef->mName;
  13798. localVar->mResolvedType = paramsType;
  13799. localVar->mCompositeCount = 0;
  13800. DoAddLocalVariable(localVar);
  13801. }
  13802. }
  13803. }
  13804. }
  13805. }
  13806. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  13807. {
  13808. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  13809. // return;
  13810. auto _ClearState = [&]()
  13811. {
  13812. mCurMethodState->mLocalMethods.Clear();
  13813. for (auto& local : mCurMethodState->mLocals)
  13814. delete local;
  13815. mCurMethodState->mLocals.Clear();
  13816. mCurMethodState->mLocalVarSet.Clear();
  13817. };
  13818. // 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
  13819. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  13820. // however (compiler bug), so this is the safest way
  13821. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  13822. {
  13823. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  13824. {
  13825. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  13826. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  13827. if (!mHadBuildError)
  13828. {
  13829. // Process as a closure - that allows us to look back and see the const locals and stuff
  13830. BfClosureState closureState;
  13831. mCurMethodState->mClosureState = &closureState;
  13832. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13833. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  13834. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  13835. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  13836. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  13837. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13838. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  13839. _ClearState();
  13840. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  13841. {
  13842. auto localVar = new BfLocalVariable();
  13843. *localVar = constLocal;
  13844. DoAddLocalVariable(localVar);
  13845. }
  13846. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  13847. bool doProcess = !mCompiler->mCanceling;
  13848. if (doProcess)
  13849. {
  13850. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  13851. ProcessMethod(deferredLocalMethod->mMethodInstance);
  13852. }
  13853. }
  13854. delete deferredLocalMethod;
  13855. mSystem->CheckLockYield();
  13856. }
  13857. }
  13858. for (auto& kv : mCurMethodState->mLocalMethodCache)
  13859. {
  13860. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  13861. }
  13862. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  13863. {
  13864. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  13865. {
  13866. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  13867. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  13868. BfClosureState closureState;
  13869. mCurMethodState->mClosureState = &closureState;
  13870. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13871. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  13872. if (lambdaInstance->mClosureTypeInstance != NULL)
  13873. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13874. else
  13875. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13876. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13877. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  13878. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13879. _ClearState();
  13880. for (auto& constLocal : lambdaInstance->mConstLocals)
  13881. {
  13882. //if (constLocal.mIsThis)
  13883. {
  13884. // Valueless 'this'
  13885. closureState.mConstLocals.Add(constLocal);
  13886. }
  13887. /*else
  13888. {
  13889. auto localVar = new BfLocalVariable();
  13890. *localVar = constLocal;
  13891. DoAddLocalVariable(localVar);
  13892. }*/
  13893. }
  13894. BfMethodInstanceGroup methodInstanceGroup;
  13895. methodInstanceGroup.mOwner = mCurTypeInstance;
  13896. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13897. bool doProcess = !mCompiler->mCanceling;
  13898. if (doProcess)
  13899. {
  13900. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13901. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13902. ProcessMethod(lambdaInstance->mMethodInstance);
  13903. if (lambdaInstance->mDtorMethodInstance != NULL)
  13904. {
  13905. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13906. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13907. }
  13908. }
  13909. }
  13910. mSystem->CheckLockYield();
  13911. }
  13912. }
  13913. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13914. {
  13915. if (checkType->IsComposite())
  13916. PopulateType(checkType, BfPopulateType_Data);
  13917. if (!checkType->WantsGCMarking())
  13918. return;
  13919. auto typeInstance = checkType->ToTypeInstance();
  13920. bool callMarkMethod = false;
  13921. // Call the actual marking method
  13922. if (memberDepth == 0)
  13923. {
  13924. // Don't call marking method on self
  13925. }
  13926. else if (checkType->IsObjectOrInterface())
  13927. {
  13928. if (!objectOffsets.Add(curOffset))
  13929. {
  13930. return;
  13931. }
  13932. callMarkMethod = true;
  13933. }
  13934. else if (checkType->IsSizedArray())
  13935. {
  13936. callMarkMethod = true;
  13937. }
  13938. else if (typeInstance != NULL)
  13939. {
  13940. typeInstance->mTypeDef->PopulateMemberSets();
  13941. BfMemberSetEntry* entry = NULL;
  13942. BfMethodDef* methodDef = NULL;
  13943. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13944. {
  13945. methodDef = (BfMethodDef*)entry->mMemberDef;
  13946. if (methodDef->HasBody())
  13947. {
  13948. callMarkMethod = true;
  13949. }
  13950. }
  13951. }
  13952. if (callMarkMethod)
  13953. {
  13954. BfTypedValue markValue;
  13955. auto memberType = checkType;
  13956. if (memberType->IsObjectOrInterface())
  13957. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13958. auto memberPtrType = CreatePointerType(memberType);
  13959. if (curOffset == 0)
  13960. {
  13961. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13962. }
  13963. else
  13964. {
  13965. if (!thisValue.mType->IsPointer())
  13966. {
  13967. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13968. auto int8PtrType = CreatePointerType(int8Type);
  13969. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13970. }
  13971. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13972. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13973. }
  13974. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13975. return;
  13976. }
  13977. auto methodDef = mCurMethodInstance->mMethodDef;
  13978. if (checkType->IsPayloadEnum())
  13979. {
  13980. for (auto& fieldInst : typeInstance->mFieldInstances)
  13981. {
  13982. if (!fieldInst.mIsEnumPayloadCase)
  13983. continue;
  13984. auto fieldDef = fieldInst.GetFieldDef();
  13985. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13986. }
  13987. return;
  13988. }
  13989. if (typeInstance == NULL)
  13990. return;
  13991. for (auto& fieldInst : typeInstance->mFieldInstances)
  13992. {
  13993. auto fieldDef = fieldInst.GetFieldDef();
  13994. if (fieldDef == NULL)
  13995. continue;
  13996. if (fieldDef->mIsStatic)
  13997. continue;
  13998. if (typeInstance == mCurTypeInstance)
  13999. {
  14000. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  14001. // we may be marking member values that can never contain a value anyway, but this is benign
  14002. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14003. continue;
  14004. }
  14005. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  14006. }
  14007. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  14008. {
  14009. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  14010. }
  14011. }
  14012. void BfModule::EmitGCMarkMembers()
  14013. {
  14014. auto methodDef = mCurMethodInstance->mMethodDef;
  14015. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  14016. BfModuleMethodInstance markFromGCThreadMethodInstance;
  14017. if (gcType != NULL)
  14018. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  14019. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  14020. {
  14021. if (mCurTypeInstance->IsBoxed())
  14022. {
  14023. // This already gets filled in by the normal boxed forwarding
  14024. }
  14025. else
  14026. {
  14027. auto thisValue = GetThis();
  14028. if (thisValue.IsSplat())
  14029. {
  14030. BfIRFunction func = mCurMethodInstance->mIRFunction;
  14031. int argIdx = 0;
  14032. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  14033. {
  14034. if (checkType->IsStruct())
  14035. {
  14036. auto checkTypeInstance = checkType->ToTypeInstance();
  14037. if (checkTypeInstance->mBaseType != NULL)
  14038. checkTypeLambda(checkTypeInstance->mBaseType);
  14039. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14040. {
  14041. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14042. if (fieldInstance->mDataIdx >= 0)
  14043. checkTypeLambda(fieldInstance->GetResolvedType());
  14044. }
  14045. }
  14046. else if (checkType->IsMethodRef())
  14047. {
  14048. BFMODULE_FATAL(this, "Not handled");
  14049. }
  14050. else if (checkType->WantsGCMarking())
  14051. {
  14052. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  14053. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  14054. argIdx++;
  14055. }
  14056. };
  14057. checkTypeLambda(thisValue.mType);
  14058. }
  14059. else if (!methodDef->mIsStatic)
  14060. {
  14061. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  14062. {
  14063. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  14064. if (moduleMethodInst)
  14065. {
  14066. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  14067. if (methodBaseType != mContext->mBfObjectType)
  14068. {
  14069. auto thisValue = GetThis();
  14070. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  14071. SizedArray<BfIRValue, 1> args;
  14072. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  14073. {
  14074. BfExprEvaluator exprEvaluator(this);
  14075. exprEvaluator.SplatArgs(baseValue, args);
  14076. }
  14077. else
  14078. {
  14079. args.push_back(baseValue.mValue);
  14080. }
  14081. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  14082. }
  14083. }
  14084. }
  14085. }
  14086. if (!methodDef->mIsStatic)
  14087. {
  14088. HashSet<int> objectOffsets;
  14089. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  14090. }
  14091. else
  14092. {
  14093. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14094. {
  14095. if (thisValue.IsSplat())
  14096. break;
  14097. auto fieldDef = fieldInst.GetFieldDef();
  14098. if (fieldDef == NULL)
  14099. continue;
  14100. if (fieldInst.mIsThreadLocal)
  14101. continue;
  14102. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  14103. {
  14104. // For extensions, only handle these fields in the appropriate extension
  14105. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14106. continue;
  14107. if (!fieldInst.mFieldIncluded)
  14108. continue;
  14109. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  14110. if (fieldTypeInst != NULL)
  14111. {
  14112. auto fieldDef = fieldInst.GetFieldDef();
  14113. BfTypedValue markVal;
  14114. if (fieldDef->mIsConst)
  14115. continue;
  14116. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  14117. continue;
  14118. mBfIRBuilder->PopulateType(fieldTypeInst);
  14119. if (fieldTypeInst->IsValuelessType())
  14120. continue;
  14121. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14122. {
  14123. markVal = ReferenceStaticField(&fieldInst);
  14124. }
  14125. else if (!fieldDef->mIsStatic)
  14126. {
  14127. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  14128. }
  14129. if (markVal)
  14130. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  14131. }
  14132. }
  14133. }
  14134. }
  14135. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14136. CallChainedMethods(mCurMethodInstance, false);
  14137. }
  14138. }
  14139. }
  14140. void BfModule::EmitGCFindTLSMembers()
  14141. {
  14142. auto methodDef = mCurMethodInstance->mMethodDef;
  14143. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  14144. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  14145. BF_ASSERT(reportTLSMark);
  14146. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14147. {
  14148. auto fieldDef = fieldInst.GetFieldDef();
  14149. if (fieldDef == NULL)
  14150. continue;
  14151. if (!fieldInst.mIsThreadLocal)
  14152. continue;
  14153. // For extensions, only handle these fields in the appropriate extension
  14154. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14155. continue;
  14156. if (!fieldInst.mFieldIncluded)
  14157. continue;
  14158. if (fieldDef->mIsConst)
  14159. continue;
  14160. auto fieldType = fieldInst.mResolvedType;
  14161. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  14162. continue;
  14163. if (fieldType->IsValuelessType())
  14164. continue;
  14165. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  14166. if (markVal)
  14167. {
  14168. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  14169. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  14170. SizedArray<BfIRValue, 2> llvmArgs;
  14171. llvmArgs.push_back(fieldRefPtr);
  14172. llvmArgs.push_back(markFuncPtr);
  14173. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  14174. }
  14175. }
  14176. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14177. CallChainedMethods(mCurMethodInstance, false);
  14178. }
  14179. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  14180. {
  14181. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  14182. if (mAwaitingInitFinish)
  14183. FinishInit();
  14184. if (!methodInstance->mIsReified)
  14185. BF_ASSERT(!mIsReified);
  14186. if (methodInstance->mMethodInfoEx != NULL)
  14187. {
  14188. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  14189. {
  14190. if (methodGenericArg->IsMethodRef())
  14191. {
  14192. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  14193. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  14194. }
  14195. }
  14196. }
  14197. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  14198. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  14199. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  14200. {
  14201. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  14202. }
  14203. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  14204. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  14205. (mCompiler->mResolvePassData != NULL))
  14206. {
  14207. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  14208. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  14209. }
  14210. if (methodInstance->mHasBeenProcessed)
  14211. {
  14212. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  14213. return;
  14214. }
  14215. if (methodInstance->mFailedConstraints)
  14216. {
  14217. // The only way this should be able to happen is if we fail our generic param check
  14218. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  14219. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  14220. methodInstance->mHasBeenProcessed = true;
  14221. return;
  14222. }
  14223. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  14224. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  14225. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  14226. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  14227. {
  14228. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  14229. auto owningModule = methodInstance->GetOwner()->mModule;
  14230. if (owningModule->mIsScratchModule)
  14231. {
  14232. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  14233. }
  14234. else
  14235. {
  14236. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  14237. if (owningModule->mOnDemandMethodCount > 0)
  14238. owningModule->mOnDemandMethodCount--;
  14239. }
  14240. }
  14241. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  14242. // self-referencing append allocations in ctor@calcAppend
  14243. methodInstance->mHasBeenProcessed = true;
  14244. mIncompleteMethodCount--;
  14245. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  14246. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  14247. auto methodDef = methodInstance->mMethodDef;
  14248. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14249. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  14250. {
  14251. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  14252. // so we get the new vdata for it
  14253. methodInstance->GetOwner()->mDirty = true;
  14254. }
  14255. int dependentGenericStartIdx = 0;
  14256. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  14257. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  14258. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  14259. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  14260. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14261. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  14262. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  14263. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  14264. if ((methodInstance->mIsReified) &&
  14265. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  14266. {
  14267. mCurTypeInstance->mHasBeenInstantiated = true;
  14268. }
  14269. // Warnings are shown in the capture phase
  14270. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  14271. mIgnoreWarnings = true;
  14272. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  14273. UseDefaultSrcPos();
  14274. // We may not actually be populated in relatively rare autocompelte cases
  14275. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  14276. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  14277. BfAstNode* nameNode = NULL;
  14278. if (methodDeclaration != NULL)
  14279. {
  14280. nameNode = methodDeclaration->mNameNode;
  14281. if (nameNode == NULL)
  14282. {
  14283. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  14284. nameNode = ctorDeclaration->mThisToken;
  14285. }
  14286. }
  14287. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  14288. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  14289. {
  14290. if (methodInstance->GetExplicitInterface() == NULL)
  14291. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  14292. else
  14293. {
  14294. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  14295. {
  14296. auto ifaceInst = ifaceEntry.mInterfaceType;
  14297. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  14298. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  14299. if (methodInstance->GetExplicitInterface() != ifaceInst)
  14300. continue;
  14301. ifaceInst->mTypeDef->PopulateMemberSets();
  14302. BfMethodDef* nextMethod = NULL;
  14303. BfMemberSetEntry* entry = NULL;
  14304. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  14305. nextMethod = (BfMethodDef*)entry->mMemberDef;
  14306. while (nextMethod != NULL)
  14307. {
  14308. auto checkMethod = nextMethod;
  14309. nextMethod = nextMethod->mNextWithSameName;
  14310. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  14311. if (implMethodInst == methodInstance)
  14312. {
  14313. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  14314. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  14315. }
  14316. }
  14317. }
  14318. }
  14319. if (methodDef->mIsOverride)
  14320. {
  14321. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  14322. {
  14323. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  14324. if (ventry.mDeclaringMethod.mMethodNum == -1)
  14325. continue;
  14326. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  14327. if (virtMethod != NULL)
  14328. {
  14329. if (virtMethod == methodInstance)
  14330. {
  14331. // Is matching method
  14332. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  14333. {
  14334. auto baseType = mCurTypeInstance->mBaseType;
  14335. if (baseType != NULL)
  14336. {
  14337. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  14338. baseType = baseType->mBaseType;
  14339. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  14340. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  14341. }
  14342. }
  14343. break;
  14344. }
  14345. }
  14346. }
  14347. }
  14348. }
  14349. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  14350. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  14351. {
  14352. if (mBfIRBuilder->mIgnoreWrites)
  14353. return;
  14354. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  14355. if (!methodInstance->mIRFunction)
  14356. {
  14357. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  14358. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  14359. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  14360. }
  14361. if (HasCompiledOutput())
  14362. {
  14363. BfDllImportEntry dllImportEntry;
  14364. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  14365. dllImportEntry.mMethodInstance = mCurMethodInstance;
  14366. mDllImportEntries.push_back(dllImportEntry);
  14367. }
  14368. return;
  14369. }
  14370. StringT<128> mangledName;
  14371. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  14372. if (!methodInstance->mIRFunction)
  14373. {
  14374. bool isIntrinsic = false;
  14375. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  14376. }
  14377. if (methodInstance->mIsIntrinsic)
  14378. return;
  14379. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  14380. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  14381. if (methodDef->mBody != NULL)
  14382. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  14383. else if (methodDeclaration != NULL)
  14384. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  14385. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14386. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  14387. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  14388. {
  14389. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  14390. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  14391. {
  14392. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  14393. }
  14394. }
  14395. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  14396. BfMethodState methodState;
  14397. if (mCurMethodState != NULL)
  14398. methodState.mClosureState = mCurMethodState->mClosureState;
  14399. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  14400. {
  14401. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  14402. if (methodInstance->mHotMethod == NULL)
  14403. CheckHotMethod(methodInstance, mangledName);
  14404. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  14405. }
  14406. methodState.mPrevMethodState = mCurMethodState;
  14407. methodState.mMethodInstance = methodInstance;
  14408. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14409. if (methodInstance->GetCustomAttributes() != NULL)
  14410. {
  14411. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  14412. if (typeOptionsIdx != -1)
  14413. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  14414. }
  14415. BfTypeState typeState(mCurTypeInstance);
  14416. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  14417. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  14418. BfMethodInstance* unspecializedMethodInstance = NULL;
  14419. if ((prevMethodState.mPrevVal != NULL) &&
  14420. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  14421. {
  14422. // This is 'inner' (probably a closure) - use binding from outer function
  14423. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  14424. }
  14425. else if ((methodInstance->mIsUnspecialized) ||
  14426. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  14427. {
  14428. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  14429. }
  14430. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  14431. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  14432. {
  14433. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  14434. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  14435. if (!unspecializedMethodInstance->mHasBeenProcessed)
  14436. {
  14437. // Make sure the unspecialized method is processed so we can take its bindings
  14438. // Clear mCurMethodState so we don't think we're in a local method
  14439. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  14440. mContext->ProcessMethod(unspecializedMethodInstance);
  14441. }
  14442. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  14443. }
  14444. if (methodDef->mMethodType == BfMethodType_Operator)
  14445. {
  14446. auto operatorDef = (BfOperatorDef*) methodDef;
  14447. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  14448. auto paramErrorRefNode = refNode;
  14449. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  14450. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  14451. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  14452. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  14453. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  14454. {
  14455. if (methodDef->mParams.size() != 2)
  14456. {
  14457. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  14458. }
  14459. else
  14460. {
  14461. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  14462. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  14463. {
  14464. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  14465. }
  14466. }
  14467. BfType* wantType = NULL;
  14468. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  14469. {
  14470. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  14471. }
  14472. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  14473. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  14474. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  14475. }
  14476. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  14477. {
  14478. if (methodDef->mParams.size() != 1)
  14479. {
  14480. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  14481. }
  14482. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  14483. {
  14484. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  14485. }
  14486. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  14487. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  14488. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  14489. {
  14490. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  14491. }
  14492. }
  14493. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  14494. {
  14495. if (methodDef->mParams.size() != 1)
  14496. {
  14497. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  14498. }
  14499. if (!mCurMethodInstance->mReturnType->IsVoid())
  14500. {
  14501. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  14502. }
  14503. }
  14504. else // Conversion
  14505. {
  14506. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  14507. {
  14508. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  14509. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  14510. }
  14511. if (methodDef->mParams.size() != 1)
  14512. {
  14513. auto refNode = paramErrorRefNode;
  14514. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  14515. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  14516. Fail("Conversion operators must declare one parameter", refNode);
  14517. }
  14518. else
  14519. {
  14520. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  14521. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  14522. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  14523. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  14524. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  14525. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  14526. // happened here
  14527. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  14528. {
  14529. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  14530. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  14531. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  14532. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  14533. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  14534. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  14535. }
  14536. }
  14537. }
  14538. }
  14539. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  14540. if (methodDef->mMethodType == BfMethodType_Mixin)
  14541. wantsDIData = false;
  14542. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  14543. wantsDIData = false;
  14544. bool wantsDIVariables = wantsDIData;
  14545. if (methodDef->mIsExtern)
  14546. wantsDIVariables = false;
  14547. SizedArray<BfIRMDNode, 8> diParams;
  14548. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  14549. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  14550. BfType* thisType = NULL;
  14551. if (!methodDef->mIsStatic)
  14552. {
  14553. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  14554. thisType = methodState.mClosureState->mClosureType;
  14555. else
  14556. thisType = mCurTypeInstance;
  14557. }
  14558. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  14559. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  14560. //////////////////////////////////////////////////////////////////////////
  14561. //
  14562. {
  14563. if (methodDeclaration != NULL)
  14564. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  14565. else if (methodDef->mBody != NULL)
  14566. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  14567. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14568. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  14569. }
  14570. BfIRMDNode diFunction;
  14571. if (wantsDIData)
  14572. {
  14573. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  14574. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  14575. int defLine = mCurFilePosition.mCurLine;
  14576. if (mDICompileUnit)
  14577. {
  14578. int flags = 0;
  14579. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  14580. if (methodDef->mProtection == BfProtection_Public)
  14581. flags = llvm::DINode::FlagPublic;
  14582. else if (methodDef->mProtection == BfProtection_Protected)
  14583. flags = llvm::DINode::FlagProtected;
  14584. else
  14585. flags = llvm::DINode::FlagPrivate;
  14586. if (methodDef->mIsOverride)
  14587. {
  14588. //flags |= llvm::DINode::FlagVirtual;
  14589. }
  14590. else if (methodDef->mIsVirtual)
  14591. flags |= llvm::DINode::FlagIntroducedVirtual;
  14592. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  14593. flags |= llvm::DINode::FlagStaticMember;
  14594. else
  14595. {
  14596. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  14597. flags |= llvm::DINode::FlagStaticMember;
  14598. }
  14599. flags |= llvm::DINode::FlagPrototyped;
  14600. if (methodDef->mMethodType == BfMethodType_Ctor)
  14601. {
  14602. flags |= llvm::DINode::FlagArtificial;
  14603. }
  14604. auto llvmFunction = methodInstance->mIRFunction;
  14605. SizedArray<BfIRMDNode, 1> genericArgs;
  14606. SizedArray<BfIRValue, 1> genericConstValueArgs;
  14607. String methodName;
  14608. if (methodInstance->GetForeignType() != NULL)
  14609. {
  14610. methodName += TypeToString(methodInstance->GetForeignType());
  14611. methodName += ".";
  14612. }
  14613. if (methodInstance->GetExplicitInterface() != NULL)
  14614. {
  14615. methodName += TypeToString(methodInstance->GetExplicitInterface());
  14616. methodName += ".";
  14617. }
  14618. methodName += methodDef->mName;
  14619. if (methodInstance->GetNumGenericArguments() != 0)
  14620. {
  14621. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  14622. {
  14623. if (genericArg->IsConstExprValue())
  14624. {
  14625. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  14626. while (genericConstValueArgs.size() < genericArgs.size())
  14627. genericConstValueArgs.push_back(BfIRValue());
  14628. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  14629. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  14630. }
  14631. else
  14632. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  14633. }
  14634. methodName += "<";
  14635. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  14636. {
  14637. if (i > 0)
  14638. methodName += ", ";
  14639. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  14640. methodName += TypeToString(type);
  14641. }
  14642. methodName += ">";
  14643. }
  14644. if ((methodName.empty()) && (methodDeclaration != NULL))
  14645. {
  14646. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14647. {
  14648. methodName += "operator";
  14649. if (operatorDecl->mIsConvOperator)
  14650. {
  14651. methodName += " ";
  14652. methodName += TypeToString(methodInstance->mReturnType);
  14653. }
  14654. else if (operatorDecl->mOpTypeToken != NULL)
  14655. methodName += operatorDecl->mOpTypeToken->ToString();
  14656. }
  14657. }
  14658. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  14659. methodName += "$CHK";
  14660. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  14661. methodName += "$UCHK";
  14662. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  14663. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  14664. // defLine + 1, diFuncType, false, true,
  14665. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  14666. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  14667. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  14668. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  14669. defLine + 1, diFuncType, false, true,
  14670. llvm::dwarf::DW_VIRTUALITY_none,
  14671. 0,
  14672. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  14673. }
  14674. }
  14675. //////////////////////////////////////////////////////////////////////////
  14676. // Head and Init get rolled into Entry afterwards.
  14677. methodState.mIRFunction = methodInstance->mIRFunction;
  14678. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  14679. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  14680. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  14681. methodState.mCurScope->mDIScope = diFunction;
  14682. auto llvmEntryBlock = methodState.mIREntryBlock;
  14683. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  14684. if (methodDef->mName == "__MALFORMED")
  14685. {
  14686. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  14687. mBfIRBuilder->SetInsertPoint(newBlock);
  14688. }
  14689. if (methodDef->mBody != NULL)
  14690. {
  14691. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  14692. }
  14693. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  14694. {
  14695. // We want to be able to step into delegate invokes -- we actually step over them
  14696. if (methodDef->mName != "Invoke")
  14697. {
  14698. UpdateSrcPos(typeDef->mTypeDeclaration);
  14699. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  14700. }
  14701. }
  14702. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14703. mBfIRBuilder->ClearDebugLocation();
  14704. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  14705. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  14706. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  14707. {
  14708. int localIdx = 0;
  14709. int argIdx = 0;
  14710. Array<BfIRValue> splatAddrValues;
  14711. for ( ; argIdx < irParamCount; localIdx++)
  14712. {
  14713. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14714. if ((isThis) && (thisType->IsValuelessType()))
  14715. isThis = false;
  14716. if (methodInstance->GetStructRetIdx() == argIdx)
  14717. {
  14718. argIdx++;
  14719. if (argIdx == irParamCount)
  14720. break;
  14721. }
  14722. BfLocalVariable* paramVar = NULL;
  14723. while (true)
  14724. {
  14725. BF_ASSERT(localIdx < methodState.mLocals.size());
  14726. paramVar = methodState.mLocals[localIdx];
  14727. if ((paramVar->mCompositeCount == -1) &&
  14728. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  14729. break;
  14730. localIdx++;
  14731. }
  14732. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  14733. {
  14734. paramVar->mIsReadOnly = true;
  14735. }
  14736. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter));
  14737. if (paramVar->mResolvedType->IsMethodRef())
  14738. wantsAddr = false;
  14739. // if ((methodDef->mHasAppend) && (argIdx == 1))
  14740. // {
  14741. // BF_ASSERT(paramVar->mName == "appendIdx");
  14742. // wantsAddr = true;
  14743. // }
  14744. if (paramVar->mIsSplat)
  14745. {
  14746. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14747. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14748. BfTypeUtils::SplatIterate([&](BfType* checkType)
  14749. {
  14750. BfIRType splatIRType;
  14751. if (checkType->IsComposite())
  14752. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  14753. else
  14754. splatIRType = mBfIRBuilder->MapType(checkType);
  14755. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  14756. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  14757. if (!paramVar->mAddr)
  14758. paramVar->mAddr = allocaInst;
  14759. if (WantsLifetimes())
  14760. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14761. splatAddrValues.push_back(allocaInst);
  14762. }, paramVar->mResolvedType);
  14763. mBfIRBuilder->SetInsertPoint(prevInsert);
  14764. }
  14765. else if (isThis)
  14766. {
  14767. if (wantsAddr)
  14768. {
  14769. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14770. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14771. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  14772. if (paramVar->mIsSplat)
  14773. {
  14774. //
  14775. }
  14776. else
  14777. {
  14778. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  14779. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14780. wantPtr = true;
  14781. if (wantPtr)
  14782. {
  14783. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  14784. }
  14785. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14786. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14787. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  14788. paramVar->mAddr = allocaInst;
  14789. if (WantsLifetimes())
  14790. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14791. }
  14792. mBfIRBuilder->SetInsertPoint(prevInsert);
  14793. }
  14794. }
  14795. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  14796. {
  14797. // Address doesn't change so we don't have to alloca it
  14798. BfIRType allocType;
  14799. int alignSize = mSystem->mPtrSize;
  14800. if (paramVar->mResolvedType->IsRef())
  14801. {
  14802. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14803. }
  14804. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  14805. {
  14806. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14807. alignSize = paramVar->mResolvedType->mAlign;
  14808. }
  14809. else
  14810. {
  14811. paramVar->mHasLocalStructBacking = true;
  14812. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  14813. if (typeInst != NULL)
  14814. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  14815. else
  14816. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  14817. }
  14818. if (wantsAddr)
  14819. {
  14820. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14821. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14822. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14823. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  14824. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14825. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  14826. paramVar->mAddr = allocaInst;
  14827. mBfIRBuilder->SetInsertPoint(prevInsert);
  14828. if (WantsLifetimes())
  14829. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14830. }
  14831. }
  14832. else if (wantsAddr)
  14833. {
  14834. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  14835. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14836. paramVar->mAddr = allocaInst;
  14837. }
  14838. if (paramVar->mIsSplat)
  14839. {
  14840. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14841. }
  14842. else if (paramVar->mIsLowered)
  14843. {
  14844. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14845. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14846. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  14847. argIdx++;
  14848. if (loweredTypeCode2 != BfTypeCode_None)
  14849. argIdx++;
  14850. }
  14851. else
  14852. {
  14853. argIdx++;
  14854. }
  14855. }
  14856. if (methodDef->mBody != NULL)
  14857. UpdateSrcPos(methodDef->mBody);
  14858. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14859. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  14860. int declArgIdx = 0;
  14861. localIdx = 0;
  14862. argIdx = 0;
  14863. int splatAddrIdx = 0;
  14864. while (localIdx < (int)methodState.mLocals.size())
  14865. {
  14866. if (argIdx == methodInstance->GetStructRetIdx())
  14867. argIdx++;
  14868. int curLocalIdx = localIdx++;
  14869. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  14870. if (!paramVar->IsParam())
  14871. continue;
  14872. if (paramVar->mCompositeCount != -1)
  14873. continue;
  14874. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14875. if ((isThis) && (thisType->IsValuelessType()))
  14876. isThis = false;
  14877. BfIRMDNode diVariable;
  14878. if (wantsDIData)
  14879. {
  14880. String paramName = paramVar->mName;
  14881. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14882. if (isThis)
  14883. {
  14884. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  14885. paramName = "__closure";
  14886. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14887. {
  14888. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14889. bool wantRef = paramVar->mResolvedType->IsComposite();
  14890. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14891. wantRef = true;
  14892. if (wantRef)
  14893. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14894. }
  14895. else if (!paramVar->mResolvedType->IsValueType())
  14896. {
  14897. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14898. }
  14899. }
  14900. else
  14901. {
  14902. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14903. {
  14904. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14905. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14906. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14907. }
  14908. }
  14909. if (!paramVar->mIsSplat)
  14910. {
  14911. if (paramVar->mResolvedType->IsValuelessType())
  14912. {
  14913. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14914. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14915. }
  14916. else if (paramVar->mIsImplicitParam)
  14917. {
  14918. // Annotate this specially?
  14919. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14920. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14921. }
  14922. else
  14923. {
  14924. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14925. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14926. }
  14927. paramVar->mDbgVarInst = diVariable;
  14928. }
  14929. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14930. {
  14931. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14932. // {
  14933. // // Only add this placeholder if we don't have any values
  14934. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14935. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14936. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14937. // }
  14938. }
  14939. }
  14940. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14941. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14942. {
  14943. // Write our argument value into the .addr
  14944. mBfIRBuilder->ClearDebugLocation();
  14945. if (paramVar->mIsSplat)
  14946. {
  14947. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14948. //
  14949. }
  14950. else
  14951. {
  14952. bool handled = false;
  14953. if (paramVar->mIsLowered)
  14954. {
  14955. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14956. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14957. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  14958. {
  14959. // We have a lowered type coming in, so we have to cast the .addr before storing
  14960. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  14961. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  14962. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  14963. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  14964. if (loweredTypeCode2 != BfTypeCode_None)
  14965. {
  14966. declArgIdx++;
  14967. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  14968. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  14969. BfIRValue primPtrVal2;
  14970. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  14971. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  14972. else
  14973. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  14974. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  14975. }
  14976. // We don't want to allow directly using value
  14977. paramVar->mValue = BfIRValue();
  14978. handled = true;
  14979. }
  14980. else
  14981. {
  14982. BF_ASSERT("Expected lowered");
  14983. }
  14984. }
  14985. if (!handled)
  14986. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14987. }
  14988. }
  14989. if (!isThis)
  14990. declArgIdx++;
  14991. if (methodDef->mBody != NULL)
  14992. UpdateSrcPos(methodDef->mBody);
  14993. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14994. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14995. else if (methodDeclaration == NULL)
  14996. UseDefaultSrcPos();
  14997. // Write our argument value into the .addr
  14998. if (paramVar->mIsSplat)
  14999. {
  15000. int splatComponentIdx = 0;
  15001. auto curArgIdx = argIdx;
  15002. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  15003. {
  15004. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  15005. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  15006. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  15007. mBfIRBuilder->ClearDebugLocation(storeInst);
  15008. if (wantsDIData)
  15009. {
  15010. BfIRMDNode diType;
  15011. if (checkType->IsComposite())
  15012. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  15013. else
  15014. diType = mBfIRBuilder->DbgGetType(checkType);
  15015. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15016. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15017. if (wantsDIVariables)
  15018. {
  15019. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  15020. }
  15021. }
  15022. curArgIdx++;
  15023. splatComponentIdx++;
  15024. };
  15025. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  15026. {
  15027. if (checkType->IsStruct())
  15028. {
  15029. auto checkTypeInstance = checkType->ToTypeInstance();
  15030. if (checkTypeInstance->mBaseType != NULL)
  15031. {
  15032. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  15033. }
  15034. if (checkTypeInstance->mIsUnion)
  15035. {
  15036. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  15037. if (!unionInnerType->IsValuelessType())
  15038. {
  15039. _FinishSplatsIterate(unionInnerType, name + "$u");
  15040. }
  15041. if (checkTypeInstance->IsEnum())
  15042. {
  15043. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  15044. _FinishSplatsIterate(dscrType, name + "$d");
  15045. }
  15046. }
  15047. else
  15048. {
  15049. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15050. {
  15051. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15052. auto fieldDef = fieldInstance->GetFieldDef();
  15053. if (fieldInstance->mDataIdx >= 0)
  15054. {
  15055. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  15056. }
  15057. }
  15058. }
  15059. }
  15060. else if (checkType->IsMethodRef())
  15061. {
  15062. auto methodRefType = (BfMethodRefType*)checkType;
  15063. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  15064. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  15065. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  15066. // {
  15067. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  15068. // if (!paramType->IsValuelessType())
  15069. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  15070. // }
  15071. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  15072. {
  15073. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15074. String paramName = methodInstance->GetParamName(paramIdx);
  15075. if (paramName == "this")
  15076. paramName = "__this";
  15077. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15078. {
  15079. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15080. }
  15081. else
  15082. {
  15083. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15084. }
  15085. }
  15086. }
  15087. else if (!checkType->IsValuelessType())
  15088. {
  15089. _FinishSplats(checkType, name);
  15090. }
  15091. };
  15092. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15093. if (!paramVar->mConstValue)
  15094. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  15095. }
  15096. BfIRValue declareCall;
  15097. if (diVariable)
  15098. {
  15099. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  15100. {
  15101. if (!paramVar->mAddr)
  15102. {
  15103. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  15104. {
  15105. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15106. {
  15107. // We don't need to set the location for this
  15108. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15109. }
  15110. }
  15111. else
  15112. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  15113. }
  15114. else
  15115. {
  15116. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  15117. }
  15118. }
  15119. }
  15120. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  15121. {
  15122. // We don't allow actually assignment to "this", so we just do a single load
  15123. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  15124. // we need to store it in the stack frame for debugging purposes
  15125. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  15126. mBfIRBuilder->ClearDebugLocation(loadedThis);
  15127. paramVar->mValue = loadedThis;
  15128. }
  15129. if ((wantsDIData) && (declareCall))
  15130. mBfIRBuilder->UpdateDebugLocation(declareCall);
  15131. if (paramVar->mIsSplat)
  15132. {
  15133. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15134. }
  15135. else if (paramVar->mIsLowered)
  15136. {
  15137. argIdx++;
  15138. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15139. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15140. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  15141. if (loweredTypeCode != BfTypeCode_None)
  15142. argIdx++;
  15143. }
  15144. else if (!paramVar->mResolvedType->IsValuelessType())
  15145. {
  15146. argIdx++;
  15147. }
  15148. }
  15149. if (wantsDIData)
  15150. {
  15151. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  15152. }
  15153. }
  15154. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  15155. {
  15156. auto paramVar = mCurMethodState->mLocals[varIdx];
  15157. // 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
  15158. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  15159. // if (paramVar->mIsSplat)
  15160. // {
  15161. // if (wantsDIVariables)
  15162. // {
  15163. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  15164. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  15165. // }
  15166. // }
  15167. if (paramVar->mResolvedType->IsValuelessType())
  15168. {
  15169. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15170. {
  15171. // Only add this placeholder if we don't have any values
  15172. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15173. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15174. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15175. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15176. }
  15177. }
  15178. }
  15179. if (IsTargetingBeefBackend())
  15180. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  15181. if (methodState.mClosureState != NULL)
  15182. {
  15183. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  15184. {
  15185. BfLocalVariable* localVar = new BfLocalVariable();
  15186. *localVar = constLocal;
  15187. AddLocalVariableDef(localVar, true);
  15188. }
  15189. }
  15190. bool wantsRemoveBody = false;
  15191. bool skipBody = false;
  15192. bool skipUpdateSrcPos = false;
  15193. bool skipEndChecks = false;
  15194. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  15195. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  15196. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  15197. hasExternSpecifier = true;
  15198. // Allocate, clear, set classVData
  15199. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15200. {
  15201. CreateStaticCtor();
  15202. }
  15203. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  15204. {
  15205. skipBody = true;
  15206. skipEndChecks = true;
  15207. if (HasCompiledOutput())
  15208. {
  15209. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  15210. mBfIRBuilder->ClearDebugLocation();
  15211. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  15212. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  15213. PopulateType(innerType, BfPopulateType_DataAndMethods);
  15214. mBfIRBuilder->PopulateType(mCurTypeInstance);
  15215. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15216. if (methodInstance->mIsForeignMethodDef)
  15217. {
  15218. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  15219. }
  15220. BfTypeVector methodGenericArguments;
  15221. if (methodInstance->mMethodInfoEx != NULL)
  15222. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  15223. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  15224. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  15225. {
  15226. if (!methodInstance->mReturnType->IsValuelessType())
  15227. {
  15228. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  15229. CreateReturn(retVal);
  15230. }
  15231. else
  15232. mBfIRBuilder->CreateRetVoid();
  15233. }
  15234. else
  15235. {
  15236. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  15237. SizedArray<BfIRValue, 8> innerParams;
  15238. BfExprEvaluator exprEvaluator(this);
  15239. if (!innerType->IsValuelessType())
  15240. {
  15241. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  15242. BfTypedValue innerVal(thisValue, innerType, true);
  15243. if (boxedType->IsBoxedStructPtr())
  15244. {
  15245. innerVal = LoadValue(innerVal);
  15246. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  15247. }
  15248. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  15249. }
  15250. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  15251. {
  15252. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  15253. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  15254. exprEvaluator.PushArg(localVal, innerParams);
  15255. }
  15256. if (!innerMethodInstance.mFunc)
  15257. {
  15258. BF_ASSERT(innerType->IsUnspecializedType());
  15259. }
  15260. else if (methodInstance->GetStructRetIdx() != -1)
  15261. {
  15262. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  15263. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  15264. exprEvaluator.mReceivingValue = &returnType;
  15265. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  15266. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  15267. mBfIRBuilder->CreateRetVoid();
  15268. }
  15269. else
  15270. {
  15271. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  15272. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  15273. if (mCurMethodInstance->mReturnType->IsValueType())
  15274. retVal = LoadValue(retVal);
  15275. CreateReturn(retVal.mValue);
  15276. }
  15277. }
  15278. }
  15279. mCurMethodState->SetHadReturn(true);
  15280. mCurMethodState->mLeftBlockUncond = true;
  15281. }
  15282. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  15283. {
  15284. SetIllegalSrcPos();
  15285. mBfIRBuilder->ClearDebugLocation();
  15286. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  15287. auto thisVal = GetThis();
  15288. int prevSize = mContext->mBfObjectType->mInstSize;
  15289. int curSize = mCurTypeInstance->mInstSize;
  15290. if (curSize > prevSize)
  15291. {
  15292. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15293. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  15294. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  15295. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  15296. }
  15297. skipUpdateSrcPos = true;
  15298. }
  15299. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  15300. {
  15301. EmitCtorBody(skipBody);
  15302. }
  15303. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  15304. {
  15305. EmitDtorBody();
  15306. skipBody = true;
  15307. }
  15308. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  15309. {
  15310. EmitIteratorBlock(skipBody);
  15311. }
  15312. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  15313. {
  15314. // We need to be able to mark deleted objects
  15315. mCurMethodState->mIgnoreObjectAccessCheck = true;
  15316. }
  15317. auto customAttributes = methodInstance->GetCustomAttributes();
  15318. if (customAttributes != NULL)
  15319. {
  15320. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  15321. mCurMethodState->mIgnoreObjectAccessCheck = true;
  15322. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  15323. mCurMethodState->mDisableChecks = true;
  15324. }
  15325. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  15326. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  15327. {
  15328. // We chain even non-default ctors to the default ctors
  15329. auto defaultCtor = methodInstance;
  15330. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  15331. CallChainedMethods(defaultCtor, false);
  15332. }
  15333. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  15334. if (methodDef->mBody == NULL)
  15335. {
  15336. if (methodDeclaration != NULL)
  15337. {
  15338. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  15339. {
  15340. if (operatorDeclaration->mIsConvOperator)
  15341. wantsRemoveBody = true;
  15342. }
  15343. }
  15344. bool isDllImport = false;
  15345. if (methodInstance->GetImportKind() == BfImportKind_Import_Static)
  15346. {
  15347. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  15348. {
  15349. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  15350. {
  15351. if (customAttr.mCtorArgs.size() == 1)
  15352. {
  15353. auto fileNameArg = customAttr.mCtorArgs[0];
  15354. int strNum = 0;
  15355. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  15356. if (constant != NULL)
  15357. {
  15358. if (constant->IsNull())
  15359. continue; // Invalid
  15360. strNum = constant->mInt32;
  15361. }
  15362. else
  15363. {
  15364. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  15365. }
  15366. if (!mImportFileNames.Contains(strNum))
  15367. mImportFileNames.Add(strNum);
  15368. }
  15369. }
  15370. }
  15371. //mImportFileNames
  15372. }
  15373. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  15374. {
  15375. CreateDllImportMethod();
  15376. }
  15377. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  15378. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  15379. {
  15380. if (mCurTypeInstance->mTypeDef->mIsFunction)
  15381. {
  15382. // Emit nothing
  15383. }
  15384. else
  15385. {
  15386. CreateDelegateInvokeMethod();
  15387. mCurMethodState->SetHadReturn(true);
  15388. mCurMethodState->mLeftBlockUncond = true;
  15389. }
  15390. }
  15391. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  15392. {
  15393. if (mCurTypeInstance->IsObject())
  15394. {
  15395. CreateDynamicCastMethod();
  15396. }
  15397. else
  15398. {
  15399. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  15400. mCurMethodState->mHadReturn = true;
  15401. }
  15402. }
  15403. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  15404. {
  15405. BfIRValue ret;
  15406. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  15407. {
  15408. // This can happen if we provide an invalid name
  15409. AssertErrorState();
  15410. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  15411. }
  15412. else
  15413. {
  15414. // Unfortunate DebugLoc shenanigans-
  15415. // 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,
  15416. // so we only set the loc on the CreateRet which gets inlined out
  15417. mBfIRBuilder->SaveDebugLocation();
  15418. mBfIRBuilder->ClearDebugLocation();
  15419. BfIRValue fromBool;
  15420. if (!mCurTypeInstance->IsTypedPrimitive())
  15421. {
  15422. fromBool = GetDefaultValue(methodInstance->mReturnType);
  15423. }
  15424. else
  15425. {
  15426. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  15427. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  15428. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  15429. }
  15430. mBfIRBuilder->RestoreDebugLocation();
  15431. ret = mBfIRBuilder->CreateRet(fromBool);
  15432. //ExtendLocalLifetimes(0);
  15433. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15434. }
  15435. mCurMethodState->SetHadReturn(true);
  15436. mCurMethodState->mLeftBlockUncond = true;
  15437. }
  15438. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  15439. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  15440. {
  15441. BfIRValue ret;
  15442. // Unfortunate DebugLoc shenanigans-
  15443. // 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,
  15444. // so we only set the loc on the CreateRet which gets inlined out
  15445. mBfIRBuilder->SaveDebugLocation();
  15446. mBfIRBuilder->ClearDebugLocation();
  15447. BfIRValue fromBool;
  15448. mBfIRBuilder->RestoreDebugLocation();
  15449. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  15450. //ExtendLocalLifetimes(0);
  15451. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15452. mCurMethodState->SetHadReturn(true);
  15453. mCurMethodState->mLeftBlockUncond = true;
  15454. }
  15455. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  15456. {
  15457. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  15458. if (HasCompiledOutput())
  15459. {
  15460. EmitEnumToStringBody();
  15461. }
  15462. mBfIRBuilder->CreateRetVoid();
  15463. mCurMethodState->SetHadReturn(true);
  15464. mCurMethodState->mLeftBlockUncond = true;
  15465. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15466. }
  15467. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  15468. {
  15469. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  15470. if (HasCompiledOutput())
  15471. {
  15472. EmitTupleToStringBody();
  15473. }
  15474. mBfIRBuilder->CreateRetVoid();
  15475. mCurMethodState->SetHadReturn(true);
  15476. mCurMethodState->mLeftBlockUncond = true;
  15477. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15478. }
  15479. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  15480. {
  15481. CreateValueTypeEqualsMethod(false);
  15482. skipBody = true;
  15483. skipEndChecks = true;
  15484. }
  15485. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  15486. {
  15487. CreateValueTypeEqualsMethod(true);
  15488. skipBody = true;
  15489. skipEndChecks = true;
  15490. }
  15491. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  15492. {
  15493. CreateValueTypeEqualsMethod(false);
  15494. skipBody = true;
  15495. skipEndChecks = true;
  15496. }
  15497. else
  15498. {
  15499. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  15500. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  15501. {
  15502. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  15503. Fail("Body expected", methodDef->mBody);
  15504. }
  15505. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  15506. {
  15507. if (methodInstance->mReturnType->IsValuelessType())
  15508. {
  15509. mBfIRBuilder->CreateRetVoid();
  15510. }
  15511. else if (HasCompiledOutput())
  15512. {
  15513. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  15514. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  15515. BfFieldDef* fieldDef = NULL;
  15516. if (fieldInstance != NULL)
  15517. fieldDef = fieldInstance->GetFieldDef();
  15518. BfType* retType = methodInstance->mReturnType;
  15519. if (retType->IsRef())
  15520. retType = retType->GetUnderlyingType();
  15521. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  15522. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  15523. {
  15524. BfTypedValue lookupValue;
  15525. if (fieldDef->IsNonConstStatic())
  15526. lookupValue = ReferenceStaticField(fieldInstance);
  15527. else if (mCurTypeInstance->IsObject())
  15528. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  15529. else
  15530. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  15531. lookupValue = LoadOrAggregateValue(lookupValue);
  15532. CreateReturn(lookupValue.mValue);
  15533. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15534. }
  15535. else
  15536. {
  15537. // This can happen if we have two properties with the same name but different types
  15538. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  15539. EmitDefaultReturn();
  15540. }
  15541. }
  15542. else
  15543. {
  15544. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  15545. EmitDefaultReturn();
  15546. }
  15547. mCurMethodState->SetHadReturn(true);
  15548. }
  15549. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  15550. {
  15551. if ((!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  15552. {
  15553. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  15554. }
  15555. else if (!mCompiler->IsAutocomplete())
  15556. {
  15557. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  15558. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  15559. auto fieldDef = fieldInstance->GetFieldDef();
  15560. auto& lastParam = mCurMethodState->mLocals.back();
  15561. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  15562. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  15563. {
  15564. BfIRValue lookupAddr;
  15565. if (fieldDef->IsNonConstStatic())
  15566. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  15567. else
  15568. {
  15569. auto thisValue = GetThis();
  15570. if (thisValue.IsSplat())
  15571. {
  15572. BFMODULE_FATAL(this, "Should not happen");
  15573. }
  15574. if (mCurTypeInstance->IsObject())
  15575. thisValue = LoadValue(thisValue);
  15576. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  15577. }
  15578. BfExprEvaluator exprEvaluator(this);
  15579. auto localVal = exprEvaluator.LoadLocal(lastParam);
  15580. localVal = LoadOrAggregateValue(localVal);
  15581. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  15582. }
  15583. else if (!fieldInstance->mResolvedType->IsValuelessType())
  15584. {
  15585. // This can happen if we have two properties with the same name but different types
  15586. AssertErrorState();
  15587. }
  15588. }
  15589. }
  15590. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15591. {
  15592. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  15593. {
  15594. if (HasCompiledOutput())
  15595. EmitGCMarkMembers();
  15596. }
  15597. else if (!mCurTypeInstance->IsObject())
  15598. {
  15599. }
  15600. }
  15601. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  15602. {
  15603. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  15604. {
  15605. if (HasCompiledOutput())
  15606. EmitGCFindTLSMembers();
  15607. }
  15608. }
  15609. }
  15610. }
  15611. else if (!skipBody)
  15612. {
  15613. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  15614. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  15615. {
  15616. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  15617. if (mCurMethodInstance->GetStructRetIdx() != -1)
  15618. {
  15619. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  15620. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  15621. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  15622. mBfIRBuilder->ClearDebugLocation(storeInst);
  15623. mCurMethodState->mRetValAddr = allocaInst;
  15624. }
  15625. else
  15626. {
  15627. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  15628. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  15629. }
  15630. }
  15631. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15632. {
  15633. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  15634. BfGetSymbolReferenceKind prevSymbolKind;
  15635. BfAutoComplete* prevAutoComplete;
  15636. if (mCompiler->mResolvePassData != NULL)
  15637. {
  15638. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  15639. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15640. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  15641. }
  15642. EmitCtorCalcAppend();
  15643. if (mCompiler->mResolvePassData != NULL)
  15644. {
  15645. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  15646. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  15647. }
  15648. }
  15649. else if (!isEmptyBodied)
  15650. {
  15651. if (!mCurMethodState->mIRExitBlock)
  15652. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  15653. bool isExpressionBody = false;
  15654. if (methodDeclaration != NULL)
  15655. {
  15656. if (methodDeclaration->mFatArrowToken != NULL)
  15657. isExpressionBody = true;
  15658. }
  15659. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  15660. {
  15661. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15662. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  15663. isExpressionBody = true;
  15664. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  15665. {
  15666. isExpressionBody = true;
  15667. }
  15668. }
  15669. else
  15670. {
  15671. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15672. {
  15673. if (!block->mChildArr.IsEmpty())
  15674. {
  15675. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  15676. {
  15677. if (exprStmt->mTrailingSemicolon == NULL)
  15678. isExpressionBody = true;
  15679. }
  15680. }
  15681. }
  15682. else
  15683. isExpressionBody = true;
  15684. }
  15685. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  15686. {
  15687. while (fieldDtorBody != NULL)
  15688. {
  15689. VisitEmbeddedStatement(fieldDtorBody->mBody);
  15690. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  15691. }
  15692. }
  15693. else if (!isExpressionBody)
  15694. {
  15695. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  15696. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  15697. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  15698. VisitCodeBlock(bodyBlock);
  15699. }
  15700. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  15701. {
  15702. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  15703. // {
  15704. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  15705. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  15706. // }
  15707. auto expectingType = mCurMethodInstance->mReturnType;
  15708. // What was this error for?
  15709. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  15710. // {
  15711. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  15712. // }
  15713. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_None;
  15714. if (expectingType->IsVoid())
  15715. {
  15716. exprEvalFlags = BfEvalExprFlags_NoCast;
  15717. bool wasReturnGenericParam = false;
  15718. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  15719. {
  15720. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  15721. }
  15722. else
  15723. {
  15724. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  15725. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  15726. wasReturnGenericParam = true;
  15727. }
  15728. // If we the void return was from a generic specialization, allow us to return a void result,
  15729. // otherwise treat expression as though it must be a statement
  15730. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  15731. if (isStatement)
  15732. expectingType = NULL;
  15733. }
  15734. UpdateSrcPos(expressionBody);
  15735. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  15736. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  15737. {
  15738. mCurMethodState->mHadReturn = true;
  15739. retVal = LoadValue(retVal);
  15740. EmitReturn(retVal.mValue);
  15741. }
  15742. }
  15743. }
  15744. }
  15745. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  15746. if (skipUpdateSrcPos)
  15747. {
  15748. // Skip
  15749. }
  15750. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15751. UpdateSrcPos(bodyBlock->mCloseBrace);
  15752. else if (methodDef->mBody != NULL)
  15753. UpdateSrcPos(methodDef->mBody);
  15754. else if (methodDeclaration != NULL)
  15755. UpdateSrcPos(methodDeclaration);
  15756. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15757. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15758. else
  15759. UseDefaultSrcPos();
  15760. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15761. {
  15762. if (mCurMethodState->mRetVal)
  15763. {
  15764. mCurMethodState->SetHadReturn(true);
  15765. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15766. mBfIRBuilder->CreateRet(retVal);
  15767. }
  15768. else
  15769. AssertErrorState();
  15770. }
  15771. if (!mCurMethodState->mHadReturn)
  15772. {
  15773. // Clear off the stackallocs that have occurred after a scopeData break
  15774. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  15775. }
  15776. if (mCurMethodState->mIRExitBlock)
  15777. {
  15778. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  15779. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  15780. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  15781. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  15782. if (!mCurMethodState->mDIRetVal)
  15783. CreateDIRetVal();
  15784. }
  15785. for (auto localVar : mCurMethodState->mLocals)
  15786. {
  15787. if ((skipEndChecks) || (bodyBlock == NULL))
  15788. break;
  15789. LocalVariableDone(localVar, true);
  15790. }
  15791. if (mCurMethodState->mIRExitBlock)
  15792. {
  15793. if ((mCurMethodState->mRetVal) && (mCurMethodInstance->GetStructRetIdx() == -1))
  15794. {
  15795. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15796. CreateReturn(loadedVal);
  15797. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15798. if (mCurMethodState->mDIRetVal)
  15799. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15800. }
  15801. else
  15802. {
  15803. // Have something on the last line to step onto
  15804. if (mHasFullDebugInfo)
  15805. {
  15806. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15807. UpdateSrcPos(bodyBlock->mCloseBrace);
  15808. EmitEnsureInstructionAt();
  15809. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15810. {
  15811. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15812. mBfIRBuilder->EnsureFunctionPatchable();
  15813. }
  15814. }
  15815. mBfIRBuilder->CreateRetVoid();
  15816. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15817. if (mCurMethodState->mDIRetVal)
  15818. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15819. }
  15820. }
  15821. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  15822. {
  15823. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  15824. {
  15825. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15826. {
  15827. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15828. mBfIRBuilder->EnsureFunctionPatchable();
  15829. }
  15830. mBfIRBuilder->CreateRetVoid();
  15831. }
  15832. }
  15833. else
  15834. {
  15835. if (!mCurMethodState->mHadReturn)
  15836. {
  15837. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  15838. if (bodyBlock != NULL)
  15839. {
  15840. if (bodyBlock->mCloseBrace != NULL)
  15841. {
  15842. BfAstNode* target = bodyBlock->mCloseBrace;
  15843. Fail("Method must return value", target);
  15844. }
  15845. else
  15846. {
  15847. // It's possible to not have a closing brace if the method ends in an EOF
  15848. AssertErrorState();
  15849. }
  15850. }
  15851. }
  15852. }
  15853. // Move 'init' into 'entry'
  15854. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  15855. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  15856. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  15857. {
  15858. // Don't keep instructions for unspecialized types
  15859. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15860. }
  15861. if ((hasExternSpecifier) && (!skipBody))
  15862. {
  15863. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  15864. // incase it gets called later by some hot-loaded coded
  15865. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()))
  15866. CreateFakeCallerMethod(mangledName);
  15867. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15868. }
  15869. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  15870. {
  15871. // We only need the DLL stub when we may be hot swapping
  15872. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15873. }
  15874. else if (wantsRemoveBody)
  15875. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15876. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15877. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15878. // unspecialized types
  15879. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15880. {
  15881. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15882. methodInstance->mIRFunction = BfIRFunction();
  15883. }
  15884. CheckAddFailType();
  15885. if (mHadBuildError)
  15886. prevHadBuildError.CancelRestore();
  15887. if (mHadBuildWarning)
  15888. prevHadWarning.CancelRestore();
  15889. if (!methodDef->mIsLocalMethod)
  15890. ProcessMethod_ProcessDeferredLocals();
  15891. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15892. if (methodState.mHotDataReferenceBuilder != NULL)
  15893. {
  15894. AddHotDataReferences(&hotDataReferenceBuilder);
  15895. }
  15896. else
  15897. {
  15898. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15899. {
  15900. // Remove the hot method data
  15901. auto hotMethod = methodInstance->mHotMethod;
  15902. auto prevMethod = hotMethod->mPrevVersion;
  15903. if (prevMethod != NULL)
  15904. {
  15905. // If there's a prev method then pull its data into the main HotMethod.
  15906. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15907. // over to the main HotMethod definition to keep the HotMethod address
  15908. // invariant
  15909. for (auto ref : hotMethod->mReferences)
  15910. ref->Deref();
  15911. hotMethod->mReferences.Clear();
  15912. BF_ASSERT(prevMethod->mRefCount == 1);
  15913. hotMethod->mReferences = prevMethod->mReferences;
  15914. if (hotMethod->mSrcTypeVersion != NULL)
  15915. hotMethod->mSrcTypeVersion->Deref();
  15916. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15917. prevMethod->mSrcTypeVersion = NULL;
  15918. prevMethod->mReferences.Clear();
  15919. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15920. prevMethod->mPrevVersion = NULL;
  15921. prevMethod->Deref();
  15922. }
  15923. hotMethod->Deref();
  15924. methodInstance->mHotMethod = NULL;
  15925. }
  15926. }
  15927. }
  15928. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15929. {
  15930. String name;
  15931. bool found = false;
  15932. auto checkMethodState = mCurMethodState;
  15933. while (checkMethodState != NULL)
  15934. {
  15935. if (checkMethodState->mClosureState == NULL)
  15936. break;
  15937. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15938. {
  15939. found = true;
  15940. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15941. break;
  15942. }
  15943. checkMethodState = checkMethodState->mPrevMethodState;
  15944. }
  15945. if (!found)
  15946. name += mCurMethodInstance->mMethodDef->mName;
  15947. int prevSepPos = (int)name.LastIndexOf('$');
  15948. if (prevSepPos != -1)
  15949. {
  15950. name.RemoveToEnd(prevSepPos);
  15951. }
  15952. name += "@";
  15953. name += baseName;
  15954. HashContext hashCtx;
  15955. if (anchorNode != NULL)
  15956. {
  15957. hashCtx.Mixin(anchorNode->GetStartCharId());
  15958. }
  15959. //
  15960. {
  15961. auto checkMethodState = declMethodState;
  15962. auto checkMixinState = declMixinState;
  15963. while (checkMethodState != NULL)
  15964. {
  15965. if (checkMixinState != NULL)
  15966. {
  15967. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15968. }
  15969. checkMethodState = checkMethodState->mPrevMethodState;
  15970. if (checkMethodState != NULL)
  15971. checkMixinState = checkMethodState->mMixinState;
  15972. }
  15973. }
  15974. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15975. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15976. {
  15977. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15978. {
  15979. StringT<128> genericTypeName;
  15980. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15981. hashCtx.MixinStr(genericTypeName);
  15982. }
  15983. }
  15984. uint64 hashVal = hashCtx.Finish64();
  15985. name += "$";
  15986. name += BfTypeUtils::HashEncode64(hashVal);
  15987. return name;
  15988. }
  15989. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15990. {
  15991. if (localMethod->mMethodDef != NULL)
  15992. return localMethod->mMethodDef;
  15993. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15994. auto declMethodState = localMethod->mDeclMethodState;
  15995. auto declMixinState = localMethod->mDeclMixinState;
  15996. auto typeInst = mCurTypeInstance;
  15997. BfAstNode* body = NULL;
  15998. BfAstNode* anchorNode = NULL;
  15999. auto _AllocDirectTypeRef = [&](BfType* type)
  16000. {
  16001. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  16002. directTypeRef->Init(type);
  16003. return directTypeRef;
  16004. };
  16005. auto methodDeclaration = localMethod->mMethodDeclaration;
  16006. if (methodDeclaration != NULL)
  16007. {
  16008. body = methodDeclaration->mBody;
  16009. anchorNode = methodDeclaration->mOpenParen;
  16010. }
  16011. else
  16012. {
  16013. body = localMethod->mLambdaBindExpr->mBody;
  16014. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  16015. }
  16016. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  16017. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  16018. BfMethodDef* methodDef;
  16019. BfMethodDef* outerMethodDef = NULL;
  16020. if (localMethod->mOuterLocalMethod != NULL)
  16021. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  16022. else
  16023. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  16024. if (methodDeclaration != NULL)
  16025. {
  16026. BfDefBuilder defBuilder(mCompiler->mSystem);
  16027. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  16028. defBuilder.mPassInstance = mCompiler->mPassInstance;
  16029. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  16030. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  16031. }
  16032. else
  16033. {
  16034. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  16035. methodDef = new BfMethodDef();
  16036. methodDef->mName = localMethod->mMethodName;
  16037. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  16038. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  16039. methodDef->mBody = body;
  16040. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  16041. {
  16042. auto paramType = invokeMethod->GetParamType(paramIdx);
  16043. String paramName;
  16044. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  16045. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  16046. else
  16047. paramName = invokeMethod->GetParamName(paramIdx);
  16048. auto paramDef = new BfParameterDef();
  16049. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  16050. paramDef->mName = paramName;
  16051. methodDef->mParams.Add(paramDef);
  16052. }
  16053. if (outerMethodDef != NULL)
  16054. {
  16055. for (auto genericParam : outerMethodDef->mGenericParams)
  16056. {
  16057. auto* copiedGenericParamDef = new BfGenericParamDef();
  16058. *copiedGenericParamDef = *genericParam;
  16059. methodDef->mGenericParams.Add(copiedGenericParamDef);
  16060. }
  16061. }
  16062. }
  16063. methodDef->mIdx = ~methodLocalIdx;
  16064. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  16065. methodDef->mName = localMethod->mExpectedFullName;
  16066. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  16067. //
  16068. // if (!localMethod->mExpectedFullName.IsEmpty())
  16069. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  16070. methodDef->mIsStatic = true;
  16071. methodDef->mIsLocalMethod = true;
  16072. methodDef->mIsVirtual = false;
  16073. localMethod->mMethodDef = methodDef;
  16074. auto methodInstanceGroup = new BfMethodInstanceGroup();
  16075. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  16076. methodInstanceGroup->mMethodIdx = -1;
  16077. methodInstanceGroup->mOwner = mCurTypeInstance;
  16078. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16079. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  16080. {
  16081. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  16082. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  16083. }
  16084. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  16085. {
  16086. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  16087. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16088. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  16089. {
  16090. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  16091. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  16092. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  16093. autoComplete->mDefType = typeInst->mTypeDef;
  16094. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  16095. autoComplete->mReplaceLocalId = methodLocalIdx;
  16096. }
  16097. }
  16098. return localMethod->mMethodDef;
  16099. }
  16100. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  16101. {
  16102. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  16103. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  16104. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16105. auto declMethodState = localMethod->mDeclMethodState;
  16106. auto declMixinState = localMethod->mDeclMixinState;
  16107. auto callerMethodState = mCurMethodState;
  16108. auto typeInst = mCurTypeInstance;
  16109. if (mCurMethodState->mMixinState != NULL)
  16110. {
  16111. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  16112. }
  16113. auto methodDef = GetLocalMethodDef(localMethod);
  16114. BfAstNode* body = NULL;
  16115. auto methodDeclaration = localMethod->mMethodDeclaration;
  16116. if (methodDeclaration != NULL)
  16117. {
  16118. body = methodDeclaration->mBody;
  16119. }
  16120. else
  16121. {
  16122. body = localMethod->mLambdaBindExpr->mBody;
  16123. }
  16124. bool hadConcreteInterfaceGenericArgument = false;
  16125. BfTypeVector sanitizedMethodGenericArguments;
  16126. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  16127. // version of this method for this pass through the outermost method
  16128. int dependentGenericStartIdx = 0;
  16129. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16130. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16131. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  16132. if (methodGenericArguments.size() == 0)
  16133. {
  16134. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16135. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  16136. }
  16137. else
  16138. {
  16139. int genericArgIdx = 0;
  16140. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  16141. // {
  16142. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  16143. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  16144. // }
  16145. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16146. {
  16147. auto genericArgType = methodGenericArguments[genericArgIdx];
  16148. BF_ASSERT(!genericArgType->IsRef());
  16149. if (genericArgType->IsConcreteInterfaceType())
  16150. {
  16151. hadConcreteInterfaceGenericArgument = true;
  16152. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  16153. genericArgType = concreteInterfaceType->mInterface;
  16154. }
  16155. sanitizedMethodGenericArguments.push_back(genericArgType);
  16156. }
  16157. }
  16158. bool wantPrematureMethodInstance = false;
  16159. if (!force)
  16160. {
  16161. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  16162. }
  16163. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  16164. bool isDefaultPass = true;
  16165. BfTypeVector lookupMethodGenericArguments;
  16166. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16167. {
  16168. auto genericArgType = methodGenericArguments[genericArgIdx];
  16169. BF_ASSERT(!genericArgType->IsRef());
  16170. lookupMethodGenericArguments.Add(genericArgType);
  16171. if (genericArgType->IsGenericParam())
  16172. {
  16173. auto genericParam = (BfGenericParamType*)genericArgType;
  16174. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16175. isDefaultPass = false;
  16176. }
  16177. else
  16178. {
  16179. isDefaultPass = false;
  16180. }
  16181. }
  16182. bool hadExistingMethodInstance = false;
  16183. if (methodInstance != NULL)
  16184. {
  16185. hadExistingMethodInstance = true;
  16186. }
  16187. else
  16188. {
  16189. if (isDefaultPass)
  16190. {
  16191. methodInstance = methodInstGroup->mDefault;
  16192. if (methodInstance != NULL)
  16193. {
  16194. hadExistingMethodInstance = true;
  16195. }
  16196. else
  16197. {
  16198. methodInstance = new BfMethodInstance();
  16199. methodInstGroup->mDefault = methodInstance;
  16200. }
  16201. }
  16202. else
  16203. {
  16204. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  16205. if (methodInstGroup->mMethodSpecializationMap == NULL)
  16206. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  16207. BfMethodInstance** methodInstancePtr = NULL;
  16208. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  16209. {
  16210. methodInstance = *methodInstancePtr;
  16211. hadExistingMethodInstance = true;
  16212. }
  16213. else
  16214. {
  16215. methodInstance = new BfMethodInstance();
  16216. *methodInstancePtr = methodInstance;
  16217. }
  16218. }
  16219. }
  16220. if (hadExistingMethodInstance)
  16221. {
  16222. if ((!methodInstance->mDisallowCalling) ||
  16223. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  16224. return BfModuleMethodInstance(methodInstance);
  16225. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  16226. }
  16227. else
  16228. {
  16229. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  16230. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  16231. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  16232. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  16233. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  16234. methodInstance->mMethodDef = methodDef;
  16235. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  16236. if (hadConcreteInterfaceGenericArgument)
  16237. methodInstance->mIgnoreBody = true;
  16238. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  16239. for (auto genericArg : sanitizedMethodGenericArguments)
  16240. {
  16241. if (genericArg->IsPrimitiveType())
  16242. genericArg = GetWrappedStructType(genericArg);
  16243. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  16244. }
  16245. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  16246. {
  16247. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16248. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  16249. }
  16250. SetupMethodIdHash(methodInstance);
  16251. }
  16252. auto _SetupMethodInstance = [&]()
  16253. {
  16254. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  16255. // Generic constraints
  16256. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  16257. {
  16258. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  16259. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  16260. }
  16261. };
  16262. //////////////////////////////////////////////////////////////////////////
  16263. auto _VisitLambdaBody = [&]()
  16264. {
  16265. if (localMethod->mDeclOnly)
  16266. return;
  16267. if (mCompiler->mCanceling)
  16268. return;
  16269. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  16270. {
  16271. VisitCodeBlock(blockBody);
  16272. }
  16273. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  16274. CreateValueFromExpression(bodyExpr);
  16275. };
  16276. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  16277. {
  16278. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  16279. auto result = ResolveTypeRef(typeRef);
  16280. if (result == NULL)
  16281. result = mContext->mBfObjectType;
  16282. return result;
  16283. };
  16284. BfTypeInstance* outerClosure = NULL;
  16285. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  16286. outerClosure = declMethodState->mClosureState->mClosureType;
  16287. BfMethodState methodState;
  16288. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  16289. BfIRFunctionType funcType;
  16290. auto voidType = GetPrimitiveType(BfTypeCode_None);
  16291. SizedArray<BfIRType, 0> paramTypes;
  16292. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  16293. mBfIRBuilder->SaveDebugLocation();
  16294. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  16295. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  16296. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  16297. BfDeferredLocalAssignData deferredLocalAssignData;
  16298. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  16299. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  16300. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  16301. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16302. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  16303. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  16304. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  16305. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  16306. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  16307. methodState.mIRFunction = declMethodState->mIRFunction;
  16308. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  16309. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  16310. {
  16311. methodState.mCurScope->mAstBlock = blockBody;
  16312. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  16313. }
  16314. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  16315. BfClosureState closureState;
  16316. if (methodDef->mMethodType == BfMethodType_Mixin)
  16317. {
  16318. if (declMethodState != NULL)
  16319. {
  16320. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  16321. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  16322. else if (declMethodState->mMethodInstance != NULL)
  16323. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  16324. }
  16325. }
  16326. if (closureState.mReturnType == NULL)
  16327. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  16328. closureState.mCapturing = true;
  16329. closureState.mLocalMethod = localMethod;
  16330. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16331. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  16332. methodState.mClosureState = &closureState;
  16333. closureState.mClosureType = outerClosure;
  16334. int outerLocalsCount = (int)methodState.mLocals.size();
  16335. if (!hadExistingMethodInstance)
  16336. {
  16337. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  16338. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  16339. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16340. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  16341. auto declareModule = this;
  16342. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  16343. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  16344. BF_ASSERT(declareModule != NULL);
  16345. methodInstance->mDeclModule = declareModule;
  16346. _SetupMethodInstance();
  16347. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  16348. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  16349. }
  16350. if (wantPrematureMethodInstance)
  16351. {
  16352. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  16353. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  16354. // its true method instance
  16355. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  16356. //BF_ASSERT(moduleMethodInstance);
  16357. return BfModuleMethodInstance(methodInstance);
  16358. }
  16359. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  16360. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  16361. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  16362. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  16363. closureState.mClosureMethodDef = methodDef;
  16364. bool wantsVisitBody = true;
  16365. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  16366. wantsVisitBody = false;
  16367. if (methodInstance->mIsUnspecializedVariation)
  16368. wantsVisitBody = false;
  16369. if (wantsVisitBody)
  16370. {
  16371. BP_ZONE("VisitLambdaBody");
  16372. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  16373. // this capture stage for each of those times
  16374. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  16375. /*
  16376. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  16377. // that will not occur during the actual lambda method generation, for example: returning a value
  16378. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  16379. // our AST nodes will still be visited
  16380. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  16381. */
  16382. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  16383. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  16384. mBfIRBuilder->SaveDebugLocation();
  16385. closureState.mCaptureVisitingBody = true;
  16386. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  16387. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  16388. methodState.mMethodInstance = methodInstance;
  16389. NewScopeState();
  16390. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  16391. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  16392. {
  16393. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  16394. for (auto localDef : methodState.mLocals)
  16395. {
  16396. if (localDef->mResolvedType->IsVar())
  16397. continue;
  16398. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  16399. }
  16400. }
  16401. _VisitLambdaBody();
  16402. RestoreScopeState();
  16403. //ProcessMethod(methodInstance);
  16404. closureState.mCaptureVisitingBody = false;
  16405. mBfIRBuilder->RestoreDebugLocation();
  16406. }
  16407. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  16408. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  16409. {
  16410. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  16411. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  16412. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  16413. }
  16414. //RestoreScopeState();
  16415. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  16416. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  16417. closureState.mClosureMethodDef = NULL;
  16418. for (auto methodInstance : closureState.mLocalMethodRefs)
  16419. {
  16420. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  16421. }
  16422. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  16423. prevIgnoreWrites.Restore();
  16424. std::multiset<BfClosureCapturedEntry> capturedEntries;
  16425. //
  16426. {
  16427. auto varMethodState = declMethodState;
  16428. while (varMethodState != NULL)
  16429. {
  16430. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  16431. {
  16432. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  16433. methodDef->mIsStatic = false;
  16434. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  16435. methodDef->mIsMutating = true;
  16436. }
  16437. bool copyOuterCaptures = false;
  16438. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  16439. {
  16440. auto localVar = varMethodState->mLocals[localIdx];
  16441. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  16442. {
  16443. if (localVar->mIsThis)
  16444. {
  16445. // We can only set mutating if our owning type is mutating
  16446. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  16447. {
  16448. if (typeInst->IsValueType())
  16449. {
  16450. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  16451. methodDef->mIsMutating = true;
  16452. }
  16453. }
  16454. methodDef->mIsStatic = false;
  16455. continue;
  16456. }
  16457. if ((localVar->mIsThis) && (outerClosure != NULL))
  16458. {
  16459. continue;
  16460. }
  16461. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  16462. {
  16463. closureState.mConstLocals.push_back(*localVar);
  16464. continue;
  16465. }
  16466. BfClosureCapturedEntry capturedEntry;
  16467. auto capturedType = localVar->mResolvedType;
  16468. bool captureByRef = false;
  16469. if (!capturedType->IsRef())
  16470. {
  16471. if (localVar->mIsThis)
  16472. {
  16473. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  16474. captureByRef = true;
  16475. }
  16476. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  16477. captureByRef = true;
  16478. }
  16479. else
  16480. {
  16481. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  16482. {
  16483. capturedType = ((BfRefType*)capturedType)->mElementType;
  16484. }
  16485. }
  16486. if (captureByRef)
  16487. {
  16488. //capturedEntry.mIsByReference = true;
  16489. capturedType = CreateRefType(capturedType);
  16490. }
  16491. else
  16492. {
  16493. //capturedEntry.mIsByReference = false;
  16494. }
  16495. capturedEntry.mNameNode = localVar->mNameNode;
  16496. capturedEntry.mType = capturedType;
  16497. capturedEntry.mName = localVar->mName;
  16498. //capturedEntry.mLocalVarDef = localVar;
  16499. capturedEntries.insert(capturedEntry);
  16500. }
  16501. }
  16502. varMethodState = varMethodState->mPrevMethodState;
  16503. if ((varMethodState == NULL) ||
  16504. (varMethodState->mMixinState != NULL) ||
  16505. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  16506. break;
  16507. }
  16508. }
  16509. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  16510. {
  16511. auto fieldDef = copyField->GetFieldDef();
  16512. BfClosureCapturedEntry capturedEntry;
  16513. capturedEntry.mName = copyField->GetFieldDef()->mName;
  16514. capturedEntry.mType = copyField->mResolvedType;
  16515. if (capturedEntry.mType->IsRef())
  16516. {
  16517. // Keep by ref
  16518. }
  16519. else if (!fieldDef->mIsReadOnly)
  16520. {
  16521. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  16522. }
  16523. capturedEntries.insert(capturedEntry);
  16524. }
  16525. int captureIdx = 0;
  16526. for (auto& capturedEntry : capturedEntries)
  16527. {
  16528. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  16529. }
  16530. /*if (isDefaultPass)
  16531. {
  16532. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  16533. int captureIdx = 0;
  16534. for (auto& capturedEntry : capturedEntries)
  16535. {
  16536. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  16537. BfParameterDef* paramDef = new BfParameterDef();
  16538. paramDef->mName = capturedEntry.mName;
  16539. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  16540. directTypeRef->mType = capturedEntry.mType;
  16541. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  16542. paramDef->mTypeRef = directTypeRef;
  16543. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  16544. methodDef->mParams.Insert(captureIdx, paramDef);
  16545. captureIdx++;
  16546. }
  16547. }
  16548. else
  16549. {
  16550. auto defaultMethodInstance = methodInstGroup->mDefault;
  16551. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  16552. }*/
  16553. methodState.Reset();
  16554. closureState.mCapturing = false;
  16555. //////////////////////////////////////////////////////////////////////////
  16556. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  16557. if (methodInstance->mReturnType != NULL)
  16558. {
  16559. BF_ASSERT(methodInstance->mDisallowCalling);
  16560. // We did a premature declaration (without captures)
  16561. methodInstance->UndoDeclaration();
  16562. methodInstance->mDisallowCalling = false;
  16563. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  16564. }
  16565. auto declareModule = this;
  16566. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  16567. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  16568. BF_ASSERT(declareModule != NULL);
  16569. methodInstance->mDeclModule = declareModule;
  16570. _SetupMethodInstance();
  16571. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  16572. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  16573. closureState.mReturnType = methodInstance->mReturnType;
  16574. mCompiler->mStats.mMethodsQueued++;
  16575. mCompiler->UpdateCompletion();
  16576. declareModule->mIncompleteMethodCount++;
  16577. mCompiler->mStats.mMethodsProcessed++;
  16578. if (!methodInstance->mIsReified)
  16579. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  16580. auto deferMethodState = rootMethodState;
  16581. // 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)
  16582. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  16583. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  16584. {
  16585. BP_ZONE("BfDeferredLocalMethod:create");
  16586. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  16587. deferredLocalMethod->mLocalMethod = localMethod;
  16588. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  16589. deferredLocalMethod->mMethodInstance = methodInstance;
  16590. auto checkMethodState = declMethodState;
  16591. while (checkMethodState != NULL)
  16592. {
  16593. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  16594. {
  16595. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  16596. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  16597. }
  16598. if (checkMethodState->mMixinState != NULL)
  16599. {
  16600. BfMixinRecord mixinRecord;
  16601. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  16602. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  16603. }
  16604. checkMethodState = checkMethodState->mPrevMethodState;
  16605. }
  16606. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  16607. }
  16608. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  16609. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  16610. mBfIRBuilder->RestoreDebugLocation();
  16611. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  16612. {
  16613. auto checkMethodState = mCurMethodState;
  16614. while (checkMethodState != NULL)
  16615. {
  16616. BfLocalMethod* nextLocalMethod = NULL;
  16617. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  16618. {
  16619. while (nextLocalMethod != NULL)
  16620. {
  16621. auto checkLocalMethod = nextLocalMethod;
  16622. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  16623. if (checkLocalMethod == localMethod)
  16624. continue;
  16625. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  16626. continue;
  16627. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  16628. if (checkMethodInstance == NULL)
  16629. continue; // Not generated yet
  16630. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  16631. {
  16632. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  16633. if (bfError != NULL)
  16634. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  16635. }
  16636. }
  16637. }
  16638. checkMethodState = checkMethodState->mPrevMethodState;
  16639. }
  16640. }
  16641. return BfModuleMethodInstance(methodInstance);
  16642. }
  16643. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  16644. {
  16645. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  16646. return 0;
  16647. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16648. int rootMethodGenericParamCount = 0;
  16649. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16650. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  16651. if (mCurMethodInstance == NULL)
  16652. return rootMethodGenericParamCount;
  16653. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  16654. return rootMethodGenericParamCount;
  16655. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  16656. if (callerLocalMethod == NULL)
  16657. return rootMethodGenericParamCount;
  16658. BfLocalMethod* calledLocalMethod = NULL;
  16659. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  16660. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  16661. {
  16662. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  16663. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  16664. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  16665. }
  16666. return rootMethodGenericParamCount;
  16667. }
  16668. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  16669. {
  16670. auto methodDef = methodInstance->mMethodDef;
  16671. auto customAttributes = methodInstance->GetCustomAttributes();
  16672. if (customAttributes != NULL)
  16673. return;
  16674. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16675. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  16676. auto typeInstance = methodInstance->GetOwner();
  16677. BfTypeState typeState(typeInstance);
  16678. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  16679. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  16680. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  16681. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  16682. {
  16683. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16684. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16685. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  16686. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  16687. }
  16688. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  16689. {
  16690. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16691. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16692. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  16693. }
  16694. customAttributes = methodInstance->GetCustomAttributes();
  16695. if (customAttributes == NULL)
  16696. {
  16697. auto owner = methodInstance->GetOwner();
  16698. if ((owner->IsDelegate()) || (owner->IsFunction()))
  16699. customAttributes = owner->mCustomAttributes;
  16700. }
  16701. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  16702. if (customAttributes != NULL)
  16703. {
  16704. auto linkNameAttr = customAttributes->Get(typeInstance->mModule->mCompiler->mCallingConventionAttributeTypeDef);
  16705. if (linkNameAttr != NULL)
  16706. {
  16707. if (linkNameAttr->mCtorArgs.size() == 1)
  16708. {
  16709. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  16710. if (constant != NULL)
  16711. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  16712. }
  16713. }
  16714. }
  16715. }
  16716. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  16717. {
  16718. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  16719. {
  16720. // Don't create a func
  16721. return;
  16722. }
  16723. auto typeInstance = methodInstance->GetOwner();
  16724. auto methodDef = methodInstance->mMethodDef;
  16725. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  16726. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  16727. if (mCompiler->mResolvePassData == NULL)
  16728. {
  16729. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  16730. {
  16731. typeInstance->mHasStaticInitMethod = true;
  16732. }
  16733. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  16734. {
  16735. typeInstance->mHasStaticDtorMethod = true;
  16736. }
  16737. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  16738. {
  16739. typeInstance->mHasStaticMarkMethod = true;
  16740. }
  16741. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16742. {
  16743. typeInstance->mHasTLSFindMethod = true;
  16744. }
  16745. }
  16746. if (isTemporaryFunc)
  16747. {
  16748. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  16749. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  16750. mangledName = "autocomplete_tmp";
  16751. }
  16752. if (!mBfIRBuilder->mIgnoreWrites)
  16753. {
  16754. BfIRFunction prevFunc;
  16755. // Remove old version (if we have one)
  16756. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16757. if (prevFunc)
  16758. {
  16759. if (methodDef->mIsExtern)
  16760. {
  16761. // Allow this
  16762. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  16763. }
  16764. else if (typeInstance->IsIRFuncUsed(prevFunc))
  16765. {
  16766. // We can have a collision of names when we have generic methods that differ only in
  16767. // their constraints, but they should only collide in their unspecialized form
  16768. // since only one will be chosen for a given concrete type
  16769. mCurMethodInstance->mMangleWithIdx = true;
  16770. mangledName.Clear();
  16771. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16772. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16773. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  16774. }
  16775. else
  16776. {
  16777. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  16778. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16779. }
  16780. }
  16781. }
  16782. if (typeInstance != mContext->mBfObjectType)
  16783. {
  16784. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  16785. GetMethodCustomAttributes(methodInstance);
  16786. }
  16787. // if (prevFunc)
  16788. // {
  16789. // if (methodDef->mIsExtern)
  16790. // {
  16791. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  16792. // methodInstance->mIRFunction = prevFunc;
  16793. // }
  16794. // else
  16795. // {
  16796. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  16797. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  16798. // {
  16799. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  16800. // BfLogSysM("Ignoring function name collision\n");
  16801. // }
  16802. // else
  16803. // {
  16804. // if (methodDef->mMethodDeclaration == NULL)
  16805. // {
  16806. // AssertErrorState();
  16807. // }
  16808. // else
  16809. // {
  16810. // BF_ASSERT(mIsSpecialModule);
  16811. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  16812. // {
  16813. // // We shouldn't have name collisions on the first run!
  16814. // AssertErrorState();
  16815. // }
  16816. // }
  16817. // }
  16818. // BfLogSysM("Before erase\n");
  16819. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16820. // }
  16821. // }
  16822. bool isIntrinsic = false;
  16823. if (!methodInstance->mIRFunction)
  16824. {
  16825. BfIRFunction func;
  16826. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  16827. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  16828. {
  16829. if (!mIsReified)
  16830. wantsLLVMFunc = false;
  16831. }*/
  16832. if (wantsLLVMFunc)
  16833. {
  16834. func = GetIntrinsic(methodInstance, true);
  16835. if (func)
  16836. {
  16837. isIntrinsic = true;
  16838. }
  16839. else
  16840. {
  16841. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  16842. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  16843. if (methodInstance->mAlwaysInline)
  16844. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16845. // if (prevFunc)
  16846. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  16847. }
  16848. methodInstance->mIRFunction = func;
  16849. //if (!ignoreWrites)
  16850. //BF_ASSERT(!func.IsFake());
  16851. }
  16852. }
  16853. if (outIsIntrinsic != NULL)
  16854. *outIsIntrinsic = isIntrinsic;
  16855. if (!isIntrinsic)
  16856. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  16857. }
  16858. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  16859. {
  16860. if (methodInstance->mHotMethod != NULL)
  16861. return;
  16862. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  16863. {
  16864. auto srcTypeInst = methodInstance->GetOwner();
  16865. StringT<128> mangledName = inMangledName;
  16866. if (mangledName.IsEmpty())
  16867. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16868. // We always keep the current primary method at the same address
  16869. BfHotMethod* hotMethod;
  16870. BfHotMethod** hotMethodPtr;
  16871. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  16872. {
  16873. hotMethod = new BfHotMethod();
  16874. *hotMethodPtr = hotMethod;
  16875. hotMethod->mRefCount = 1;
  16876. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16877. #ifdef BF_DBG_HOTMETHOD_IDX
  16878. static int sMethodIdx = 0;
  16879. hotMethod->mMethodIdx = sMethodIdx++;
  16880. #endif
  16881. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16882. }
  16883. else
  16884. {
  16885. hotMethod = *hotMethodPtr;
  16886. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  16887. {
  16888. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  16889. auto prevHotMethod = *hotMethodPtr;
  16890. hotMethod = new BfHotMethod();
  16891. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16892. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  16893. hotDupMethod->mRefCount++;
  16894. prevHotMethod->mReferences.Add(hotDupMethod);
  16895. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  16896. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16897. }
  16898. else if (mCompiler->IsHotCompile())
  16899. {
  16900. // Link the previous version into the mPrevVersion
  16901. BfHotMethod* prevMethod = new BfHotMethod();
  16902. prevMethod->mRefCount = 1;
  16903. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  16904. hotMethod->mPrevVersion = prevMethod;
  16905. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  16906. hotMethod->mSrcTypeVersion = NULL;
  16907. prevMethod->mFlags = hotMethod->mFlags;
  16908. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  16909. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  16910. #ifdef BF_DBG_HOTMETHOD_NAME
  16911. prevMethod->mMangledName = hotMethod->mMangledName;
  16912. #endif
  16913. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  16914. }
  16915. else
  16916. {
  16917. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16918. hotMethod->Clear(true);
  16919. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16920. }
  16921. }
  16922. if (methodInstance->mIsClosure)
  16923. {
  16924. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16925. }
  16926. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16927. hotMethod->mSrcTypeVersion->mRefCount++;
  16928. hotMethod->mRefCount++;
  16929. #ifdef BF_DBG_HOTMETHOD_NAME
  16930. hotMethod->mMangledName = mangledName;
  16931. #endif
  16932. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!mCompiler->IsHotCompile()))
  16933. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  16934. methodInstance->mHotMethod = hotMethod;
  16935. }
  16936. }
  16937. // methodDeclaration is NULL for default constructors
  16938. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16939. {
  16940. BP_ZONE("BfModule::BfMethodDeclaration");
  16941. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  16942. BF_ASSERT((!mContext->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  16943. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16944. // to effectively make mIgnoreWrites method-scoped
  16945. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16946. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16947. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16948. if (mCompiler->IsAutocomplete())
  16949. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16950. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16951. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16952. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16953. if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  16954. {
  16955. BF_ASSERT(mContext->mResolvingVarField);
  16956. isTemporaryFunc = true;
  16957. }
  16958. if (mAwaitingInitFinish)
  16959. FinishInit();
  16960. auto typeInstance = mCurTypeInstance;
  16961. auto typeDef = typeInstance->mTypeDef;
  16962. auto methodDef = mCurMethodInstance->mMethodDef;
  16963. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16964. if (methodDef->mName == "__FATALERRORNAME")
  16965. BFMODULE_FATAL(this, "__FATALERRORNAME");
  16966. if (typeInstance->IsClosure())
  16967. {
  16968. if (methodDef->mName == "Invoke")
  16969. return;
  16970. }
  16971. auto methodInstance = mCurMethodInstance;
  16972. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16973. addToWorkList = false;
  16974. bool hasNonGenericParams = false;
  16975. bool hasGenericParams = false;
  16976. int dependentGenericStartIdx = 0;
  16977. if (methodDef->mIsLocalMethod)
  16978. {
  16979. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16980. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16981. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16982. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16983. // over the local method each time
  16984. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16985. dependentGenericStartIdx = 0;
  16986. if (rootMethodInstance->mMethodInfoEx != NULL)
  16987. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16988. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16989. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16990. }
  16991. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16992. {
  16993. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16994. if (genericArgType->IsGenericParam())
  16995. {
  16996. hasGenericParams = true;
  16997. auto genericParam = (BfGenericParamType*)genericArgType;
  16998. methodInstance->mIsUnspecialized = true;
  16999. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  17000. methodInstance->mIsUnspecializedVariation = true;
  17001. }
  17002. else
  17003. {
  17004. hasNonGenericParams = true;
  17005. if (genericArgType->IsUnspecializedType())
  17006. {
  17007. methodInstance->mIsUnspecialized = true;
  17008. methodInstance->mIsUnspecializedVariation = true;
  17009. }
  17010. }
  17011. }
  17012. if ((hasGenericParams) && (hasNonGenericParams))
  17013. {
  17014. methodInstance->mIsUnspecializedVariation = true;
  17015. }
  17016. if (typeInstance->IsUnspecializedType())
  17017. {
  17018. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  17019. // actually want to do method processing on it
  17020. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  17021. methodInstance->mIsUnspecializedVariation = true;
  17022. methodInstance->mIsUnspecialized = true;
  17023. }
  17024. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  17025. for (auto genericParamDef : methodDef->mGenericParams)
  17026. {
  17027. if (mCompiler->IsAutocomplete())
  17028. {
  17029. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17030. //autoComplete->CheckTypeRef()
  17031. }
  17032. }
  17033. if (methodInstance->mIsUnspecializedVariation)
  17034. {
  17035. }
  17036. if (methodInstance->mIsUnspecializedVariation)
  17037. BF_ASSERT(methodInstance->mIsUnspecialized);
  17038. if (methodDef->mMethodType == BfMethodType_Mixin)
  17039. methodInstance->mIsUnspecialized = true;
  17040. if (methodInstance->mIsUnspecialized)
  17041. {
  17042. //BF_ASSERT(methodInstance->mDeclModule == methodInstance->GetOwner()->mModule);
  17043. }
  17044. BfAutoComplete* bfAutocomplete = NULL;
  17045. if (mCompiler->mResolvePassData != NULL)
  17046. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  17047. if (methodInstance->mMethodInfoEx != NULL)
  17048. {
  17049. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17050. {
  17051. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17052. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17053. {
  17054. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  17055. }
  17056. else
  17057. {
  17058. auto externConstraintDef = genericParam->GetExternConstraintDef();
  17059. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  17060. auto autoComplete = mCompiler->GetAutoComplete();
  17061. if (autoComplete != NULL)
  17062. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  17063. if (genericParam->mExternType != NULL)
  17064. {
  17065. //
  17066. }
  17067. else
  17068. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  17069. }
  17070. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  17071. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17072. {
  17073. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  17074. if (bfAutocomplete != NULL)
  17075. {
  17076. for (auto nameNode : genericParamDef->mNameNodes)
  17077. {
  17078. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  17079. }
  17080. }
  17081. }
  17082. }
  17083. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  17084. {
  17085. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  17086. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17087. if (genericParam->mTypeConstraint != NULL)
  17088. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17089. }
  17090. }
  17091. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  17092. {
  17093. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17094. BfAstNode* nameNode = methodDeclaration->mNameNode;
  17095. if (nameNode == NULL)
  17096. {
  17097. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17098. nameNode = ctorDeclaration->mThisToken;
  17099. }
  17100. if (autoComplete->IsAutocompleteNode(nameNode))
  17101. {
  17102. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  17103. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  17104. autoComplete->mDefType = typeDef;
  17105. autoComplete->mDefMethod = methodDef;
  17106. autoComplete->SetDefinitionLocation(nameNode);
  17107. if (methodDef->mIsOverride)
  17108. {
  17109. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  17110. {
  17111. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  17112. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17113. continue;
  17114. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17115. if (virtMethod != NULL)
  17116. {
  17117. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  17118. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  17119. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  17120. {
  17121. // Is matching method
  17122. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  17123. {
  17124. auto baseType = typeInstance->mBaseType;
  17125. if (baseType != NULL)
  17126. {
  17127. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17128. baseType = baseType->mBaseType;
  17129. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17130. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  17131. autoComplete->mDefType = baseType->mTypeDef;
  17132. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  17133. }
  17134. }
  17135. break;
  17136. }
  17137. }
  17138. }
  17139. }
  17140. }
  17141. }
  17142. bool reportErrors = true;
  17143. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  17144. reportErrors = true;
  17145. // Only the defining contexts needs to report errors here
  17146. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  17147. if (methodDef->mMethodType == BfMethodType_Dtor)
  17148. {
  17149. if (methodDef->mIsStatic)
  17150. {
  17151. }
  17152. else
  17153. {
  17154. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  17155. {
  17156. BfAstNode* refNode = methodDeclaration;
  17157. if (refNode == NULL)
  17158. {
  17159. // Whatever caused this ctor to be generated should have caused another failure
  17160. // But that failure might not be generated until the ctor is generated
  17161. }
  17162. else
  17163. {
  17164. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  17165. if (dtorDecl != NULL)
  17166. refNode = dtorDecl->mThisToken;
  17167. Fail("Structs cannot have destructors", refNode);
  17168. }
  17169. }
  17170. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17171. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  17172. (mCurTypeInstance != mContext->mBfObjectType))
  17173. {
  17174. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  17175. }
  17176. }
  17177. }
  17178. BfType* resolvedReturnType = NULL;
  17179. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  17180. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  17181. (methodDef->mReturnTypeRef != NULL))
  17182. {
  17183. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  17184. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  17185. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  17186. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  17187. {
  17188. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  17189. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17190. }
  17191. if (resolvedReturnType == NULL)
  17192. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17193. }
  17194. else
  17195. {
  17196. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  17197. }
  17198. BF_ASSERT(resolvedReturnType != NULL);
  17199. mCurMethodInstance->mReturnType = resolvedReturnType;
  17200. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  17201. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  17202. //if (!methodInstance->IsSpecializedGenericMethod())
  17203. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  17204. if (methodDef->mExplicitInterface != NULL)
  17205. {
  17206. auto autoComplete = mCompiler->GetAutoComplete();
  17207. if (autoComplete != NULL)
  17208. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  17209. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  17210. BfTypeInstance* explicitInterface = NULL;
  17211. if (explicitType != NULL)
  17212. explicitInterface = explicitType->ToTypeInstance();
  17213. if (explicitInterface != NULL)
  17214. {
  17215. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  17216. if (autoComplete != NULL)
  17217. {
  17218. BfTokenNode* dotToken = NULL;
  17219. BfAstNode* nameNode = NULL;
  17220. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  17221. {
  17222. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  17223. nameNode = methodDeclaration->mNameNode;
  17224. }
  17225. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  17226. }
  17227. }
  17228. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  17229. {
  17230. bool interfaceFound = false;
  17231. for (auto ifaceInst : typeInstance->mInterfaces)
  17232. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  17233. if (!interfaceFound)
  17234. {
  17235. if (methodDef->mMethodDeclaration != NULL)
  17236. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  17237. else
  17238. {
  17239. // For property decls, we should have already given the error during type population
  17240. if (mCompiler->mRevision == 1)
  17241. AssertErrorState();
  17242. }
  17243. }
  17244. }
  17245. }
  17246. bool isThisStruct = mCurTypeInstance->IsStruct();
  17247. BfType* thisType = NULL;
  17248. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  17249. {
  17250. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  17251. {
  17252. thisType = mCurTypeInstance;
  17253. if (thisType == NULL)
  17254. return;
  17255. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  17256. {
  17257. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17258. {
  17259. PopulateType(checkType, BfPopulateType_Data);
  17260. }, thisType);
  17261. }
  17262. }
  17263. else
  17264. {
  17265. thisType = mCurTypeInstance;
  17266. PopulateType(thisType, BfPopulateType_Declaration);
  17267. }
  17268. }
  17269. int implicitParamCount = 0;
  17270. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  17271. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  17272. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  17273. bool hadDelegateParams = false;
  17274. bool hadParams = false;
  17275. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  17276. {
  17277. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  17278. BfParameterDef* paramDef = NULL;
  17279. int paramDefIdx = -1;
  17280. if (paramIdx < implicitParamCount)
  17281. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  17282. else
  17283. {
  17284. paramDefIdx = paramIdx - implicitParamCount;
  17285. paramDef = methodDef->mParams[paramDefIdx];
  17286. }
  17287. if (hadParams)
  17288. break;
  17289. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  17290. continue;
  17291. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  17292. (paramDef->mParamKind != BfParamKind_AppendIdx))
  17293. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  17294. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  17295. {
  17296. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  17297. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  17298. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  17299. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  17300. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  17301. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  17302. }
  17303. BfType* resolvedParamType = NULL;
  17304. if (closureCaptureEntry != NULL)
  17305. resolvedParamType = closureCaptureEntry->mType;
  17306. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  17307. {
  17308. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  17309. resolvedParamType = mContext->mBfObjectType;
  17310. }
  17311. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  17312. {
  17313. if (methodDef->mMethodType != BfMethodType_Mixin)
  17314. {
  17315. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  17316. resolvedParamType = mContext->mBfObjectType;
  17317. }
  17318. else
  17319. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  17320. }
  17321. BfType* unresolvedParamType = resolvedParamType;
  17322. bool wasGenericParam = false;
  17323. if (resolvedParamType == NULL)
  17324. {
  17325. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  17326. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  17327. }
  17328. if (resolvedParamType == NULL)
  17329. {
  17330. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  17331. unresolvedParamType = resolvedParamType;
  17332. if (mCurTypeInstance->IsBoxed())
  17333. {
  17334. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  17335. // If we failed a lookup here then we better have also failed it in the original type
  17336. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  17337. }
  17338. }
  17339. if (!methodInstance->IsSpecializedGenericMethod())
  17340. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  17341. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  17342. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  17343. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  17344. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  17345. {
  17346. BfMethodState methodState;
  17347. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17348. methodState.mTempKind = BfMethodState::TempKind_Static;
  17349. BfTypedValue defaultValue;
  17350. if (resolvedParamType->IsConstExprValue())
  17351. {
  17352. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  17353. BfExprEvaluator exprEvaluator(this);
  17354. exprEvaluator.mExpectingType = constExprType->mType;
  17355. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  17356. defaultValue = exprEvaluator.GetResult();
  17357. }
  17358. else
  17359. {
  17360. BfConstResolver constResolver(this);
  17361. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  17362. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  17363. {
  17364. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  17365. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  17366. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  17367. {
  17368. defaultValue = castedDefaultValue; // Good!
  17369. }
  17370. else if (!CanCast(defaultValue, resolvedParamType))
  17371. {
  17372. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  17373. // a conversion operator.
  17374. // This should throw an error
  17375. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  17376. AssertErrorState();
  17377. if (!defaultValue.mValue.IsConst())
  17378. defaultValue = BfTypedValue();
  17379. }
  17380. }
  17381. }
  17382. if (!defaultValue)
  17383. {
  17384. defaultValue = GetDefaultTypedValue(resolvedParamType);
  17385. if (!defaultValue.mValue.IsConst())
  17386. defaultValue = BfTypedValue();
  17387. }
  17388. if (defaultValue)
  17389. {
  17390. if (defaultValue.mType->IsVar())
  17391. {
  17392. AssertErrorState();
  17393. }
  17394. else
  17395. {
  17396. BF_ASSERT(defaultValue.mValue.IsConst());
  17397. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  17398. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  17399. CurrentAddToConstHolder(defaultValue.mValue);
  17400. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  17401. }
  17402. }
  17403. }
  17404. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  17405. {
  17406. bool addParams = true;
  17407. bool isValid = false;
  17408. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  17409. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  17410. {
  17411. // Span<T>
  17412. isValid = true;
  17413. }
  17414. else if (resolvedParamType->IsArray())
  17415. {
  17416. // Array is the 'normal' params type
  17417. isValid = true;
  17418. }
  17419. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  17420. {
  17421. hadDelegateParams = true;
  17422. // This means we copy the params from a delegate
  17423. BfMethodParam methodParam;
  17424. methodParam.mResolvedType = resolvedParamType;
  17425. methodParam.mParamDefIdx = paramDefIdx;
  17426. methodParam.mDelegateParamIdx = 0;
  17427. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  17428. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  17429. {
  17430. methodParam.mDelegateParamIdx = delegateParamIdx;
  17431. mCurMethodInstance->mParams.Add(methodParam);
  17432. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  17433. if (!methodInstance->IsSpecializedGenericMethod())
  17434. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  17435. }
  17436. isValid = true;
  17437. addParams = false;
  17438. }
  17439. else if (resolvedParamType->IsGenericParam())
  17440. {
  17441. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  17442. if (genericParamInstance->mTypeConstraint != NULL)
  17443. {
  17444. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  17445. if (genericParamInstance->mTypeConstraint->IsArray())
  17446. {
  17447. BfMethodParam methodParam;
  17448. methodParam.mResolvedType = resolvedParamType;
  17449. methodParam.mParamDefIdx = paramDefIdx;
  17450. mCurMethodInstance->mParams.Add(methodParam);
  17451. isValid = true;
  17452. }
  17453. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  17454. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  17455. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  17456. {
  17457. mCurMethodInstance->mHadGenericDelegateParams = true;
  17458. isValid = true;
  17459. addParams = false;
  17460. }
  17461. }
  17462. }
  17463. else
  17464. {
  17465. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  17466. if ((paramTypeInst != NULL) &&
  17467. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  17468. {
  17469. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  17470. isValid = true;
  17471. addParams = false;
  17472. }
  17473. }
  17474. if (!isValid)
  17475. {
  17476. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  17477. // Failure case, make it an Object[]
  17478. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  17479. }
  17480. if (addParams)
  17481. {
  17482. BfMethodParam methodParam;
  17483. methodParam.mResolvedType = resolvedParamType;
  17484. methodParam.mParamDefIdx = paramDefIdx;
  17485. mCurMethodInstance->mParams.push_back(methodParam);
  17486. }
  17487. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  17488. {
  17489. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  17490. }
  17491. }
  17492. else
  17493. {
  17494. BfMethodParam methodParam;
  17495. methodParam.mResolvedType = resolvedParamType;
  17496. methodParam.mParamDefIdx = paramDefIdx;
  17497. mCurMethodInstance->mParams.Add(methodParam);
  17498. }
  17499. }
  17500. if (hadDelegateParams)
  17501. {
  17502. HashSet<String> usedNames;
  17503. Dictionary<int, int> usedParamDefIdx;
  17504. for (auto methodParam : methodDef->mParams)
  17505. {
  17506. usedNames.Add(methodParam->mName);
  17507. }
  17508. for (auto& methodParam : mCurMethodInstance->mParams)
  17509. {
  17510. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  17511. {
  17512. int* refCount = NULL;
  17513. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  17514. (*refCount)++;
  17515. }
  17516. }
  17517. for (auto& methodParam : mCurMethodInstance->mParams)
  17518. {
  17519. if (methodParam.mDelegateParamIdx != -1)
  17520. {
  17521. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  17522. methodParam.mDelegateParamNameCombine = true;
  17523. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  17524. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  17525. if (usedNames.Contains(paramName))
  17526. methodParam.mDelegateParamNameCombine = true;
  17527. }
  17528. }
  17529. }
  17530. int argIdx = 0;
  17531. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  17532. if (!methodDef->mIsStatic)
  17533. {
  17534. auto thisType = methodInstance->GetOwner();
  17535. if (methodInstance->GetParamIsSplat(-1))
  17536. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  17537. else if (!thisType->IsValuelessType())
  17538. {
  17539. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17540. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17541. if (!methodDef->mIsMutating)
  17542. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17543. argIdx++;
  17544. if (loweredTypeCode2 != BfTypeCode_None)
  17545. argIdx++;
  17546. }
  17547. }
  17548. if (methodInstance->GetStructRetIdx() != -1)
  17549. argIdx++;
  17550. for (auto& methodParam : mCurMethodInstance->mParams)
  17551. {
  17552. if (methodParam.mResolvedType->IsMethodRef())
  17553. {
  17554. methodParam.mIsSplat = true;
  17555. }
  17556. else if ((methodParam.mResolvedType->IsComposite()) && (methodInstance->AllowsSplatting()))
  17557. {
  17558. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  17559. if (methodParam.mResolvedType->IsSplattable())
  17560. {
  17561. int splatCount = methodParam.mResolvedType->GetSplatCount();
  17562. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  17563. {
  17564. methodParam.mIsSplat = true;
  17565. argIdx += splatCount;
  17566. continue;
  17567. }
  17568. }
  17569. }
  17570. argIdx++;
  17571. }
  17572. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  17573. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  17574. {
  17575. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  17576. }
  17577. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  17578. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  17579. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  17580. (!methodDef->mIsSkipCall))
  17581. {
  17582. if (methodDeclaration->mEndSemicolon == NULL)
  17583. {
  17584. AssertParseErrorState();
  17585. }
  17586. else
  17587. {
  17588. bool isError = true;
  17589. if (typeInstance->IsTypedPrimitive())
  17590. {
  17591. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17592. {
  17593. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  17594. {
  17595. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  17596. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  17597. {
  17598. isError = false;
  17599. }
  17600. }
  17601. }
  17602. }
  17603. if (isError)
  17604. {
  17605. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  17606. MethodToString(methodInstance).c_str()),
  17607. methodDef->GetRefNode());
  17608. }
  17609. }
  17610. }
  17611. if (methodDef->IsEmptyPartial())
  17612. hasExternSpecifier = true;
  17613. if (!methodInstance->IsAutocompleteMethod())
  17614. {
  17615. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17616. int implicitParamCount = methodInstance->GetImplicitParamCount();
  17617. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  17618. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  17619. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  17620. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  17621. int paramIdx = 0;
  17622. int defaultParamIdx = 0;
  17623. while (true)
  17624. {
  17625. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  17626. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  17627. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  17628. {
  17629. paramIdx++;
  17630. continue;
  17631. }
  17632. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  17633. {
  17634. defaultParamIdx++;
  17635. continue;
  17636. }
  17637. if ((isDone) || (isDefaultDone))
  17638. {
  17639. // 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
  17640. // to cause us to throw an assertion in the declaration here
  17641. if (!defaultMethodInstance->mHadGenericDelegateParams)
  17642. BF_ASSERT((isDone) && (isDefaultDone));
  17643. break;
  17644. }
  17645. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  17646. if (paramType->IsRef())
  17647. paramType = paramType->GetUnderlyingType();
  17648. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  17649. paramIdx++;
  17650. defaultParamIdx++;
  17651. }
  17652. }
  17653. StringT<128> mangledName;
  17654. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17655. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  17656. {
  17657. auto paramType = methodInstance->GetParamType(paramIdx);
  17658. if (paramType->IsComposite())
  17659. PopulateType(paramType, BfPopulateType_Data);
  17660. if (!methodInstance->IsParamSkipped(paramIdx))
  17661. {
  17662. if (paramType->IsStruct())
  17663. {
  17664. //
  17665. }
  17666. else
  17667. {
  17668. PopulateType(paramType, BfPopulateType_Declaration);
  17669. }
  17670. }
  17671. }
  17672. // Only process method in default unspecialized mode, not in variations
  17673. if (methodInstance->mIsUnspecializedVariation)
  17674. return;
  17675. PopulateType(resolvedReturnType, BfPopulateType_Data);
  17676. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  17677. if (resolvedReturnType->IsValuelessType())
  17678. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  17679. if (!mBfIRBuilder->mIgnoreWrites)
  17680. {
  17681. bool isIntrinsic = false;
  17682. if (!methodInstance->mIRFunction)
  17683. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  17684. if (isIntrinsic)
  17685. {
  17686. addToWorkList = false;
  17687. }
  17688. }
  17689. auto func = methodInstance->mIRFunction;
  17690. // if (methodInstance->mIsReified)
  17691. // CheckHotMethod(methodInstance, mangledName);
  17692. 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);
  17693. SizedArray<BfIRMDNode, 8> diParams;
  17694. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  17695. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  17696. {
  17697. //CS0708
  17698. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  17699. }
  17700. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  17701. {
  17702. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  17703. methodDef->mIsVirtual = false;
  17704. }
  17705. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  17706. {
  17707. if (methodDef->mIsStatic)
  17708. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  17709. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  17710. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  17711. else if (methodDef->mMethodType == BfMethodType_Ctor)
  17712. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  17713. else if (methodDef->mMethodType == BfMethodType_Dtor)
  17714. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  17715. }
  17716. if (isTemporaryFunc)
  17717. {
  17718. // This handles temporary methods for autocomplete types
  17719. //BF_ASSERT(mIsScratchModule);
  17720. //BF_ASSERT(mCompiler->IsAutocomplete());
  17721. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  17722. return; // Bail out early for autocomplete pass
  17723. }
  17724. if ((methodInstance->GetImportCallKind() != BfImportCallKind_None) && (!mBfIRBuilder->mIgnoreWrites) && (!methodInstance->mIRFunction))
  17725. {
  17726. BfLogSysM("DllImportGlobalVar DoMethodDeclaration processing %p\n", methodInstance);
  17727. // If this is in an extension then we did create the global variable already in the original obj
  17728. bool doDefine = mExtensionCount == 0;
  17729. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, doDefine);
  17730. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17731. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17732. }
  17733. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  17734. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  17735. // autocompleter. Why did we have this check anyway?
  17736. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  17737. {
  17738. AddMethodReference(methodInstance);
  17739. mFuncReferences[methodInstance] = func;
  17740. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  17741. }*/
  17742. if (mParentModule != NULL)
  17743. {
  17744. // For extension modules we need to keep track of our own methods so we can know which methods
  17745. // we have defined ourselves and which are from the parent module or other extensions
  17746. if (!func.IsFake())
  17747. mFuncReferences[methodInstance] = func;
  17748. }
  17749. if (addToWorkList)
  17750. {
  17751. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  17752. if (wasAwaitingDecl)
  17753. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  17754. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  17755. {
  17756. if (!wasAwaitingDecl)
  17757. AddMethodToWorkList(methodInstance);
  17758. }
  17759. else
  17760. {
  17761. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  17762. methodInstance->mIgnoreBody = true;
  17763. if (typeInstance->IsUnspecializedType())
  17764. {
  17765. // Don't hold on to actual Function for unspecialized types
  17766. methodInstance->mIRFunction = BfIRFunction();
  17767. }
  17768. }
  17769. }
  17770. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  17771. (!methodDef->mIsLocalMethod) &&
  17772. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  17773. (!methodDef->mReturnTypeRef->IsTemporary()))
  17774. {
  17775. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  17776. {
  17777. //TODO:
  17778. //CS0053
  17779. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  17780. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  17781. methodDef->mReturnTypeRef, true);
  17782. }
  17783. else
  17784. {
  17785. //CS0050
  17786. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  17787. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  17788. methodDef->mReturnTypeRef, true);
  17789. }
  17790. }
  17791. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  17792. {
  17793. Fail("Interfaces cannot contain constructors", methodDeclaration);
  17794. }
  17795. // Don't compare specialized generic methods against normal methods
  17796. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  17797. (!methodDef->mIsLocalMethod))
  17798. {
  17799. if (!methodInstance->mIsForeignMethodDef)
  17800. {
  17801. typeDef->PopulateMemberSets();
  17802. BfMethodDef* nextMethod = NULL;
  17803. BfMemberSetEntry* entry = NULL;
  17804. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17805. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17806. while (nextMethod != NULL)
  17807. {
  17808. auto checkMethod = nextMethod;
  17809. nextMethod = nextMethod->mNextWithSameName;
  17810. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  17811. {
  17812. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17813. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  17814. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17815. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17816. {
  17817. bool canChain = false;
  17818. if ((methodDef->mParams.empty()) &&
  17819. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  17820. {
  17821. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  17822. canChain = true;
  17823. else if (methodDef->mMethodType == BfMethodType_Normal)
  17824. {
  17825. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  17826. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  17827. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  17828. canChain = true;
  17829. }
  17830. }
  17831. if (canChain)
  17832. {
  17833. bool isBetter;
  17834. bool isWorse;
  17835. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  17836. if (isBetter && !isWorse)
  17837. {
  17838. methodInstance->mChainType = BfMethodChainType_ChainHead;
  17839. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  17840. }
  17841. else
  17842. {
  17843. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  17844. methodInstance->mChainType = BfMethodChainType_ChainMember;
  17845. }
  17846. }
  17847. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  17848. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  17849. {
  17850. // We're allowed to override an empty-bodied method
  17851. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  17852. }
  17853. else
  17854. {
  17855. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  17856. continue;
  17857. bool silentlyAllow = false;
  17858. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  17859. {
  17860. if (typeInstance->IsInterface())
  17861. {
  17862. if (methodDef->mIsOverride)
  17863. silentlyAllow = true;
  17864. }
  17865. else
  17866. silentlyAllow = true;
  17867. }
  17868. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  17869. silentlyAllow = true;
  17870. if (!silentlyAllow)
  17871. {
  17872. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  17873. {
  17874. auto refNode = methodDef->GetRefNode();
  17875. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  17876. if (bfError != NULL)
  17877. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  17878. }
  17879. }
  17880. }
  17881. }
  17882. }
  17883. }
  17884. }
  17885. // Virtual methods give their error while slotting
  17886. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  17887. (!methodDef->mIsLocalMethod) &&
  17888. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  17889. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  17890. {
  17891. bool foundHiddenMethod = false;
  17892. auto baseType = typeInstance->mBaseType;
  17893. while (baseType != NULL)
  17894. {
  17895. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  17896. auto baseTypeDef = baseType->mTypeDef;
  17897. baseTypeDef->PopulateMemberSets();
  17898. BfMethodDef* checkMethod = NULL;
  17899. BfMemberSetEntry* entry = NULL;
  17900. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17901. checkMethod = (BfMethodDef*)entry->mMemberDef;
  17902. while (checkMethod != NULL)
  17903. {
  17904. if (checkMethod->mMethodDeclaration == NULL)
  17905. continue;
  17906. if (baseType->mMethodInstanceGroups.size() == 0)
  17907. {
  17908. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  17909. break;
  17910. }
  17911. if (checkMethod == methodDef)
  17912. continue;
  17913. if (checkMethod->mName != methodDef->mName)
  17914. continue;
  17915. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  17916. if (checkMethodInstance != NULL)
  17917. {
  17918. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17919. (checkMethod->mProtection != BfProtection_Private) &&
  17920. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17921. {
  17922. if (!methodDef->mIsNew)
  17923. {
  17924. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  17925. if (refNode != NULL)
  17926. {
  17927. 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?
  17928. if (bfError != NULL)
  17929. bfError->mIsPersistent = true;
  17930. }
  17931. }
  17932. foundHiddenMethod = true;
  17933. break;
  17934. }
  17935. }
  17936. checkMethod = checkMethod->mNextWithSameName;
  17937. }
  17938. if (foundHiddenMethod)
  17939. break;
  17940. baseType = baseType->mBaseType;
  17941. }
  17942. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  17943. {
  17944. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17945. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  17946. methodDeclaration->mNewSpecifier;
  17947. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  17948. }
  17949. }
  17950. }
  17951. mCompiler->mStats.mMethodDeclarations++;
  17952. mCompiler->UpdateCompletion();
  17953. }
  17954. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  17955. {
  17956. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  17957. auto typeInstance = mCurTypeInstance;
  17958. auto methodDef = methodInstance->mMethodDef;
  17959. int virtualMethodMatchIdx = -1;
  17960. if (typeInstance->mHotTypeData != NULL)
  17961. {
  17962. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  17963. {
  17964. BF_ASSERT(mCompiler->IsHotCompile());
  17965. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  17966. // may slot this override anyway (?)
  17967. int vTableStart = 0;
  17968. auto implBaseType = typeInstance->GetImplBaseType();
  17969. if (implBaseType != NULL)
  17970. vTableStart = implBaseType->mVirtualMethodTableSize;
  17971. StringT<128> mangledName;
  17972. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17973. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  17974. {
  17975. // O(1) checking when virtual methods haven't changed
  17976. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  17977. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  17978. if (mangledName == entry.mFuncName)
  17979. {
  17980. virtualMethodMatchIdx = vTableStart + checkIdx;
  17981. break;
  17982. }
  17983. }
  17984. if (virtualMethodMatchIdx != -1)
  17985. {
  17986. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17987. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  17988. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  17989. }
  17990. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  17991. }
  17992. }
  17993. if (virtualMethodMatchIdx == -1)
  17994. {
  17995. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  17996. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  17997. typeInstance->mVirtualMethodTable.push_back(entry);
  17998. }
  17999. }
  18000. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  18001. {
  18002. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  18003. {
  18004. // When we provide an extension override in the same project a root type override
  18005. isBetter = true;
  18006. isWorse = false;
  18007. }
  18008. else
  18009. {
  18010. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18011. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18012. }
  18013. }
  18014. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  18015. {
  18016. BP_ZONE("BfModule::SlotVirtualMethod");
  18017. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  18018. return false;
  18019. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  18020. {
  18021. if (!mCompiler->mOptions.mAllowHotSwapping)
  18022. return;
  18023. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  18024. return;
  18025. if (methodInstance->mHotMethod == NULL)
  18026. CheckHotMethod(methodInstance, "");
  18027. if (methodInstance->mHotMethod == NULL)
  18028. return;
  18029. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  18030. if (declMethodInstance->mHotMethod == NULL)
  18031. CheckHotMethod(declMethodInstance, "");
  18032. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  18033. virtualDecl->mRefCount++;
  18034. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  18035. };
  18036. auto typeInstance = mCurTypeInstance;
  18037. auto typeDef = typeInstance->mTypeDef;
  18038. auto methodDef = methodInstance->mMethodDef;
  18039. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18040. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18041. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18042. BfAstNode* declaringNode = methodDeclaration;
  18043. if (propertyMethodDeclaration != NULL)
  18044. declaringNode = propertyMethodDeclaration->mNameNode;
  18045. BfMethodInstance* methodOverriden = NULL;
  18046. bool usedMethod = false;
  18047. BfTokenNode* virtualToken = NULL;
  18048. if (propertyDeclaration != NULL)
  18049. virtualToken = propertyDeclaration->mVirtualSpecifier;
  18050. else if (methodDeclaration != NULL)
  18051. virtualToken = methodDeclaration->mVirtualSpecifier;
  18052. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  18053. {
  18054. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  18055. }
  18056. else if (methodDef->mIsVirtual)
  18057. {
  18058. if (mCompiler->IsHotCompile())
  18059. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  18060. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  18061. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  18062. BfTypeInstance* checkBase = typeInstance;
  18063. // If we are in an extension, look in ourselves first
  18064. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  18065. checkBase = checkBase->mBaseType;
  18066. if (typeInstance->IsValueType())
  18067. {
  18068. if (typeInstance->mBaseType == NULL)
  18069. return false; // It's actually ValueType
  18070. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  18071. if (!methodDef->mIsOverride)
  18072. {
  18073. Fail("Structs cannot have virtual methods", virtualToken, true);
  18074. return false;
  18075. }
  18076. checkBase = mContext->mBfObjectType;
  18077. if (checkBase->mVirtualMethodTableSize == 0)
  18078. PopulateType(checkBase, BfPopulateType_Full);
  18079. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  18080. return false; // System circular ref, don't do struct checking on those
  18081. }
  18082. int virtualMethodMatchIdx = -1;
  18083. bool hadHidingError = false;
  18084. BfMethodInstance* bestOverrideMethodInstance = NULL;
  18085. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  18086. int bestOverrideMethodIdx = -1;
  18087. int ambiguousOverrideMethodIdx = -1;
  18088. if (checkBase != NULL)
  18089. {
  18090. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18091. auto lookupType = checkBase;
  18092. while (lookupType != NULL)
  18093. {
  18094. lookupType->mTypeDef->PopulateMemberSets();
  18095. BfMethodDef* nextMethodDef = NULL;
  18096. BfMemberSetEntry* entry;
  18097. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  18098. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  18099. while (nextMethodDef != NULL)
  18100. {
  18101. auto checkMethodDef = nextMethodDef;
  18102. nextMethodDef = nextMethodDef->mNextWithSameName;
  18103. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  18104. continue;
  18105. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  18106. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  18107. continue;
  18108. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  18109. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  18110. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  18111. {
  18112. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  18113. continue;
  18114. }
  18115. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18116. if (baseMethodInstance == NULL)
  18117. {
  18118. AssertErrorState();
  18119. continue;
  18120. }
  18121. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  18122. {
  18123. if (methodDef->mIsOverride)
  18124. {
  18125. BfMethodInstance* checkMethodInstance;
  18126. if (typeInstance->IsValueType())
  18127. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18128. else
  18129. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18130. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  18131. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  18132. continue;
  18133. if (bestOverrideMethodInstance != NULL)
  18134. {
  18135. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  18136. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18137. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18138. if (isBetter == isWorse)
  18139. {
  18140. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  18141. }
  18142. else
  18143. {
  18144. if (isWorse)
  18145. continue;
  18146. ambiguousOverrideMethodInstance = NULL;
  18147. }
  18148. }
  18149. bestOverrideMethodInstance = checkMethodInstance;
  18150. bestOverrideMethodIdx = checkMethodIdx;
  18151. }
  18152. else
  18153. {
  18154. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  18155. {
  18156. if (!hadHidingError)
  18157. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  18158. hadHidingError = true;
  18159. }
  18160. }
  18161. }
  18162. }
  18163. lookupType = lookupType->mBaseType;
  18164. }
  18165. }
  18166. //TODO:
  18167. if ((checkBase != NULL)
  18168. && (false)
  18169. )
  18170. {
  18171. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18172. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  18173. {
  18174. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  18175. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  18176. {
  18177. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  18178. continue;
  18179. }
  18180. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18181. if (baseMethodInstance == NULL)
  18182. {
  18183. AssertErrorState();
  18184. continue;
  18185. }
  18186. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  18187. {
  18188. if (methodDef->mIsOverride)
  18189. {
  18190. BfMethodInstance* checkMethodInstance;
  18191. if (typeInstance->IsValueType())
  18192. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18193. else
  18194. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18195. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  18196. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  18197. continue;
  18198. if (bestOverrideMethodInstance != NULL)
  18199. {
  18200. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  18201. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18202. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18203. if (isBetter == isWorse)
  18204. {
  18205. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  18206. }
  18207. else
  18208. {
  18209. if (isWorse)
  18210. continue;
  18211. ambiguousOverrideMethodInstance = NULL;
  18212. }
  18213. }
  18214. bestOverrideMethodInstance = checkMethodInstance;
  18215. bestOverrideMethodIdx = checkMethodIdx;
  18216. }
  18217. else
  18218. {
  18219. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  18220. {
  18221. if (!hadHidingError)
  18222. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  18223. hadHidingError = true;
  18224. }
  18225. }
  18226. }
  18227. }
  18228. }
  18229. if (bestOverrideMethodInstance != NULL)
  18230. {
  18231. if (ambiguousOverrideMethodInstance != NULL)
  18232. {
  18233. bool allow = false;
  18234. // 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.
  18235. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  18236. bool canSeeEachOther = false;
  18237. //
  18238. {
  18239. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  18240. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  18241. canSeeEachOther = true;
  18242. }
  18243. //
  18244. {
  18245. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  18246. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  18247. canSeeEachOther = true;
  18248. }
  18249. if (!canSeeEachOther)
  18250. {
  18251. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  18252. }
  18253. else
  18254. {
  18255. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  18256. if (error != NULL)
  18257. {
  18258. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  18259. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  18260. }
  18261. }
  18262. }
  18263. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18264. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  18265. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  18266. {
  18267. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  18268. {
  18269. BfTypeReference* returnTypeRef;
  18270. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18271. {
  18272. returnTypeRef = propertyDeclaration->mTypeRef;
  18273. Fail("Property differs from overridden property by type", returnTypeRef, true);
  18274. }
  18275. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  18276. {
  18277. returnTypeRef = methodDeclaration->mReturnType;
  18278. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  18279. }
  18280. else
  18281. {
  18282. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  18283. }
  18284. return usedMethod;
  18285. }
  18286. }
  18287. if (methodDef->mIsOverride)
  18288. {
  18289. // We can have multiple matches when a virtual method is used to implement interface methods
  18290. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  18291. // vtable entries for this method signature
  18292. virtualMethodMatchIdx = bestOverrideMethodIdx;
  18293. if (!typeInstance->IsValueType())
  18294. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  18295. if (typeInstance->IsValueType())
  18296. {
  18297. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  18298. }
  18299. else
  18300. {
  18301. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  18302. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  18303. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  18304. {
  18305. methodOverriden = overridenRef;
  18306. BfMethodInstance* setMethodInstance = methodInstance;
  18307. bool doOverride = true;
  18308. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  18309. {
  18310. bool isBetter = false;
  18311. bool isWorse = false;
  18312. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  18313. if (isBetter == isWorse)
  18314. {
  18315. // We have to resolve later per-project
  18316. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  18317. {
  18318. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  18319. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  18320. }
  18321. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  18322. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  18323. doOverride = false;
  18324. }
  18325. else
  18326. {
  18327. if ((isBetter) && (ambiguityContext != NULL))
  18328. {
  18329. ambiguityContext->Remove(virtualMethodMatchIdx);
  18330. }
  18331. doOverride = isBetter;
  18332. }
  18333. }
  18334. if (doOverride)
  18335. {
  18336. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  18337. _AddVirtualDecl(declMethodInstance);
  18338. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  18339. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  18340. }
  18341. }
  18342. }
  18343. if (methodOverriden != NULL)
  18344. {
  18345. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  18346. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  18347. {
  18348. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  18349. BfAstNode* protectionRefNode = NULL;
  18350. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  18351. {
  18352. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  18353. if (protectionRefNode == NULL)
  18354. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  18355. if (protectionRefNode == NULL)
  18356. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  18357. }
  18358. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  18359. {
  18360. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  18361. if (protectionRefNode == NULL)
  18362. protectionRefNode = methodDeclaration->mNameNode;
  18363. }
  18364. if (protectionRefNode != NULL)
  18365. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  18366. }
  18367. }
  18368. }
  18369. }
  18370. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  18371. {
  18372. if (methodDef->mIsOverride)
  18373. {
  18374. BfTokenNode* overrideToken = NULL;
  18375. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  18376. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  18377. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  18378. overrideToken = methodDeclaration->mVirtualSpecifier;
  18379. if (overrideToken != NULL)
  18380. {
  18381. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  18382. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  18383. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  18384. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  18385. else
  18386. Fail("No suitable method found to override", overrideToken, true);
  18387. }
  18388. return usedMethod;
  18389. }
  18390. UniqueSlotVirtualMethod(methodInstance);
  18391. }
  18392. else
  18393. usedMethod = true;
  18394. if (typeInstance->IsValueType())
  18395. return usedMethod;
  18396. }
  18397. bool foundInterface = false;
  18398. bool hadAnyMatch = false;
  18399. // See if this method matches interfaces
  18400. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  18401. {
  18402. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  18403. if (ifaceInst->IsIncomplete())
  18404. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  18405. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  18406. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  18407. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  18408. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  18409. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  18410. continue;
  18411. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  18412. continue;
  18413. bool hadMatch = false;
  18414. BfMethodInstance* hadNameMatch = NULL;
  18415. BfType* expectedReturnType = NULL;
  18416. bool showedError = false;
  18417. // We go through our VTable looking for NULL entries within the interface sections
  18418. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  18419. // because a normal method declared in this type could have matched earlier
  18420. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  18421. ifaceInst->mTypeDef->PopulateMemberSets();
  18422. BfMethodDef* checkMethodDef = NULL;
  18423. BfMemberSetEntry* entry;
  18424. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  18425. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  18426. while (checkMethodDef != NULL)
  18427. {
  18428. int iMethodIdx = checkMethodDef->mIdx;
  18429. int iTableIdx = iMethodIdx + startIdx;
  18430. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  18431. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  18432. bool storeIFaceMethod = false;
  18433. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  18434. continue;
  18435. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  18436. auto iMethodInst = iMethodGroup.mDefault;
  18437. if (iMethodInst == NULL)
  18438. {
  18439. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  18440. AssertErrorState();
  18441. continue;
  18442. }
  18443. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  18444. hadNameMatch = iMethodInst;
  18445. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  18446. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  18447. {
  18448. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  18449. }
  18450. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  18451. {
  18452. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  18453. {
  18454. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  18455. {
  18456. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  18457. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  18458. if (error != NULL)
  18459. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  18460. showedError = true;
  18461. }
  18462. }
  18463. }
  18464. if (doesMethodSignatureMatch)
  18465. {
  18466. usedMethod = true;
  18467. hadMatch = true;
  18468. hadAnyMatch = true;
  18469. storeIFaceMethod = true;
  18470. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  18471. {
  18472. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  18473. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  18474. {
  18475. // When autocompletion regenerates a single method body but not the whole type then
  18476. // we will see ourselves in the vtable already
  18477. return usedMethod;
  18478. }
  18479. bool isBetter = false;
  18480. bool isWorse = false;
  18481. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  18482. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  18483. if (isBetter == isWorse)
  18484. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  18485. if (isBetter == isWorse)
  18486. {
  18487. if (ambiguityContext != NULL)
  18488. {
  18489. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  18490. }
  18491. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  18492. storeIFaceMethod = true;
  18493. }
  18494. else
  18495. {
  18496. if ((isBetter) && (ambiguityContext != NULL))
  18497. ambiguityContext->Remove(~iTableIdx);
  18498. storeIFaceMethod = isBetter;
  18499. }
  18500. }
  18501. }
  18502. if (storeIFaceMethod)
  18503. {
  18504. if (methodInstance->GetNumGenericParams() != 0)
  18505. _AddVirtualDecl(iMethodInst);
  18506. *iMethodPtr = methodInstance;
  18507. }
  18508. checkMethodDef = checkMethodDef->mNextWithSameName;
  18509. }
  18510. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  18511. {
  18512. if (expectedReturnType != NULL)
  18513. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  18514. else if (hadNameMatch != NULL)
  18515. {
  18516. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  18517. if (error != NULL)
  18518. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  18519. }
  18520. else
  18521. {
  18522. auto propertyDecl = methodDef->GetPropertyDeclaration();
  18523. if (propertyDecl != NULL)
  18524. {
  18525. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  18526. String name;
  18527. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  18528. name = "this[]";
  18529. else if (propertyDecl->mNameNode != NULL)
  18530. propertyDecl->mNameNode->ToString(name);
  18531. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  18532. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  18533. }
  18534. else
  18535. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  18536. }
  18537. }
  18538. }
  18539. // Any overriden virtual methods that were used in interfaces also need to be replaced
  18540. if (methodOverriden != NULL)
  18541. {
  18542. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  18543. {
  18544. if (methodEntry.mMethodRef == methodOverriden)
  18545. methodEntry.mMethodRef = methodInstance;
  18546. }
  18547. }
  18548. return usedMethod;
  18549. }
  18550. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  18551. {
  18552. auto typeInstance = mCurTypeInstance;
  18553. auto methodDef = methodInstance->mMethodDef;
  18554. if (methodDef->mMethodType == BfMethodType_Ctor)
  18555. return true;
  18556. bool foundOverride = false;
  18557. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  18558. {
  18559. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  18560. }
  18561. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  18562. {
  18563. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  18564. }
  18565. BfAstNode* declaringNode = methodDef->GetRefNode();
  18566. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  18567. {
  18568. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  18569. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  18570. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  18571. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  18572. continue;
  18573. ifaceInst->mTypeDef->PopulateMemberSets();
  18574. BfMethodDef* nextMethod = NULL;
  18575. BfMemberSetEntry* entry = NULL;
  18576. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18577. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18578. while (nextMethod != NULL)
  18579. {
  18580. auto checkMethod = nextMethod;
  18581. nextMethod = nextMethod->mNextWithSameName;
  18582. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  18583. if (ifaceMethod == NULL)
  18584. continue;
  18585. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  18586. {
  18587. if (methodDef->mIsOverride)
  18588. {
  18589. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  18590. {
  18591. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  18592. if (error != NULL)
  18593. {
  18594. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  18595. }
  18596. }
  18597. foundOverride = true;
  18598. }
  18599. else if (!methodDef->mIsNew)
  18600. {
  18601. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  18602. }
  18603. }
  18604. }
  18605. }
  18606. if ((methodDef->mIsOverride) && (!foundOverride))
  18607. {
  18608. // This allows us to declare a method in the base definition or in an extension and then provide
  18609. // an implementation in a more-specific extension
  18610. typeInstance->mTypeDef->PopulateMemberSets();
  18611. BfMethodDef* nextMethod = NULL;
  18612. BfMemberSetEntry* entry = NULL;
  18613. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18614. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18615. while (nextMethod != NULL)
  18616. {
  18617. auto checkMethod = nextMethod;
  18618. nextMethod = nextMethod->mNextWithSameName;
  18619. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  18620. if (ifaceMethod == NULL)
  18621. continue;
  18622. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  18623. continue;
  18624. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  18625. {
  18626. foundOverride = true;
  18627. }
  18628. }
  18629. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  18630. // {
  18631. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  18632. // if (ifaceMethod == NULL)
  18633. // continue;
  18634. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  18635. // continue;
  18636. //
  18637. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  18638. // {
  18639. // foundOverride = true;
  18640. // }
  18641. // }
  18642. }
  18643. if (methodDef->mIsOverride)
  18644. {
  18645. if (!foundOverride)
  18646. {
  18647. BfTokenNode* overrideToken = NULL;
  18648. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18649. overrideToken = propertyDeclaration->mVirtualSpecifier;
  18650. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  18651. overrideToken = methodDeclaration->mVirtualSpecifier;
  18652. if (overrideToken != NULL)
  18653. {
  18654. Fail("No suitable method found to override", overrideToken, true);
  18655. }
  18656. else
  18657. {
  18658. // Possible cause - DTOR with params
  18659. AssertErrorState();
  18660. }
  18661. }
  18662. return true;
  18663. }
  18664. // Generic methods can't be called virtually
  18665. if (methodInstance->GetNumGenericParams() != 0)
  18666. return true;
  18667. // Only public methods can be called virtually
  18668. if (methodDef->mProtection != BfProtection_Public)
  18669. return true;
  18670. UniqueSlotVirtualMethod(methodInstance);
  18671. return true;
  18672. }
  18673. void BfModule::DbgFinish()
  18674. {
  18675. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  18676. return;
  18677. if (mAwaitingInitFinish)
  18678. FinishInit();
  18679. if (mHasForceLinkMarker)
  18680. return;
  18681. String markerName;
  18682. BfIRValue linkMarker;
  18683. if (mBfIRBuilder->DbgHasInfo())
  18684. {
  18685. bool needForceLinking = false;
  18686. for (auto& ownedType : mOwnedTypeInstances)
  18687. {
  18688. bool hasConfirmedReference = false;
  18689. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  18690. {
  18691. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  18692. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  18693. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  18694. {
  18695. hasConfirmedReference = true;
  18696. }
  18697. }
  18698. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  18699. needForceLinking = true;
  18700. }
  18701. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  18702. {
  18703. BfMethodState methodState;
  18704. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18705. methodState.mTempKind = BfMethodState::TempKind_Static;
  18706. mHasForceLinkMarker = true;
  18707. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  18708. SizedArray<BfIRType, 0> paramTypes;
  18709. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  18710. String linkName = "FORCELINKMOD_" + mModuleName;
  18711. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  18712. mBfIRBuilder->SetActiveFunction(func);
  18713. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  18714. mBfIRBuilder->SetInsertPoint(entryBlock);
  18715. auto firstType = mOwnedTypeInstances[0];
  18716. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  18717. SizedArray<BfIRMDNode, 1> diParamTypes;
  18718. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  18719. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  18720. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  18721. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  18722. methodState.mCurScope->mDIScope = diScope;
  18723. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  18724. SizedArray<BfIRValue, 8> args;
  18725. BfExprEvaluator exprEvaluator(this);
  18726. for (auto& ownedType : mOwnedTypeInstances)
  18727. {
  18728. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  18729. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  18730. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  18731. }
  18732. mBfIRBuilder->CreateRetVoid();
  18733. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  18734. }
  18735. }
  18736. }
  18737. bool BfModule::Finish()
  18738. {
  18739. BP_ZONE("BfModule::Finish");
  18740. BfLogSysM("BfModule finish: %p\n", this);
  18741. if (mHadBuildError)
  18742. {
  18743. // Don't AssertErrorState here, this current pass may not have failed but
  18744. // the module was still queued in mFinishedModuleWorkList
  18745. ClearModule();
  18746. return true;
  18747. }
  18748. if (mUsedSlotCount != -1)
  18749. {
  18750. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  18751. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  18752. }
  18753. BF_ASSERT(mAddedToCount);
  18754. mAddedToCount = false;
  18755. mAwaitingFinish = false;
  18756. mCompiler->mStats.mModulesFinished++;
  18757. if (HasCompiledOutput())
  18758. {
  18759. DbgFinish();
  18760. if (mAwaitingInitFinish)
  18761. FinishInit();
  18762. for (auto ownedTypeInst : mOwnedTypeInstances)
  18763. {
  18764. // Generate dbg info and add global variables if we haven't already
  18765. mBfIRBuilder->PopulateType(ownedTypeInst);
  18766. }
  18767. if (mBfIRBuilder->DbgHasInfo())
  18768. {
  18769. mBfIRBuilder->DbgFinalize();
  18770. }
  18771. String objOutputPath;
  18772. String irOutputPath;
  18773. mIsModuleMutable = false;
  18774. //mOutFileNames.Clear();
  18775. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  18776. bool writeModule = mBfIRBuilder->HasExports();
  18777. String outputPath;
  18778. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  18779. auto& compilerOpts = mCompiler->mOptions;
  18780. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  18781. auto moduleOptions = GetModuleOptions();
  18782. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  18783. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  18784. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  18785. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  18786. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  18787. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  18788. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  18789. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  18790. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  18791. bool allowWriteToLib = true;
  18792. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  18793. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  18794. {
  18795. codeGenOptions.mWriteToLib = true;
  18796. mWroteToLib = true;
  18797. }
  18798. else
  18799. {
  18800. mWroteToLib = false;
  18801. }
  18802. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  18803. {
  18804. outputPath = mModuleName;
  18805. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  18806. BfModuleFileName moduleFileName;
  18807. if (mParentModule != NULL)
  18808. {
  18809. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  18810. {
  18811. if (checkPair.mValue == this)
  18812. moduleFileName.mProjects = checkPair.mKey;
  18813. }
  18814. }
  18815. moduleFileName.mProjects.Add(mProject);
  18816. if (fileIdx > 0)
  18817. outputPath += StrFormat("@%d", fileIdx + 1);
  18818. if (mCompiler->mOptions.mWriteIR)
  18819. irOutputPath = outputPath + ".ll";
  18820. if (mCompiler->mOptions.mGenerateObj)
  18821. {
  18822. objOutputPath = outputPath + BF_OBJ_EXT;
  18823. moduleFileName.mFileName = objOutputPath;
  18824. }
  18825. else if (mCompiler->mOptions.mWriteIR)
  18826. {
  18827. moduleFileName.mFileName = irOutputPath;
  18828. }
  18829. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  18830. {
  18831. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  18832. }
  18833. moduleFileName.mModuleWritten = writeModule;
  18834. moduleFileName.mWroteToLib = mWroteToLib;
  18835. if (!mOutFileNames.Contains(moduleFileName))
  18836. mOutFileNames.Add(moduleFileName);
  18837. }
  18838. if (mCompiler->IsHotCompile())
  18839. {
  18840. codeGenOptions.mIsHotCompile = true;
  18841. if (mParentModule != NULL)
  18842. mParentModule->mHadHotObjectWrites = true;
  18843. mHadHotObjectWrites = true;
  18844. }
  18845. //TODO: Testing VDATA
  18846. /*if (mModuleName == "vdata")
  18847. {
  18848. codeGenOptions.mOptLevel = 4;
  18849. }*/
  18850. codeGenOptions.GenerateHash();
  18851. BP_ZONE("BfModule::Finish.WriteObjectFile");
  18852. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  18853. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  18854. mLastModuleWrittenRevision = mCompiler->mRevision;
  18855. }
  18856. else
  18857. {
  18858. for (auto type : mOwnedTypeInstances)
  18859. {
  18860. BF_ASSERT(!type->IsIncomplete());
  18861. }
  18862. }
  18863. for (auto& specModulePair : mSpecializedMethodModules)
  18864. {
  18865. auto specModule = specModulePair.mValue;
  18866. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  18867. {
  18868. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  18869. }
  18870. }
  18871. CleanupFileInstances();
  18872. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  18873. return true;
  18874. }
  18875. void BfModule::ReportMemory(MemReporter* memReporter)
  18876. {
  18877. memReporter->Add(sizeof(BfModule));
  18878. if (mBfIRBuilder != NULL)
  18879. {
  18880. memReporter->BeginSection("IRBuilder_ConstData");
  18881. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  18882. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  18883. memReporter->EndSection();
  18884. memReporter->BeginSection("IRBuilder_BFIR");
  18885. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  18886. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  18887. memReporter->EndSection();
  18888. memReporter->Add(sizeof(BfIRBuilder));
  18889. }
  18890. memReporter->BeginSection("FileInstanceMap");
  18891. memReporter->AddMap(mFileInstanceMap);
  18892. memReporter->AddMap(mNamedFileInstanceMap);
  18893. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  18894. memReporter->EndSection();
  18895. memReporter->AddVec(mOwnedTypeInstances, false);
  18896. memReporter->AddVec(mSpecializedMethodModules, false);
  18897. memReporter->AddVec(mOutFileNames, false);
  18898. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  18899. memReporter->AddMap(mInterfaceSlotRefs, false);
  18900. memReporter->AddMap(mStaticFieldRefs, false);
  18901. memReporter->AddMap(mClassVDataRefs, false);
  18902. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  18903. memReporter->AddMap(mTypeDataRefs, false);
  18904. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  18905. memReporter->AddMap(mDeferredMethodCallData, false);
  18906. memReporter->AddHashSet(mDeferredMethodIds, false);
  18907. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  18908. }
  18909. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  18910. // be transient through the next compile
  18911. void BfModule::ClearModuleData()
  18912. {
  18913. BfLogSysM("ClearModuleData %p\n", this);
  18914. if (mAddedToCount)
  18915. {
  18916. mCompiler->mStats.mModulesFinished++;
  18917. mAddedToCount = false;
  18918. }
  18919. mDICompileUnit = BfIRMDNode();
  18920. mIsModuleMutable = false;
  18921. mIncompleteMethodCount = 0;
  18922. mHasGenericMethods = false;
  18923. // We don't want to clear these because we want it to persist through module extensions-
  18924. // otherwise we may think an extension succeeds even though the base module failed
  18925. //mHadBuildError = false;
  18926. //mHadBuildWarning = false;
  18927. mClassVDataRefs.Clear();
  18928. mClassVDataExtRefs.Clear();
  18929. for (auto& kv : mTypeDataRefs)
  18930. kv.mValue = BfIRValue();
  18931. mStringCharPtrPool.Clear();
  18932. mStringObjectPool.Clear();
  18933. mStaticFieldRefs.Clear();
  18934. BF_ASSERT(!mIgnoreErrors);
  18935. for (auto prevIRBuilder : mPrevIRBuilders)
  18936. delete prevIRBuilder;
  18937. mPrevIRBuilders.Clear();
  18938. for (auto& specPair : mSpecializedMethodModules)
  18939. {
  18940. auto specModule = specPair.mValue;
  18941. specModule->ClearModuleData();
  18942. }
  18943. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18944. mBuiltInFuncs[i] = BfIRFunction();
  18945. if (mNextAltModule != NULL)
  18946. mNextAltModule->ClearModuleData();
  18947. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  18948. delete mBfIRBuilder;
  18949. mBfIRBuilder = NULL;
  18950. mWantsIRIgnoreWrites = false;
  18951. }
  18952. void BfModule::DisownMethods()
  18953. {
  18954. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18955. mBuiltInFuncs[i] = BfIRFunction();
  18956. BfModule* methodModule = this;
  18957. if (mParentModule != NULL)
  18958. methodModule = mParentModule;
  18959. for (auto typeInst : methodModule->mOwnedTypeInstances)
  18960. {
  18961. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  18962. {
  18963. if (methodGroup.mDefault != NULL)
  18964. {
  18965. if (methodGroup.mDefault->mIRFunction)
  18966. {
  18967. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  18968. if (methodGroup.mDefault->mDeclModule == this)
  18969. {
  18970. methodGroup.mDefault->mIRFunction = BfIRFunction();
  18971. }
  18972. }
  18973. }
  18974. if (methodGroup.mMethodSpecializationMap != NULL)
  18975. {
  18976. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  18977. {
  18978. auto methodInstance = mapPair.mValue;
  18979. if (methodInstance->mDeclModule == this)
  18980. {
  18981. methodInstance->mIRFunction = BfIRFunction();
  18982. }
  18983. }
  18984. }
  18985. }
  18986. }
  18987. }
  18988. void BfModule::ClearModule()
  18989. {
  18990. ClearModuleData();
  18991. DisownMethods();
  18992. for (auto& specPair : mSpecializedMethodModules)
  18993. {
  18994. auto specModule = specPair.mValue;
  18995. specModule->ClearModule();
  18996. }
  18997. if (mNextAltModule != NULL)
  18998. mNextAltModule->ClearModule();
  18999. }