BfModule.cpp 696 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663
  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)
  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. if (moduleName.Contains("_Comparison_"))
  676. {
  677. NOP;
  678. }
  679. gLastCreatedModule = this;
  680. mContext = context;
  681. mModuleName = moduleName;
  682. if (!moduleName.empty())
  683. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  684. mAddedToCount = false;
  685. mParentModule = NULL;
  686. mNextAltModule = NULL;
  687. mBfIRBuilder = NULL;
  688. mWantsIRIgnoreWrites = false;
  689. mModuleOptions = NULL;
  690. mLastUsedRevision = -1;
  691. mUsedSlotCount = -1;
  692. mIsReified = true;
  693. mReifyQueued = false;
  694. mIsSpecialModule = false;
  695. mIsScratchModule = false;
  696. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  697. mHadBuildError = false;
  698. mHadBuildWarning = false;
  699. mIgnoreErrors = false;
  700. mIgnoreWarnings = false;
  701. mHadIgnoredError = false;
  702. mReportErrors = true;
  703. mIsInsideAutoComplete = false;
  704. mIsDeleting = false;
  705. mSkipInnerLookup = false;
  706. mIsHotModule = false;
  707. mSetIllegalSrcPosition = false;
  708. mNoResolveGenericParams = false;
  709. mWroteToLib = false;
  710. mContext = context;
  711. mCompiler = context->mCompiler;
  712. mSystem = mCompiler->mSystem;
  713. mProject = NULL;
  714. mCurMethodState = NULL;
  715. mAttributeState = NULL;
  716. mCurLocalMethodId = 0;
  717. mParentNodeEntry = NULL;
  718. mRevision = -1;
  719. mRebuildIdx = 0;
  720. mLastModuleWrittenRevision = 0;
  721. mIsModuleMutable = false;
  722. mExtensionCount = 0;
  723. mIncompleteMethodCount = 0;
  724. mOnDemandMethodCount = 0;
  725. mHasGenericMethods = false;
  726. mCurMethodInstance = NULL;
  727. mCurTypeInstance = NULL;
  728. mAwaitingInitFinish = false;
  729. mAwaitingFinish = false;
  730. mHasFullDebugInfo = false;
  731. mHadHotObjectWrites = false;
  732. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  733. mBuiltInFuncs[i] = BfIRFunction();
  734. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  735. }
  736. void BfReportMemory();
  737. BfModule::~BfModule()
  738. {
  739. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  740. if (!mIsDeleting)
  741. RemoveModuleData();
  742. }
  743. void BfModule::RemoveModuleData()
  744. {
  745. BF_ASSERT(!mIsDeleting);
  746. if (!mModuleName.empty())
  747. {
  748. // Note: module names not necessarily unique
  749. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  750. }
  751. CleanupFileInstances();
  752. delete mBfIRBuilder;
  753. mBfIRBuilder = NULL;
  754. //delete mCpu;
  755. for (auto prevModule : mPrevIRBuilders)
  756. delete prevModule;
  757. mPrevIRBuilders.Clear();
  758. for (auto& pairVal : mDeferredMethodCallData)
  759. delete pairVal.mValue;
  760. mDeferredMethodCallData.Clear();
  761. mDeferredMethodIds.Clear();
  762. for (auto& specModulePair : mSpecializedMethodModules)
  763. delete specModulePair.mValue;
  764. mSpecializedMethodModules.Clear();
  765. if (mNextAltModule != NULL)
  766. delete mNextAltModule;
  767. mNextAltModule = NULL;
  768. if (mModuleOptions != NULL)
  769. delete mModuleOptions;
  770. mModuleOptions = NULL;
  771. BfReportMemory();
  772. }
  773. void BfModule::Init(bool isFullRebuild)
  774. {
  775. mContext->mFinishedModuleWorkList.Remove(this);
  776. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  777. BF_ASSERT(mIsReified);
  778. if (!mIsScratchModule)
  779. {
  780. mCompiler->mStats.mModulesStarted++;
  781. if (mIsReified)
  782. mCompiler->mStats.mReifiedModuleCount++;
  783. mAddedToCount = true;
  784. }
  785. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  786. mFuncReferences.Clear();
  787. mClassVDataRefs.Clear();
  788. mClassVDataExtRefs.Clear();
  789. //mTypeDataRefs.Clear();
  790. mDbgRawAllocDataRefs.Clear();
  791. CleanupFileInstances();
  792. mStaticFieldRefs.Clear();
  793. //mInterfaceSlotRefs.Clear();
  794. // If we are just doing an extension then the ownede types aren't rebuilt.
  795. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  796. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  797. if (isFullRebuild)
  798. mRevision = mCompiler->mRevision;
  799. BF_ASSERT(mCurTypeInstance == NULL);
  800. mIsModuleMutable = true;
  801. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  802. #ifdef _DEBUG
  803. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  804. #else
  805. EnsureIRBuilder(false);
  806. #endif
  807. mCurMethodState = NULL;
  808. mAwaitingInitFinish = true;
  809. mOnDemandMethodCount = 0;
  810. mAwaitingFinish = false;
  811. mHasForceLinkMarker = false;
  812. mUsedSlotCount = -1;
  813. }
  814. bool BfModule::WantsFinishModule()
  815. {
  816. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  817. }
  818. void BfModule::FinishInit()
  819. {
  820. BF_ASSERT(mAwaitingInitFinish);
  821. auto moduleOptions = GetModuleOptions();
  822. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  823. #ifdef BF_PLATFORM_WINDOWS
  824. if (mCompiler->mOptions.mToolsetType == BfToolsetType_GNU)
  825. {
  826. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  827. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-gnu");
  828. else
  829. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-gnu");
  830. }
  831. else //if (mCompiler->mOptions.mToolsetType == BfToolsetType_Microsoft)
  832. {
  833. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  834. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-msvc");
  835. else
  836. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-msvc");
  837. }
  838. #elif defined BF_PLATFORM_LINUX
  839. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  840. mBfIRBuilder->Module_SetTargetTriple("i686-unknown-linux-gnu");
  841. else
  842. mBfIRBuilder->Module_SetTargetTriple("x86_64-unknown-linux-gnu");
  843. #else
  844. // Leave it default
  845. mBfIRBuilder->Module_SetTargetTriple("");
  846. #endif
  847. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  848. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  849. {
  850. // Og+ requires debug info
  851. moduleOptions.mEmitDebugInfo = 1;
  852. }
  853. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  854. // We need to create DIBuilder for mIsSpecialModule so we have it around when we need it
  855. // if ((!mCompiler->mIsResolveOnly) && ((mIsScratchModule) || (moduleOptions.mEmitDebugInfo != 0)))
  856. // {
  857. // BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mIsScratchModule) || (!mIsReified));
  858. // mBfIRBuilder->DbgInit();
  859. // }
  860. // else
  861. // mHasFullDebugInfo = false;
  862. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  863. {
  864. mBfIRBuilder->DbgInit();
  865. }
  866. else
  867. mHasFullDebugInfo = false;
  868. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  869. ((moduleOptions.mEmitDebugInfo != 0)))
  870. {
  871. if (mCompiler->mOptions.IsCodeView())
  872. {
  873. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  874. }
  875. else
  876. {
  877. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  878. }
  879. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  880. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  881. }
  882. mAwaitingInitFinish = false;
  883. }
  884. void BfModule::ReifyModule()
  885. {
  886. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  887. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  888. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  889. mIsReified = true;
  890. mReifyQueued = false;
  891. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  892. mCompiler->mStats.mModulesReified++;
  893. }
  894. void BfModule::UnreifyModule()
  895. {
  896. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  897. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  898. mIsReified = false;
  899. mReifyQueued = false;
  900. StartNewRevision(RebuildKind_None, true);
  901. mCompiler->mStats.mModulesUnreified++;
  902. }
  903. void BfModule::CleanupFileInstances()
  904. {
  905. for (auto& itr : mNamedFileInstanceMap)
  906. {
  907. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  908. delete itr.mValue;
  909. }
  910. mCurFilePosition.mFileInstance = NULL;//
  911. mFileInstanceMap.Clear();
  912. mNamedFileInstanceMap.Clear();
  913. }
  914. void BfModule::Cleanup()
  915. {
  916. CleanupFileInstances();
  917. }
  918. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  919. {
  920. BF_ASSERT(!mIsDeleting);
  921. if (mBfIRBuilder == NULL)
  922. {
  923. if ((!mIsScratchModule) && (!mAddedToCount))
  924. {
  925. mCompiler->mStats.mModulesStarted++;
  926. mAddedToCount = true;
  927. }
  928. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  929. /*if (mCompiler->mIsResolveOnly)
  930. BF_ASSERT(mIsResolveOnly);*/
  931. mBfIRBuilder = new BfIRBuilder(this);
  932. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  933. if (mIsScratchModule)
  934. {
  935. mBfIRBuilder->mIgnoreWrites = true;
  936. BF_ASSERT(!dbgVerifyCodeGen);
  937. }
  938. #ifdef _DEBUG
  939. if (mCompiler->mIsResolveOnly)
  940. {
  941. // For "deep" verification testing
  942. /*if (!mIsSpecialModule)
  943. dbgVerifyCodeGen = true;*/
  944. // We only want to turn this off on smaller builds for testing
  945. mBfIRBuilder->mIgnoreWrites = true;
  946. if (dbgVerifyCodeGen)
  947. mBfIRBuilder->mIgnoreWrites = false;
  948. if (!mBfIRBuilder->mIgnoreWrites)
  949. {
  950. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  951. mBfIRBuilder->mDbgVerifyCodeGen = true;
  952. }
  953. }
  954. else if (!mIsReified)
  955. {
  956. mBfIRBuilder->mIgnoreWrites = true;
  957. }
  958. else
  959. {
  960. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  961. // code as we walk the AST
  962. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  963. if (
  964. (mModuleName == "-")
  965. //|| (mModuleName == "System_Internal")
  966. //|| (mModuleName == "vdata")
  967. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  968. )
  969. mBfIRBuilder->mDbgVerifyCodeGen = true;
  970. // Just for testing!
  971. //mBfIRBuilder->mIgnoreWrites = true;
  972. }
  973. #else
  974. if (mCompiler->mIsResolveOnly)
  975. {
  976. // Always ignore writes in resolveOnly for release builds
  977. mBfIRBuilder->mIgnoreWrites = true;
  978. }
  979. else
  980. {
  981. // Just for memory testing! This breaks everything.
  982. //mBfIRBuilder->mIgnoreWrites = true;
  983. // For "deep" verification testing
  984. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  985. }
  986. #endif
  987. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  988. }
  989. }
  990. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  991. {
  992. String name = "FORCELINKMOD_" + module->mModuleName;
  993. if (outName != NULL)
  994. *outName = name;
  995. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  996. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  997. }
  998. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  999. {
  1000. BP_ZONE("BfModule::StartNewRevision");
  1001. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1002. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1003. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1004. // Already on new revision?
  1005. if ((mRevision == mCompiler->mRevision) && (!force))
  1006. return;
  1007. mHadBuildError = false;
  1008. mHadBuildWarning = false;
  1009. mExtensionCount = 0;
  1010. mRevision = mCompiler->mRevision;
  1011. mRebuildIdx++;
  1012. ClearModuleData();
  1013. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1014. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1015. mStringPoolRefs.Clear();
  1016. mDllImportEntries.Clear();
  1017. mImportFileNames.Clear();
  1018. for (auto& pairVal : mDeferredMethodCallData)
  1019. delete pairVal.mValue;
  1020. mDeferredMethodCallData.Clear();
  1021. mDeferredMethodIds.Clear();
  1022. mModuleRefs.Clear();
  1023. mOutFileNames.Clear();
  1024. mTypeDataRefs.Clear();
  1025. mInterfaceSlotRefs.Clear();
  1026. if (rebuildKind == BfModule::RebuildKind_None)
  1027. {
  1028. for (auto& specPair : mSpecializedMethodModules)
  1029. {
  1030. auto specModule = specPair.mValue;
  1031. if (specModule->mIsReified != mIsReified)
  1032. {
  1033. if (mIsReified)
  1034. specModule->ReifyModule();
  1035. else
  1036. specModule->UnreifyModule();
  1037. }
  1038. }
  1039. }
  1040. else
  1041. {
  1042. for (auto& specPair : mSpecializedMethodModules)
  1043. {
  1044. auto specModule = specPair.mValue;
  1045. delete specModule;
  1046. }
  1047. }
  1048. mSpecializedMethodModules.Clear();
  1049. delete mNextAltModule;
  1050. mNextAltModule = NULL;
  1051. BF_ASSERT(mModuleOptions == NULL);
  1052. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1053. bool needsTypePopulated = false;
  1054. int oldOnDemandCount = 0;
  1055. // We don't have to rebuild types in the unspecialized module because there is no
  1056. // data that's needed -- their method instances are all NULL and the module
  1057. // doesn't get included in the build
  1058. if (this != mContext->mScratchModule)
  1059. {
  1060. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1061. {
  1062. auto typeInst = mOwnedTypeInstances[typeIdx];
  1063. if (!typeInst->IsDeleting())
  1064. {
  1065. typeInst->mIsReified = mIsReified;
  1066. if (rebuildKind != BfModule::RebuildKind_None)
  1067. {
  1068. if (typeInst->IsOnDemand())
  1069. {
  1070. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1071. if (rebuildKind == BfModule::RebuildKind_All)
  1072. mContext->DeleteType(typeInst);
  1073. else
  1074. {
  1075. RebuildMethods(typeInst);
  1076. }
  1077. }
  1078. else
  1079. mContext->RebuildType(typeInst, false, false, false);
  1080. }
  1081. else
  1082. {
  1083. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1084. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1085. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1086. {
  1087. oldOnDemandCount++;
  1088. }
  1089. }
  1090. if (typeInst->IsDeleting())
  1091. typeIdx--;
  1092. }
  1093. }
  1094. }
  1095. if (!mIsDeleting)
  1096. Init();
  1097. mOnDemandMethodCount += oldOnDemandCount;
  1098. }
  1099. void BfModule::StartExtension()
  1100. {
  1101. BF_ASSERT(!mIsModuleMutable);
  1102. BfLogSysM("Extension started of module %p\n", this);
  1103. mExtensionCount++;
  1104. if (mBfIRBuilder != NULL)
  1105. mPrevIRBuilders.push_back(mBfIRBuilder);
  1106. mBfIRBuilder = NULL;
  1107. mWantsIRIgnoreWrites = false;
  1108. mFuncReferences.Clear();
  1109. mClassVDataRefs.Clear();
  1110. mClassVDataExtRefs.Clear();
  1111. for (auto& kv : mTypeDataRefs)
  1112. kv.mValue = BfIRValue();
  1113. mDbgRawAllocDataRefs.Clear();
  1114. mStringCharPtrPool.Clear();
  1115. mStringObjectPool.Clear();
  1116. mStaticFieldRefs.Clear();
  1117. for (auto& kv : mInterfaceSlotRefs)
  1118. kv.mValue = BfIRValue();
  1119. mDeferredMethodCallData.Clear();
  1120. mDeferredMethodIds.Clear();
  1121. DisownMethods();
  1122. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1123. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1124. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1125. Init(false);
  1126. if (!wasAwaitingInitFinish)
  1127. FinishInit();
  1128. mOnDemandMethodCount = prevOnDemandMethodCount;
  1129. }
  1130. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1131. {
  1132. BfIRValue vDataValue;
  1133. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1134. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1135. else
  1136. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1137. typeValueParams.push_back(vDataValue);
  1138. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1139. {
  1140. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1141. typeValueParams.push_back(GetDefaultValue(primType));
  1142. }
  1143. }
  1144. BfIRValue BfModule::GetConstValue(int64 val)
  1145. {
  1146. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1147. }
  1148. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1149. {
  1150. BfType* checkType = type;
  1151. if (type->IsTypedPrimitive())
  1152. {
  1153. checkType = type->GetUnderlyingType();
  1154. }
  1155. if (checkType->IsPrimitiveType())
  1156. {
  1157. auto primType = (BfPrimitiveType*)checkType;
  1158. if (checkType->IsFloat())
  1159. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1160. else
  1161. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1162. }
  1163. return BfIRValue();
  1164. }
  1165. BfIRValue BfModule::GetConstValue8(int val)
  1166. {
  1167. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1168. }
  1169. BfIRValue BfModule::GetConstValue32(int32 val)
  1170. {
  1171. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1172. }
  1173. BfIRValue BfModule::GetConstValue64(int64 val)
  1174. {
  1175. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1176. }
  1177. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1178. {
  1179. PopulateType(type, BfPopulateType_Data);
  1180. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1181. if (type->IsTypedPrimitive())
  1182. {
  1183. auto underlyingType = type->GetUnderlyingType();
  1184. if (underlyingType == NULL)
  1185. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1186. return GetDefaultValue(type->GetUnderlyingType());
  1187. }
  1188. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1189. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1190. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1191. if ((type->IsIntegral()) || (type->IsBoolean()))
  1192. {
  1193. auto primType = (BfPrimitiveType*)type;
  1194. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1195. }
  1196. if (type->IsFloat())
  1197. {
  1198. auto primType = (BfPrimitiveType*)type;
  1199. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1200. }
  1201. if (type->IsVoid())
  1202. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1203. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1204. }
  1205. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1206. {
  1207. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1208. if (type->mSize == 0)
  1209. return BfTypedValue(BfIRValue(), type);
  1210. else
  1211. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1212. }
  1213. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1214. {
  1215. PopulateType(type, BfPopulateType_Data);
  1216. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1217. if (defaultValueKind == BfDefaultValueKind_Undef)
  1218. {
  1219. auto primType = type->ToPrimitiveType();
  1220. if (primType != NULL)
  1221. {
  1222. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1223. }
  1224. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1225. }
  1226. BfTypedValue typedValue;
  1227. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1228. {
  1229. if (type->IsRef())
  1230. {
  1231. BfRefType* refType = (BfRefType*)type;
  1232. BfType* underlyingType = refType->GetUnderlyingType();
  1233. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1234. }
  1235. else
  1236. {
  1237. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1238. }
  1239. if (!mBfIRBuilder->mIgnoreWrites)
  1240. {
  1241. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1242. GetConstValue(type->mSize), type->mAlign);
  1243. }
  1244. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1245. typedValue = LoadValue(typedValue);
  1246. return typedValue;
  1247. }
  1248. if ((type->IsRef()) && (!allowRef))
  1249. {
  1250. BfRefType* refType = (BfRefType*)type;
  1251. BfType* underlyingType = refType->GetUnderlyingType();
  1252. if (underlyingType->IsValuelessType())
  1253. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1254. else
  1255. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1256. }
  1257. else
  1258. {
  1259. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1260. }
  1261. return typedValue;
  1262. }
  1263. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1264. {
  1265. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1266. BfIRType strCharType;
  1267. //
  1268. {
  1269. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1270. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1271. }
  1272. BfIRValue strConstant;
  1273. if (define)
  1274. {
  1275. strConstant = mBfIRBuilder->CreateConstString(str);
  1276. }
  1277. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1278. true, BfIRLinkageType_External,
  1279. strConstant, stringDataName);
  1280. if (define)
  1281. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1282. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1283. }
  1284. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1285. {
  1286. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1287. mBfIRBuilder->PopulateType(stringTypeInst);
  1288. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1289. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1290. BfIRValue stringValData;
  1291. if (define)
  1292. {
  1293. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1294. mStringCharPtrPool[stringId] = stringCharsVal;
  1295. SizedArray<BfIRValue, 8> typeValueParams;
  1296. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1297. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1298. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1299. typeValueParams.clear();
  1300. typeValueParams.push_back(objData);
  1301. if (lenByteCount == 4)
  1302. {
  1303. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1304. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1305. }
  1306. else
  1307. {
  1308. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1309. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1310. }
  1311. typeValueParams.push_back(stringCharsVal); // mPtr
  1312. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1313. }
  1314. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1315. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1316. true,
  1317. BfIRLinkageType_External,
  1318. define ? stringValData : BfIRValue(),
  1319. stringObjName);
  1320. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1321. return stringVal;
  1322. }
  1323. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1324. {
  1325. BF_ASSERT(constantStr.IsConst());
  1326. if (constHolder == NULL)
  1327. constHolder = mBfIRBuilder;
  1328. auto constant = constHolder->GetConstant(constantStr);
  1329. if (constant->mTypeCode == BfTypeCode_Int32)
  1330. {
  1331. return constant->mInt32;
  1332. }
  1333. while (constant->mConstType == BfConstType_BitCast)
  1334. {
  1335. auto constBitCast = (BfConstantBitCast*)constant;
  1336. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1337. }
  1338. if (constant->mConstType == BfConstType_GEP32_2)
  1339. {
  1340. auto constGEP = (BfConstantGEP32_2*)constant;
  1341. constant = constHolder->GetConstantById(constGEP->mTarget);
  1342. }
  1343. if (constant->mConstType == BfConstType_GlobalVar)
  1344. {
  1345. auto constGV = (BfGlobalVar*)constant;
  1346. const char* strDataPrefix = "__bfStrData";
  1347. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1348. return atoi(constGV->mName + strlen(strDataPrefix));
  1349. const char* strObjPrefix = "__bfStrObj";
  1350. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1351. return atoi(constGV->mName + strlen(strObjPrefix));
  1352. }
  1353. return -1;
  1354. }
  1355. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1356. {
  1357. BfIRValue* irValue = NULL;
  1358. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1359. return *irValue;
  1360. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1361. if (!mStringObjectPool.ContainsKey(stringId))
  1362. mStringPoolRefs.Add(stringId);
  1363. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1364. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1365. *irValue = strCharPtrConst;
  1366. return strCharPtrConst;
  1367. }
  1368. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1369. {
  1370. if (strValue.IsConst())
  1371. {
  1372. int stringId = GetStringPoolIdx(strValue);
  1373. BF_ASSERT(stringId != -1);
  1374. return GetStringCharPtr(stringId);
  1375. }
  1376. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1377. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1378. return charPtr;
  1379. }
  1380. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1381. {
  1382. return GetStringCharPtr(GetStringObjectValue(str));
  1383. }
  1384. BfIRValue BfModule::GetStringObjectValue(int strId)
  1385. {
  1386. BfIRValue* objValue;
  1387. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1388. return *objValue;
  1389. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1390. return GetStringObjectValue(stringPoolEntry.mString, true);
  1391. }
  1392. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1393. {
  1394. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1395. mBfIRBuilder->PopulateType(stringType);
  1396. int strId = mContext->GetStringLiteralId(str);
  1397. BfIRValue* irValuePtr = NULL;
  1398. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1399. return *irValuePtr;
  1400. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1401. if (!mStringCharPtrPool.ContainsKey(strId))
  1402. mStringPoolRefs.Add(strId);
  1403. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1404. *irValuePtr = strObject;
  1405. mStringPoolRefs.Add(strId);
  1406. return strObject;
  1407. }
  1408. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1409. {
  1410. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1411. type,
  1412. true,
  1413. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1414. constant,
  1415. name.c_str());
  1416. return newConst;
  1417. }
  1418. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1419. {
  1420. auto curScope = mCurMethodState->mCurScope;
  1421. if (curScope->mLabelNode != NULL)
  1422. curScope->mLabelNode->ToString(curScope->mLabel);
  1423. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1424. {
  1425. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1426. while (checkScope != NULL)
  1427. {
  1428. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1429. {
  1430. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1431. if (errorNode != NULL)
  1432. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1433. break;
  1434. }
  1435. checkScope = checkScope->mPrevScope;
  1436. }
  1437. }
  1438. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1439. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1440. {
  1441. if (prevScope->mHadScopeValueRetain)
  1442. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1443. else
  1444. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1445. }
  1446. mCurMethodState->mBlockNestLevel++;
  1447. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1448. {
  1449. // DIScope could be NULL if we're in an unspecialized method (for example)
  1450. if (mCurMethodState->mCurScope->mDIScope)
  1451. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1452. }
  1453. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1454. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1455. }
  1456. void BfModule::RestoreScoreState_LocalVariables()
  1457. {
  1458. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1459. {
  1460. auto localVar = mCurMethodState->mLocals.back();
  1461. LocalVariableDone(localVar, false);
  1462. mCurMethodState->mLocals.pop_back();
  1463. if (localVar->mShadowedLocal != NULL)
  1464. {
  1465. BfLocalVarEntry* localVarEntryPtr;
  1466. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1467. {
  1468. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1469. }
  1470. }
  1471. else
  1472. {
  1473. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1474. }
  1475. delete localVar;
  1476. }
  1477. }
  1478. void BfModule::RestoreScopeState()
  1479. {
  1480. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1481. mCurMethodState->mBlockNestLevel--;
  1482. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1483. {
  1484. BfIRBlock afterEndBlock;
  1485. if (!mCurMethodState->mLeftBlockUncond)
  1486. {
  1487. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1488. mBfIRBuilder->CreateBr(afterEndBlock);
  1489. mBfIRBuilder->ClearDebugLocation_Last();
  1490. }
  1491. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1492. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1493. if (afterEndBlock)
  1494. {
  1495. mBfIRBuilder->AddBlock(afterEndBlock);
  1496. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1497. }
  1498. }
  1499. if (!mCurMethodState->mLeftBlockUncond)
  1500. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1501. RestoreScoreState_LocalVariables();
  1502. if (mCurMethodState->mCurScope->mValueScopeStart)
  1503. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1504. mCurMethodState->mCurScope = prevScopeData;
  1505. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1506. }
  1507. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1508. {
  1509. if (mBfIRBuilder->mIgnoreWrites)
  1510. return mBfIRBuilder->GetFakeVal();
  1511. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1512. mBfIRBuilder->PopulateType(type);
  1513. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1514. if (!mBfIRBuilder->mIgnoreWrites)
  1515. BF_ASSERT(!prevInsertBlock.IsFake());
  1516. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1517. BfIRValue allocaInst;
  1518. if (arraySize)
  1519. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1520. else
  1521. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1522. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1523. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1524. if (name != NULL)
  1525. mBfIRBuilder->SetName(allocaInst, name);
  1526. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1527. if (addLifetime)
  1528. {
  1529. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1530. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1531. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1532. }
  1533. return allocaInst;
  1534. }
  1535. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1536. {
  1537. if (mBfIRBuilder->mIgnoreWrites)
  1538. return mBfIRBuilder->GetFakeVal();
  1539. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1540. mBfIRBuilder->PopulateType(typeInst);
  1541. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1542. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1543. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1544. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1545. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1546. if (name != NULL)
  1547. mBfIRBuilder->SetName(allocaInst, name);
  1548. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1549. if (addLifetime)
  1550. {
  1551. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1552. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1553. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1554. }
  1555. return allocaInst;
  1556. }
  1557. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1558. {
  1559. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1560. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1561. /*if (mCurMethodState->mInHeadScope)
  1562. isScopeAlloc = true;*/
  1563. if (scopeData == NULL)
  1564. return;
  1565. auto checkBaseType = val.mType->ToTypeInstance();
  1566. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1567. {
  1568. bool hadDtorCall = false;
  1569. while (checkBaseType != NULL)
  1570. {
  1571. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1572. {
  1573. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1574. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1575. BfIRValue useVal = val.mValue;
  1576. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1577. if (isDynAlloc)
  1578. {
  1579. //
  1580. }
  1581. else if (condAlloca)
  1582. {
  1583. BF_ASSERT(!IsTargetingBeefBackend());
  1584. BF_ASSERT(!isDynAlloc);
  1585. auto valPtr = CreateAlloca(checkBaseType);
  1586. mBfIRBuilder->CreateStore(useVal, valPtr);
  1587. useVal = valPtr;
  1588. }
  1589. SizedArray<BfIRValue, 1> llvmArgs;
  1590. llvmArgs.push_back(useVal);
  1591. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1592. if (deferredCall != NULL)
  1593. {
  1594. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1595. if (condAlloca)
  1596. deferredCall->mArgsNeedLoad = true;
  1597. }
  1598. hadDtorCall = true;
  1599. break;
  1600. }
  1601. checkBaseType = checkBaseType->mBaseType;
  1602. }
  1603. return;
  1604. }
  1605. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1606. if (mayEscape)
  1607. {
  1608. // Is this worth it?
  1609. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1610. // {
  1611. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1612. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1613. // if (!isDyn)
  1614. // {
  1615. // int clearSize = val.mType->mSize;
  1616. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1617. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1618. // SizedArray<BfIRValue, 1> llvmArgs;
  1619. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1620. // llvmArgs.push_back(GetConstValue8(0xDD));
  1621. // llvmArgs.push_back(GetConstValue(clearSize));
  1622. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1623. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1624. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1625. // }
  1626. // else
  1627. // {
  1628. // const char* funcName = "SetDeleted1";
  1629. // if (val.mType->mSize >= 16)
  1630. // funcName = "SetDeleted16";
  1631. // else if (val.mType->mSize >= 8)
  1632. // funcName = "SetDeleted8";
  1633. // else if (val.mType->mSize >= 4)
  1634. // funcName = "SetDeleted4";
  1635. //
  1636. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1637. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1638. // SizedArray<BfIRValue, 1> llvmArgs;
  1639. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1640. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1641. // }
  1642. // }
  1643. }
  1644. }
  1645. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1646. {
  1647. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1648. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1649. return false;
  1650. auto checkTypeInstance = startTypeInstance;
  1651. while (checkTypeInstance != NULL)
  1652. {
  1653. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1654. {
  1655. if (fieldInstance.mMergedDataIdx != -1)
  1656. {
  1657. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1658. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1659. {
  1660. // For fields added in extensions, we automatically initialize those if necessary
  1661. auto fieldDef = fieldInstance.GetFieldDef();
  1662. if (!fieldDef->mDeclaringType->IsExtension())
  1663. return false;
  1664. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1665. {
  1666. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1667. mBfIRBuilder->SaveDebugLocation();
  1668. if (localVar->IsParam())
  1669. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1670. else
  1671. {
  1672. BF_ASSERT(localVar->mDeclBlock);
  1673. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1674. }
  1675. mBfIRBuilder->ClearDebugLocation();
  1676. BfIRValue curVal;
  1677. if (localVar->mIsThis)
  1678. curVal = mBfIRBuilder->GetArgument(0);
  1679. else
  1680. curVal = localVar->mAddr;
  1681. auto subTypeInstance = startTypeInstance;
  1682. while (subTypeInstance != checkTypeInstance)
  1683. {
  1684. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1685. subTypeInstance = subTypeInstance->mBaseType;
  1686. }
  1687. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1688. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1689. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1690. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1691. mBfIRBuilder->RestoreDebugLocation();
  1692. }
  1693. localVar->mUnassignedFieldFlags &= ~checkMask;
  1694. if (localVar->mUnassignedFieldFlags == 0)
  1695. localVar->mIsAssigned = true;
  1696. }
  1697. }
  1698. }
  1699. checkTypeInstance = checkTypeInstance->mBaseType;
  1700. }
  1701. return localVar->mIsAssigned;
  1702. }
  1703. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1704. {
  1705. //if (localVar->mAddr == NULL)
  1706. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1707. {
  1708. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1709. {
  1710. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1711. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1712. }
  1713. }*/
  1714. BfAstNode* localNameNode = localVar->mNameNode;
  1715. if (localVar->mIsThis)
  1716. {
  1717. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1718. }
  1719. if (localNameNode != NULL)
  1720. {
  1721. bool isOut = false;
  1722. if (localVar->mResolvedType->IsRef())
  1723. {
  1724. auto refType = (BfRefType*)localVar->mResolvedType;
  1725. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1726. }
  1727. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1728. {
  1729. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1730. TryLocalVariableInit(localVar);
  1731. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1732. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1733. //bool deferFullAnalysis = true;
  1734. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1735. if (!localVar->mIsAssigned)
  1736. {
  1737. if (deferUsageWarning)
  1738. {
  1739. // Ignore
  1740. }
  1741. else if (localVar->mIsThis)
  1742. {
  1743. bool foundFields = false;
  1744. auto checkTypeInstance = mCurTypeInstance;
  1745. while (checkTypeInstance != NULL)
  1746. {
  1747. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1748. {
  1749. if (fieldInstance.mMergedDataIdx != -1)
  1750. {
  1751. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1752. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1753. {
  1754. auto fieldDef = fieldInstance.GetFieldDef();
  1755. if (fieldDef->mProtection != BfProtection_Hidden)
  1756. {
  1757. if (checkTypeInstance == mCurTypeInstance)
  1758. {
  1759. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1760. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1761. }
  1762. else
  1763. {
  1764. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1765. TypeToString(checkTypeInstance).c_str(),
  1766. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1767. }
  1768. }
  1769. foundFields = true;
  1770. }
  1771. }
  1772. }
  1773. checkTypeInstance = checkTypeInstance->mBaseType;
  1774. }
  1775. if (!foundFields)
  1776. {
  1777. if (mCurTypeInstance->mInstSize > 0)
  1778. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1779. }
  1780. }
  1781. else if (localVar->IsParam())
  1782. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1783. else if (!deferUsageWarning)
  1784. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1785. }
  1786. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1787. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1788. }
  1789. }
  1790. }
  1791. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1792. {
  1793. auto checkScope = mCurMethodState->mCurScope;
  1794. while (true)
  1795. {
  1796. if (checkScope == scopeData)
  1797. break;
  1798. checkScope->mHadOuterDynStack = true;
  1799. checkScope = checkScope->mPrevScope;
  1800. }
  1801. }
  1802. void BfModule::SaveStackState(BfScopeData* scopeData)
  1803. {
  1804. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1805. // scopes within scopeData restore the stack
  1806. auto checkScope = mCurMethodState->mCurScope;
  1807. while (true)
  1808. {
  1809. if (checkScope == scopeData)
  1810. {
  1811. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1812. {
  1813. if (mBfIRBuilder->mHasDebugInfo)
  1814. mBfIRBuilder->SaveDebugLocation();
  1815. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1816. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1817. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1818. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1819. mBfIRBuilder->SetInsertPoint(prevPos);
  1820. if (mBfIRBuilder->mHasDebugInfo)
  1821. mBfIRBuilder->RestoreDebugLocation();
  1822. }
  1823. break;
  1824. }
  1825. if (checkScope->mSavedStack)
  1826. {
  1827. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1828. checkScope->mSavedStack = BfIRValue();
  1829. }
  1830. checkScope = checkScope->mPrevScope;
  1831. }
  1832. }
  1833. BfIRValue BfModule::ValueScopeStart()
  1834. {
  1835. if (IsTargetingBeefBackend())
  1836. return mBfIRBuilder->CreateValueScopeStart();
  1837. return BfIRValue();
  1838. }
  1839. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1840. {
  1841. if (valueScopeStart)
  1842. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1843. }
  1844. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1845. {
  1846. auto bfParser = astNode->GetSourceData()->ToParserData();
  1847. if (bfParser == NULL)
  1848. return NULL;
  1849. BfFileInstance** fileInstancePtr = NULL;
  1850. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1851. {
  1852. return *fileInstancePtr;
  1853. }
  1854. else
  1855. {
  1856. // It's possible two parsers have the same file name (ie: mNextRevision)
  1857. BfFileInstance** namedFileInstancePtr = NULL;
  1858. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1859. {
  1860. auto bfFileInstance = *namedFileInstancePtr;
  1861. *fileInstancePtr = bfFileInstance;
  1862. return bfFileInstance;
  1863. }
  1864. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1865. auto bfFileInstance = new BfFileInstance();
  1866. *fileInstancePtr = bfFileInstance;
  1867. *namedFileInstancePtr = bfFileInstance;
  1868. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1869. bfFileInstance->mParser = bfParser;
  1870. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1871. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1872. {
  1873. String fileName = bfParser->mFileName;
  1874. for (int i = 0; i < (int)fileName.length(); i++)
  1875. {
  1876. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1877. fileName[i] = DIR_SEP_CHAR;
  1878. }
  1879. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1880. }
  1881. return bfFileInstance;
  1882. }
  1883. }
  1884. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1885. {
  1886. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1887. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1888. return;
  1889. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1890. if (astNode == NULL)
  1891. return;
  1892. auto bfParser = astNode->GetSourceData()->ToParserData();
  1893. if (bfParser == NULL)
  1894. return;
  1895. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1896. {
  1897. if (mCurFilePosition.mFileInstance != NULL)
  1898. {
  1899. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1900. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1901. }
  1902. auto bfFileInstance = GetFileFromNode(astNode);
  1903. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1904. {
  1905. mCurFilePosition = bfFileInstance->mPrevPosition;
  1906. }
  1907. else
  1908. {
  1909. mCurFilePosition.mFileInstance = bfFileInstance;
  1910. mCurFilePosition.mCurLine = 0;
  1911. mCurFilePosition.mCurSrcPos = 0;
  1912. }
  1913. }
  1914. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1915. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1916. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1917. if (jumpEntry->mCharIdx > srcPos)
  1918. jumpEntry--;
  1919. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1920. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1921. mCurFilePosition.mCurColumn = 0;
  1922. while (mCurFilePosition.mCurSrcPos < srcPos)
  1923. {
  1924. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1925. {
  1926. mCurFilePosition.mCurLine++;
  1927. mCurFilePosition.mCurColumn = 0;
  1928. }
  1929. else
  1930. {
  1931. mCurFilePosition.mCurColumn++;
  1932. }
  1933. mCurFilePosition.mCurSrcPos++;
  1934. }
  1935. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1936. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1937. {
  1938. int column = mCurFilePosition.mCurColumn + 1;
  1939. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1940. {
  1941. // Set to illegal position
  1942. column = 0;
  1943. }
  1944. if (mSetIllegalSrcPosition)
  1945. column = 0;
  1946. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1947. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1948. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1949. {
  1950. // This is from a different scope...
  1951. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1952. {
  1953. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1954. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1955. }
  1956. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1957. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1958. }
  1959. else
  1960. {
  1961. if (mCurMethodState->mCurScope->mAltDIFile)
  1962. {
  1963. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1964. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1965. }
  1966. }
  1967. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1968. if (mCurMethodState->mCrossingMixin)
  1969. inlineAt = BfIRMDNode();
  1970. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1971. if ((flags & BfSrcPosFlag_Expression) == 0)
  1972. mBfIRBuilder->CreateStatementStart();
  1973. }
  1974. }
  1975. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  1976. {
  1977. // We've turned off expr src pos (for now?)
  1978. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1979. }
  1980. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  1981. {
  1982. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  1983. }
  1984. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  1985. {
  1986. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1987. {
  1988. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  1989. {
  1990. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  1991. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1992. }
  1993. else
  1994. {
  1995. // Set to whatever it previously was but at column zero, which we will know to be illegal
  1996. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1997. }
  1998. if ((flags & BfSrcPosFlag_Expression) == 0)
  1999. mBfIRBuilder->CreateStatementStart();
  2000. }
  2001. }
  2002. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2003. {
  2004. // We've turned off expr src pos (for now?)
  2005. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2006. }
  2007. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2008. {
  2009. if ((protection == BfProtection_Public) ||
  2010. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2011. ((protection == BfProtection_Private) && (allowPrivate)))
  2012. return true;
  2013. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2014. return true;
  2015. return false;
  2016. }
  2017. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2018. {
  2019. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2020. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2021. {
  2022. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2023. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2024. }
  2025. allowProtected = allowPrivate;
  2026. }
  2027. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2028. {
  2029. if (memberProtection == BfProtection_Hidden)
  2030. return false;
  2031. if (memberProtection == BfProtection_Public)
  2032. return true;
  2033. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2034. {
  2035. BfTypeInstance* curCheckType = mCurTypeInstance;
  2036. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2037. {
  2038. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2039. curCheckType = mixinOwner;
  2040. }
  2041. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2042. if (allowPrivate)
  2043. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2044. else
  2045. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2046. }
  2047. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2048. return true;
  2049. if (memberProtection == BfProtection_Protected)
  2050. {
  2051. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2052. {
  2053. bool allowProtected = false;
  2054. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2055. auto curCheckType = mCurTypeInstance;
  2056. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2057. {
  2058. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2059. curCheckType = mixinOwner;
  2060. }
  2061. auto lookupCheckType = lookupStartType;
  2062. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2063. {
  2064. if (lookupCheckType == curCheckType)
  2065. {
  2066. allowProtected = true;
  2067. break;
  2068. }
  2069. if (lookupCheckType == memberOwner)
  2070. break;
  2071. lookupCheckType = lookupCheckType->mBaseType;
  2072. if (lookupCheckType == NULL)
  2073. break;
  2074. }
  2075. if (!allowProtected)
  2076. {
  2077. // It's possible our outer type is derived from 'memberOwner'
  2078. while (curCheckType->mTypeDef->mNestDepth > 0)
  2079. {
  2080. curCheckType = GetOuterType(curCheckType);
  2081. if (curCheckType == NULL)
  2082. break;
  2083. auto lookupCheckType = lookupStartType;
  2084. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2085. {
  2086. if (lookupCheckType == curCheckType)
  2087. {
  2088. allowProtected = true;
  2089. break;
  2090. }
  2091. if (lookupCheckType == memberOwner)
  2092. break;
  2093. lookupCheckType = lookupCheckType->mBaseType;
  2094. if (lookupCheckType == NULL)
  2095. break;
  2096. }
  2097. }
  2098. }
  2099. if (allowProtected)
  2100. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2101. else
  2102. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2103. }
  2104. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2105. return true;
  2106. }
  2107. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2108. return true;
  2109. return false;
  2110. }
  2111. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2112. {
  2113. if ((mCompiler->mResolvePassData != NULL) &&
  2114. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2115. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2116. {
  2117. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2118. }
  2119. }
  2120. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2121. {
  2122. BP_ZONE("BfModule::Fail");
  2123. if (mIgnoreErrors)
  2124. {
  2125. mHadIgnoredError = true;
  2126. return NULL;
  2127. }
  2128. if (!mReportErrors)
  2129. {
  2130. mCompiler->mPassInstance->SilentFail();
  2131. return NULL;
  2132. }
  2133. if (refNode != NULL)
  2134. refNode = BfNodeToNonTemporary(refNode);
  2135. //BF_ASSERT(refNode != NULL);
  2136. if (mCurMethodInstance != NULL)
  2137. mCurMethodInstance->mHasFailed = true;
  2138. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2139. return NULL;
  2140. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2141. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2142. if (!mHadBuildError)
  2143. mHadBuildError = true;
  2144. if (mParentModule != NULL)
  2145. mParentModule->mHadBuildError = true;
  2146. if (mCurTypeInstance != NULL)
  2147. AddFailType(mCurTypeInstance);
  2148. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2149. String errorString = error;
  2150. bool isWhileSpecializing = false;
  2151. bool isWhileSpecializingMethod = false;
  2152. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2153. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2154. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2155. errorString += StrFormat("\n while generating append size calculating method");
  2156. else if (refNode == NULL)
  2157. {
  2158. if (mCurTypeInstance != NULL)
  2159. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2160. else if (mProject != NULL)
  2161. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2162. }
  2163. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2164. {
  2165. auto checkMethodState = mCurMethodState;
  2166. while (checkMethodState != NULL)
  2167. {
  2168. auto methodInstance = checkMethodState->mMethodInstance;
  2169. if (methodInstance == NULL)
  2170. {
  2171. checkMethodState = checkMethodState->mPrevMethodState;
  2172. continue;
  2173. }
  2174. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2175. methodInstance->mHasFailed = true;
  2176. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2177. if (isSpecializedMethod)
  2178. {
  2179. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2180. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2181. if (unspecializedMethod->mHasFailed)
  2182. return NULL; // At least SOME error has already been reported
  2183. }
  2184. if (isSpecializedMethod)
  2185. {
  2186. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2187. isWhileSpecializing = true;
  2188. isWhileSpecializingMethod = true;
  2189. }
  2190. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2191. {
  2192. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2193. isWhileSpecializing = true;
  2194. isWhileSpecializingMethod = true;
  2195. }
  2196. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2197. {
  2198. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2199. isWhileSpecializing = true;
  2200. }
  2201. checkMethodState = checkMethodState->mPrevMethodState;
  2202. }
  2203. // Keep in mind that all method specializations with generic type instances as its method generic params
  2204. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2205. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2206. // those method specializations if that occurs
  2207. if (isWhileSpecializing)
  2208. {
  2209. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2210. if (bfError != NULL)
  2211. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2212. return bfError;
  2213. }
  2214. }
  2215. if (!mHadBuildError)
  2216. mHadBuildError = true;
  2217. // Check mixins
  2218. {
  2219. auto checkMethodInstance = mCurMethodState;
  2220. while (checkMethodInstance != NULL)
  2221. {
  2222. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2223. if (rootMixinState != NULL)
  2224. {
  2225. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2226. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2227. auto mixinState = checkMethodInstance->mMixinState;
  2228. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2229. {
  2230. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2231. mixinState = mixinState->mPrevMixinState;
  2232. }
  2233. return bfError;
  2234. }
  2235. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2236. }
  2237. }
  2238. BfError* bfError = NULL;
  2239. if (refNode == NULL)
  2240. bfError = mCompiler->mPassInstance->Fail(errorString);
  2241. else
  2242. {
  2243. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2244. }
  2245. if (bfError != NULL)
  2246. {
  2247. bfError->mIsPersistent = isPersistent;
  2248. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2249. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2250. mCompiler->mPassInstance->MoreInfo("Error during deferred code emission", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2251. }
  2252. return bfError;
  2253. }
  2254. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2255. {
  2256. if (mIgnoreErrors)
  2257. return NULL;
  2258. if (refNode != NULL)
  2259. refNode = BfNodeToNonTemporary(refNode);
  2260. mHadBuildError = true;
  2261. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2262. }
  2263. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2264. {
  2265. if (mIgnoreErrors || mIgnoreWarnings)
  2266. return NULL;
  2267. if (!mReportErrors)
  2268. {
  2269. mCompiler->mPassInstance->SilentFail();
  2270. return NULL;
  2271. }
  2272. BfAstNode* unwarnNode = refNode;
  2273. //
  2274. {
  2275. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2276. while (parentNodeEntry != NULL)
  2277. {
  2278. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2279. break;
  2280. unwarnNode = parentNodeEntry->mNode;
  2281. parentNodeEntry = parentNodeEntry->mPrev;
  2282. }
  2283. }
  2284. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2285. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2286. {
  2287. return NULL;
  2288. }
  2289. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2290. if (mCurMethodInstance != NULL)
  2291. {
  2292. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2293. return NULL;
  2294. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2295. return NULL; // No ctorCalcAppend warnings
  2296. }
  2297. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2298. return NULL;
  2299. if (refNode != NULL)
  2300. refNode = BfNodeToNonTemporary(refNode);
  2301. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2302. {
  2303. // We used to bubble up warnings into the mixin injection site, BUT
  2304. // we are now assuming any relevant warnings will be given at the declaration site
  2305. return NULL;
  2306. // AddFailType(mCurTypeInstance);
  2307. //
  2308. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2309. // if (bfError == NULL)
  2310. // return NULL;
  2311. // mHadBuildWarning = true;
  2312. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2313. }
  2314. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2315. if (bfError != NULL)
  2316. {
  2317. AddFailType(mCurTypeInstance);
  2318. mHadBuildWarning = true;
  2319. bfError->mIsPersistent = isPersistent;
  2320. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2321. {
  2322. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2323. if (parser != NULL)
  2324. {
  2325. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2326. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2327. }
  2328. }
  2329. }
  2330. return bfError;
  2331. }
  2332. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2333. {
  2334. if (mBfIRBuilder->mOpFailed)
  2335. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2336. }
  2337. void BfModule::NotImpl(BfAstNode* astNode)
  2338. {
  2339. Fail("INTERNAL ERROR: Not implemented", astNode);
  2340. }
  2341. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2342. {
  2343. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2344. if (!allowPrivate)
  2345. allowPrivate |= memberType->IsInterface();
  2346. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2347. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2348. {
  2349. return false;
  2350. }
  2351. return true;
  2352. }
  2353. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2354. {
  2355. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2356. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2357. auto memberTypeInstance = memberType->ToTypeInstance();
  2358. if (memberTypeInstance == NULL)
  2359. {
  2360. auto underlyingType = memberType->GetUnderlyingType();
  2361. if (underlyingType != NULL)
  2362. return CheckDefineMemberProtection(protection, underlyingType);
  2363. return true;
  2364. }
  2365. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2366. return false;
  2367. if (memberTypeInstance->IsGenericTypeInstance())
  2368. {
  2369. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2370. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2371. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2372. {
  2373. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2374. return false;
  2375. }
  2376. }
  2377. return true;
  2378. }
  2379. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2380. {
  2381. if (usedType == usingType)
  2382. return;
  2383. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2384. return;
  2385. if (usedType->IsSpecializedByAutoCompleteMethod())
  2386. return;
  2387. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2388. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2389. {
  2390. bool addType = true;
  2391. auto checkType = usedType;
  2392. while (true)
  2393. {
  2394. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2395. checkType = checkType->GetUnderlyingType();
  2396. else if (checkType->IsArray())
  2397. {
  2398. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2399. }
  2400. else
  2401. break;
  2402. }
  2403. PopulateType(checkType, BfPopulateType_Data);
  2404. if (checkType->IsValuelessType())
  2405. addType = false;
  2406. else if (checkType->IsPrimitiveType())
  2407. addType = false;
  2408. else
  2409. {
  2410. auto checkTypeInst = checkType->ToTypeInstance();
  2411. if (checkTypeInst == NULL)
  2412. {
  2413. addType = false;
  2414. }
  2415. else
  2416. {
  2417. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2418. addType = false;
  2419. }
  2420. }
  2421. if (addType)
  2422. {
  2423. auto checkTypeInst = checkType->ToTypeInstance();
  2424. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2425. BF_ASSERT(hotTypeVersion != NULL);
  2426. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2427. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2428. (checkType->IsComposite()))
  2429. isAllocation = true;
  2430. if (isAllocation)
  2431. {
  2432. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2433. }
  2434. else
  2435. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2436. }
  2437. }
  2438. //BP_ZONE("BfModule::AddDependency");
  2439. /*if (usedType->IsMethodRef())
  2440. {
  2441. auto methodRefType = (BfMethodRefType*)usedType;
  2442. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2443. return;
  2444. }*/
  2445. // Why in the world were we doing this?
  2446. // This caused functions to get immediately deleted since they appear to have no references ever....
  2447. // if (usedType->IsFunction())
  2448. // {
  2449. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2450. // }
  2451. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2452. {
  2453. auto usingModule = usingType->GetModule();
  2454. BfModule* usedModule;
  2455. if (usedType->IsFunction())
  2456. {
  2457. auto typeInst = usedType->ToTypeInstance();
  2458. if (typeInst->mBaseType == NULL)
  2459. PopulateType(typeInst);
  2460. usedModule = typeInst->mBaseType->GetModule();
  2461. }
  2462. else
  2463. usedModule = usedType->GetModule();
  2464. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2465. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2466. {
  2467. usingModule->mModuleRefs.Add(usedModule);
  2468. }
  2469. }
  2470. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2471. {
  2472. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2473. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2474. if (genericArg == usedType)
  2475. return;
  2476. }
  2477. auto underlyingType = usedType->GetUnderlyingType();
  2478. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2479. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2480. BfDependedType* checkDType = usedType->ToDependedType();
  2481. if (checkDType == NULL)
  2482. return;
  2483. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2484. mContext->MarkAsReferenced(checkDType);
  2485. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2486. if (checkDType->IsGenericTypeInstance())
  2487. {
  2488. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2489. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2490. {
  2491. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2492. }
  2493. }
  2494. }
  2495. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2496. {
  2497. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2498. {
  2499. if (methodInstance->mHotMethod == NULL)
  2500. CheckHotMethod(methodInstance, "");
  2501. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2502. if (devirtualized)
  2503. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2504. else
  2505. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2506. }
  2507. }
  2508. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2509. {
  2510. auto checkTypeInst = typeInst;
  2511. while (checkTypeInst != NULL)
  2512. {
  2513. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2514. return true;
  2515. checkTypeInst = checkTypeInst->mBaseType;
  2516. }
  2517. return false;
  2518. }
  2519. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2520. {
  2521. if (mContext->mCurTypeState == NULL)
  2522. return;
  2523. BP_ZONE("PopulateGlobalContainersList");
  2524. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2525. if (userTypeDef == NULL)
  2526. userTypeDef = mCurTypeInstance->mTypeDef;
  2527. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2528. {
  2529. mContext->mCurTypeState->mGlobalContainers.Clear();
  2530. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2531. {
  2532. BfAtomComposite findStr;
  2533. if (namespaceIdx != -1)
  2534. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2535. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2536. while (typeDefItr)
  2537. {
  2538. auto typeDef = *typeDefItr;
  2539. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2540. {
  2541. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2542. {
  2543. BfGlobalContainerEntry globalEntry;
  2544. globalEntry.mTypeDef = typeDef;
  2545. globalEntry.mTypeInst = NULL;
  2546. typeDef->PopulateMemberSets();
  2547. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2548. }
  2549. }
  2550. else if (!typeDef->mIsPartial)
  2551. {
  2552. //break;
  2553. }
  2554. typeDefItr.MoveToNextHashMatch();
  2555. }
  2556. }
  2557. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2558. }
  2559. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2560. // reifing types
  2561. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2562. {
  2563. if (globalEntry.mTypeInst == NULL)
  2564. {
  2565. bool include = false;
  2566. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2567. include = true;
  2568. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2569. {
  2570. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2571. include = true;
  2572. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2573. include = true;
  2574. }
  2575. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2576. {
  2577. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2578. include = true;
  2579. }
  2580. if (include)
  2581. {
  2582. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2583. if (type != NULL)
  2584. globalEntry.mTypeInst = type->ToTypeInstance();
  2585. }
  2586. }
  2587. }
  2588. }
  2589. void PrintUsers(llvm::MDNode* md);
  2590. BfModuleOptions BfModule::GetModuleOptions()
  2591. {
  2592. if (mIsScratchModule)
  2593. return BfModuleOptions();
  2594. if (mModuleOptions != NULL)
  2595. return *mModuleOptions;
  2596. BfModuleOptions moduleOptions;
  2597. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2598. if (mProject != NULL)
  2599. {
  2600. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2601. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2602. }
  2603. auto headModule = this;
  2604. while (headModule->mParentModule != NULL)
  2605. headModule = headModule->mParentModule;
  2606. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2607. if (headModule->mOwnedTypeInstances.size() > 0)
  2608. {
  2609. auto typeInst = headModule->mOwnedTypeInstances[0];
  2610. PopulateType(typeInst);
  2611. if (typeInst->mTypeOptionsIdx != -1)
  2612. {
  2613. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2614. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2615. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2616. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2617. }
  2618. }
  2619. return moduleOptions;
  2620. }
  2621. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2622. {
  2623. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2624. auto typeOptions = GetTypeOptions();
  2625. if (typeOptions != NULL)
  2626. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2627. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2628. }
  2629. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2630. {
  2631. mContext->mFailTypes.Add(typeInstance);
  2632. }
  2633. void BfModule::CheckAddFailType()
  2634. {
  2635. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2636. // but we still need to add the owning type to the FailTypes list
  2637. //.. OLD:
  2638. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2639. /*if (mCurTypeInstance->mModule != this)
  2640. return;*/
  2641. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2642. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2643. // being recompiled. This forces types with warnings to be recompiled.
  2644. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2645. // constantly warning-aware
  2646. if ((mHadBuildError) ||
  2647. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2648. {
  2649. //mContext->mFailTypes.Add(mCurTypeInstance);
  2650. }
  2651. }
  2652. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2653. {
  2654. if (!mCompiler->IsHotCompile())
  2655. return;
  2656. typeInst->mDirty = true;
  2657. for (auto& dep : typeInst->mDependencyMap)
  2658. {
  2659. auto depType = dep.mKey;
  2660. auto depFlags = dep.mValue.mFlags;
  2661. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2662. {
  2663. MarkDerivedDirty(depType->ToTypeInstance());
  2664. }
  2665. }
  2666. }
  2667. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2668. {
  2669. auto fieldType = fieldInstance->GetResolvedType();
  2670. auto field = fieldInstance->GetFieldDef();
  2671. if (fieldType->IsVar())
  2672. return;
  2673. BfIRValue initValue;
  2674. if (field->mIsConst)
  2675. {
  2676. if (fieldType->IsPointer())
  2677. fieldType = fieldType->GetUnderlyingType();
  2678. }
  2679. if (!field->mIsExtern)
  2680. initValue = GetDefaultValue(fieldType);
  2681. if (fieldInstance->mOwner->IsUnspecializedType())
  2682. {
  2683. // Placeholder
  2684. auto ptrVal = CreatePointerType(fieldType);
  2685. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2686. }
  2687. else
  2688. {
  2689. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2690. StringT<128> staticVarName;
  2691. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2692. if (!fieldType->IsValuelessType())
  2693. {
  2694. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2695. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2696. false,
  2697. BfIRLinkageType_External,
  2698. initValue,
  2699. staticVarName,
  2700. isThreadLocal);
  2701. BF_ASSERT(globalVar);
  2702. mStaticFieldRefs[fieldInstance] = globalVar;
  2703. }
  2704. }
  2705. }
  2706. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2707. {
  2708. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2709. BfType* fieldType = NULL;
  2710. if (fieldInstance != NULL)
  2711. {
  2712. fieldType = fieldInstance->GetResolvedType();
  2713. if (fieldType == NULL)
  2714. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2715. }
  2716. else
  2717. {
  2718. BF_ASSERT(mCompiler->IsAutocomplete());
  2719. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2720. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2721. {
  2722. fieldType = typeInstance;
  2723. }
  2724. else
  2725. {
  2726. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2727. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2728. if (isLet || isVar)
  2729. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2730. else
  2731. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2732. if (fieldType == NULL)
  2733. fieldType = mContext->mBfObjectType;
  2734. }
  2735. }
  2736. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2737. return;
  2738. if (mContext->mFieldResolveReentrys.size() > 1)
  2739. {
  2740. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2741. {
  2742. String failStr = "Circular data reference detected between the following fields:";
  2743. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2744. {
  2745. if (i > 1)
  2746. failStr += ",";
  2747. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2748. }
  2749. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2750. if (err)
  2751. err->mIsPersistent = true;
  2752. return;
  2753. }
  2754. }
  2755. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2756. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2757. if (fieldInstance == NULL)
  2758. popTypeResolveReentry.Pop();
  2759. auto typeDef = typeInstance->mTypeDef;
  2760. BfIRValue constValue;
  2761. if (fieldDef->mIsExtern)
  2762. {
  2763. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2764. {
  2765. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2766. }
  2767. if (fieldDef->mInitializer != NULL)
  2768. {
  2769. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2770. }
  2771. }
  2772. else if (fieldDef->mInitializer == NULL)
  2773. {
  2774. if (fieldDef->IsEnumCaseEntry())
  2775. {
  2776. if (typeInstance->IsTypedPrimitive())
  2777. {
  2778. BfFieldInstance* prevFieldInstance = NULL;
  2779. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2780. {
  2781. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2782. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2783. {
  2784. prevFieldInstance = checkFieldInst;
  2785. break;
  2786. }
  2787. }
  2788. if (prevFieldInstance == NULL)
  2789. constValue = GetConstValue(0, typeInstance);
  2790. else
  2791. {
  2792. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2793. if (prevFieldInstance->mConstIdx == -1)
  2794. {
  2795. if (!mCompiler->IsAutocomplete())
  2796. AssertErrorState();
  2797. constValue = GetConstValue(0, typeInstance);
  2798. }
  2799. else
  2800. {
  2801. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2802. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2803. }
  2804. }
  2805. }
  2806. }
  2807. else
  2808. {
  2809. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2810. }
  2811. }
  2812. else
  2813. {
  2814. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2815. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2816. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2817. BfConstResolver constResolver(this);
  2818. BfMethodState methodState;
  2819. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2820. methodState.mTempKind = BfMethodState::TempKind_Static;
  2821. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2822. if (fieldType->IsVar())
  2823. {
  2824. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2825. if (!initValue)
  2826. {
  2827. AssertErrorState();
  2828. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2829. }
  2830. if (fieldInstance != NULL)
  2831. {
  2832. fieldInstance->mResolvedType = initValue.mType;
  2833. }
  2834. constValue = initValue.mValue;
  2835. }
  2836. else
  2837. {
  2838. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2839. constValue = uncastedInitValue.mValue;
  2840. }
  2841. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2842. }
  2843. if (fieldInstance != NULL)
  2844. {
  2845. fieldType = fieldInstance->GetResolvedType();
  2846. if ((fieldType == NULL) || (fieldType->IsVar()))
  2847. {
  2848. AssertErrorState();
  2849. // Default const type is 'int'
  2850. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2851. if (fieldInstance != NULL)
  2852. {
  2853. fieldInstance->mResolvedType = initValue.mType;
  2854. }
  2855. constValue = initValue.mValue;
  2856. }
  2857. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2858. {
  2859. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2860. CurrentAddToConstHolder(constValue);
  2861. fieldInstance->mConstIdx = constValue.mId;
  2862. }
  2863. }
  2864. }
  2865. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2866. {
  2867. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2868. auto fieldType = fieldInstance->GetResolvedType();
  2869. if ((field->mIsConst) && (!isDeclType))
  2870. {
  2871. ResolveConstField(typeInstance, fieldInstance, field);
  2872. return fieldInstance->GetResolvedType();
  2873. }
  2874. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2875. if (!fieldType->IsVar())
  2876. return fieldType;
  2877. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2878. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2879. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2880. auto typeDef = typeInstance->mTypeDef;
  2881. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2882. {
  2883. AssertErrorState();
  2884. return mContext->mBfObjectType;
  2885. }
  2886. bool hadInferenceCycle = false;
  2887. if (mContext->mFieldResolveReentrys.size() > 1)
  2888. {
  2889. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2890. {
  2891. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2892. {
  2893. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2894. auto fieldDef = fieldInst->GetFieldDef();
  2895. auto fieldOwner = fieldInst->mOwner;
  2896. auto fieldModule = fieldOwner->mModule;
  2897. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2898. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2899. }
  2900. return mContext->mBfObjectType;
  2901. }
  2902. }
  2903. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2904. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2905. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2906. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2907. if ((field->mInitializer == NULL) && (!isDeclType))
  2908. {
  2909. Fail("Implicitly-typed fields must be initialized", field->mFieldDeclaration);
  2910. return mContext->mBfObjectType;
  2911. }
  2912. BfType* resolvedType = NULL;
  2913. if (!hadInferenceCycle)
  2914. {
  2915. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2916. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2917. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2918. BfMethodState methodState;
  2919. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2920. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2921. if (!staticOnly)
  2922. {
  2923. //BfLocalVariable localVar;
  2924. //methodState.mLocals.push_back(localVar);
  2925. }
  2926. if (isDeclType)
  2927. {
  2928. auto fieldDef = fieldInstance->GetFieldDef();
  2929. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2930. }
  2931. else
  2932. {
  2933. BfTypedValue valueFromExpr;
  2934. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2935. FixIntUnknown(valueFromExpr);
  2936. resolvedType = valueFromExpr.mType;
  2937. }
  2938. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2939. }
  2940. if (resolvedType == NULL)
  2941. return mContext->mBfObjectType;
  2942. fieldInstance->SetResolvedType(resolvedType);
  2943. if (field->mIsStatic)
  2944. {
  2945. }
  2946. else if (fieldInstance->mDataIdx <= 0)
  2947. {
  2948. }
  2949. else
  2950. {
  2951. BF_ASSERT(typeInstance->IsIncomplete());
  2952. }
  2953. return resolvedType;
  2954. }
  2955. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2956. {
  2957. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2958. auto fieldType = fieldInstance->GetResolvedType();
  2959. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2960. {
  2961. int fieldDataCount = 1;
  2962. if (fieldType->IsStruct())
  2963. {
  2964. auto structTypeInst = fieldType->ToTypeInstance();
  2965. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2966. }
  2967. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2968. auto thisVariable = GetThisVariable();
  2969. if (thisVariable != NULL)
  2970. {
  2971. for (int i = 0; i < fieldDataCount; i++)
  2972. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2973. }
  2974. }
  2975. }
  2976. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2977. {
  2978. if (fieldInstance->mCustomAttributes == NULL)
  2979. return false;
  2980. auto fieldDef = fieldInstance->GetFieldDef();
  2981. if (!fieldDef->mIsStatic)
  2982. return false;
  2983. bool isThreadLocal = false;
  2984. if (fieldInstance->mCustomAttributes != NULL)
  2985. {
  2986. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2987. {
  2988. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  2989. return true;
  2990. }
  2991. }
  2992. return false;
  2993. }
  2994. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  2995. {
  2996. if (fieldDef == NULL)
  2997. fieldDef = fieldInstance->GetFieldDef();
  2998. if (fieldType == NULL)
  2999. fieldType = fieldInstance->GetResolvedType();
  3000. if (initializer == NULL)
  3001. {
  3002. if (fieldDef == NULL)
  3003. return BfTypedValue();
  3004. initializer = fieldDef->mInitializer;
  3005. }
  3006. BfTypedValue result;
  3007. if (initializer == NULL)
  3008. {
  3009. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3010. }
  3011. else
  3012. {
  3013. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3014. {
  3015. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3016. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3017. }
  3018. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3019. {
  3020. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3021. BfConstResolver constResolver(this);
  3022. constResolver.Resolve(initializer);
  3023. return GetDefaultTypedValue(fieldType);
  3024. }
  3025. else if (fieldDef->mIsConst)
  3026. {
  3027. BfTypeState typeState;
  3028. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3029. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3030. BfConstResolver constResolver(this);
  3031. if (fieldType->IsVar())
  3032. return constResolver.Resolve(initializer);
  3033. else
  3034. return constResolver.Resolve(initializer, fieldType);
  3035. }
  3036. if (fieldType->IsVar())
  3037. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3038. else
  3039. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3040. }
  3041. if (fieldInstance != NULL)
  3042. MarkFieldInitialized(fieldInstance);
  3043. return result;
  3044. }
  3045. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3046. {
  3047. }
  3048. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3049. {
  3050. PopulateType(classType);
  3051. if (isInterfacePass)
  3052. {
  3053. for (auto ifaceInst : classType->mInterfaces)
  3054. {
  3055. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3056. continue;
  3057. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3058. continue;
  3059. if (ifaceInst.mDeclaringType->IsExtension())
  3060. {
  3061. bool needsExCheck = false;
  3062. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3063. {
  3064. exChecks->push_back(ifaceInst.mInterfaceType);
  3065. continue;
  3066. }
  3067. }
  3068. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3069. }
  3070. }
  3071. else
  3072. {
  3073. outVals->push_back(classType->mTypeId);
  3074. }
  3075. if (classType->mBaseType != NULL)
  3076. {
  3077. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3078. }
  3079. }
  3080. void BfModule::CreateDynamicCastMethod()
  3081. {
  3082. auto objType = mContext->mBfObjectType;
  3083. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3084. {
  3085. // The main reason to punt on this method for ResolveOnly is because types can be created
  3086. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3087. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3088. // remove this punt when we recycle typeId's
  3089. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3090. mCurMethodState->mHadReturn = true;
  3091. return;
  3092. }
  3093. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3094. auto func = mCurMethodState->mIRFunction;
  3095. auto thisValue = mBfIRBuilder->GetArgument(0);
  3096. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3097. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3098. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3099. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3100. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3101. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3102. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3103. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3104. SizedArray<int, 8> typeMatches;
  3105. SizedArray<BfTypeInstance*, 8> exChecks;
  3106. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3107. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3108. {
  3109. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3110. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3111. BfTypeVector genericArgs;
  3112. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3113. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3114. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3115. typeMatches.push_back(unboundType->mTypeId);
  3116. }
  3117. if (mCurTypeInstance->IsBoxed())
  3118. {
  3119. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3120. BfTypeInstance* innerType = boxedType->mElementType;
  3121. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3122. if (innerType->IsTypedPrimitive())
  3123. {
  3124. auto underlyingType = innerType->GetUnderlyingType();
  3125. typeMatches.push_back(underlyingType->mTypeId);
  3126. }
  3127. auto innerTypeInst = innerType->ToTypeInstance();
  3128. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3129. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3130. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3131. {
  3132. PopulateType(innerTypeInst);
  3133. //TODO: What case was this supposed to handle?
  3134. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3135. }
  3136. }
  3137. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3138. BfIRValue vDataPtr;
  3139. if (!exChecks.empty())
  3140. {
  3141. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3142. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3143. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3144. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3145. }
  3146. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3147. for (auto typeMatch : typeMatches)
  3148. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3149. Array<BfIRValue> incomingFalses;
  3150. for (auto ifaceTypeInst : exChecks)
  3151. {
  3152. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3153. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3154. mBfIRBuilder->SetInsertPoint(nextBB);
  3155. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3156. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3157. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3158. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3159. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3160. incomingFalses.push_back(nextBB);
  3161. }
  3162. mBfIRBuilder->AddBlock(trueBB);
  3163. mBfIRBuilder->SetInsertPoint(trueBB);
  3164. mBfIRBuilder->CreateBr(exitBB);
  3165. mBfIRBuilder->AddBlock(exitBB);
  3166. mBfIRBuilder->SetInsertPoint(exitBB);
  3167. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3168. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3169. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3170. for (auto incomingFalseBlock : incomingFalses)
  3171. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3172. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3173. mBfIRBuilder->CreateRet(phi);
  3174. mCurMethodState->mHadReturn = true;
  3175. }
  3176. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3177. {
  3178. BfExprEvaluator exprEvaluator(this);
  3179. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3180. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3181. BfTypedValue result = exprEvaluator.GetResult();
  3182. if (result)
  3183. {
  3184. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3185. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3186. mBfIRBuilder->AddBlock(nextBB);
  3187. mBfIRBuilder->SetInsertPoint(nextBB);
  3188. }
  3189. }
  3190. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3191. {
  3192. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3193. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3194. SizedArray<BfIRType, 4> paramTypes;
  3195. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3196. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3197. mBfIRBuilder->SetActiveFunction(func);
  3198. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3199. mBfIRBuilder->SetInsertPoint(entryBlock);
  3200. SizedArray<BfIRValue, 8> args;
  3201. BfExprEvaluator exprEvaluator(this);
  3202. if (mCurMethodInstance->HasThis())
  3203. {
  3204. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3205. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3206. }
  3207. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3208. {
  3209. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3210. if (paramType->IsValuelessType())
  3211. continue;
  3212. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3213. }
  3214. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3215. mBfIRBuilder->CreateRetVoid();
  3216. }
  3217. void BfModule::CreateValueTypeEqualsMethod()
  3218. {
  3219. if (mCurMethodInstance->mIsUnspecialized)
  3220. return;
  3221. if (mCurTypeInstance->IsTypedPrimitive())
  3222. return;
  3223. if (mBfIRBuilder->mIgnoreWrites)
  3224. return;
  3225. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3226. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3227. bool isValid = true;
  3228. auto compareDType = compareType->ToDependedType();
  3229. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3230. if (compareTypeInst != NULL)
  3231. {
  3232. if (compareType->IsPrimitiveType())
  3233. compareTypeInst = GetWrappedStructType(compareType);
  3234. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3235. {
  3236. isValid = false;
  3237. }
  3238. mBfIRBuilder->PopulateType(compareTypeInst);
  3239. }
  3240. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3241. if (!isValid)
  3242. {
  3243. ClearLifetimeEnds();
  3244. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3245. return;
  3246. }
  3247. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3248. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3249. if (refNode == NULL)
  3250. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3251. UpdateSrcPos(refNode);
  3252. SetIllegalSrcPos();
  3253. auto resultVal = CreateAlloca(boolType);
  3254. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3255. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3256. if (compareType->IsSizedArray())
  3257. {
  3258. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3259. if (sizedArrayType->mElementCount > 6)
  3260. {
  3261. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3262. auto itr = CreateAlloca(intPtrType);
  3263. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3264. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3265. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3266. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3267. mBfIRBuilder->CreateBr(loopBB);
  3268. mBfIRBuilder->SetInsertPoint(loopBB);
  3269. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3270. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3271. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3272. mBfIRBuilder->SetInsertPoint(bodyBB);
  3273. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3274. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3275. EmitEquals(leftValue, rightValue, exitBB);
  3276. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3277. mBfIRBuilder->CreateStore(incValue, itr);
  3278. mBfIRBuilder->CreateBr(loopBB);
  3279. mBfIRBuilder->SetInsertPoint(doneBB);
  3280. }
  3281. else
  3282. {
  3283. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3284. {
  3285. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3286. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3287. EmitEquals(leftValue, rightValue, exitBB);
  3288. }
  3289. }
  3290. }
  3291. else if (compareType->IsMethodRef())
  3292. {
  3293. auto methodRefType = (BfMethodRefType*)compareType;
  3294. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3295. BfExprEvaluator exprEvaluator(this);
  3296. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3297. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3298. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3299. // values for the same method reference -- they will always refer back to the same local variables.
  3300. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3301. if (dataIdx != -1)
  3302. {
  3303. bool failed = false;
  3304. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3305. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3306. BF_ASSERT(!failed);
  3307. EmitEquals(leftValue, rightValue, exitBB);
  3308. }
  3309. }
  3310. else if (compareTypeInst->IsEnum())
  3311. {
  3312. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3313. BfExprEvaluator exprEvaluator(this);
  3314. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3315. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3316. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3317. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3318. leftValue = LoadValue(leftValue);
  3319. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3320. rightValue = LoadValue(rightValue);
  3321. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3322. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3323. EmitEquals(leftValue, rightValue, exitBB);
  3324. int enumCount = 0;
  3325. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3326. {
  3327. BfFieldInstance* fieldInstance = &fieldRef;
  3328. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3329. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3330. {
  3331. enumCount = -fieldInstance->mDataIdx;
  3332. }
  3333. }
  3334. if (enumCount > 0)
  3335. {
  3336. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3337. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3338. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3339. {
  3340. BfFieldInstance* fieldInstance = &fieldRef;
  3341. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3342. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3343. {
  3344. int enumIdx = -fieldInstance->mDataIdx - 1;
  3345. if (fieldInstance->mResolvedType->mSize == 0)
  3346. {
  3347. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3348. }
  3349. else
  3350. {
  3351. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3352. mBfIRBuilder->SetInsertPoint(caseBlock);
  3353. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3354. BfTypedValue leftTuple;
  3355. BfTypedValue rightTuple;
  3356. if (leftPayload.IsAddr())
  3357. {
  3358. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3359. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3360. }
  3361. else
  3362. {
  3363. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3364. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3365. }
  3366. EmitEquals(leftTuple, rightTuple, exitBB);
  3367. mBfIRBuilder->CreateBr(matchedBlock);
  3368. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3369. }
  3370. }
  3371. }
  3372. mBfIRBuilder->AddBlock(matchedBlock);
  3373. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3374. }
  3375. }
  3376. else if (compareTypeInst->IsUnion())
  3377. {
  3378. auto innerType = compareTypeInst->GetUnionInnerType();
  3379. if (!innerType->IsValuelessType())
  3380. {
  3381. BfExprEvaluator exprEvaluator(this);
  3382. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3383. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3384. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3385. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3386. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3387. }
  3388. }
  3389. else
  3390. {
  3391. BfExprEvaluator exprEvaluator(this);
  3392. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3393. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3394. bool hadComparison = false;
  3395. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3396. {
  3397. BfFieldInstance* fieldInstance = &fieldRef;
  3398. if (fieldInstance->mDataOffset == -1)
  3399. continue;
  3400. if (fieldInstance->mResolvedType->IsValuelessType())
  3401. continue;
  3402. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3403. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3404. if (!fieldInstance->mResolvedType->IsComposite())
  3405. {
  3406. leftValue = LoadValue(leftValue);
  3407. rightValue = LoadValue(rightValue);
  3408. }
  3409. EmitEquals(leftValue, rightValue, exitBB);
  3410. }
  3411. auto baseTypeInst = compareTypeInst->mBaseType;
  3412. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3413. {
  3414. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3415. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3416. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3417. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3418. EmitEquals(leftValue, rightValue, exitBB);
  3419. }
  3420. }
  3421. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3422. mBfIRBuilder->CreateBr(exitBB);
  3423. mBfIRBuilder->AddBlock(exitBB);
  3424. mBfIRBuilder->SetInsertPoint(exitBB);
  3425. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3426. ClearLifetimeEnds();
  3427. mBfIRBuilder->CreateRet(loadedResult);
  3428. mCurMethodState->mHadReturn = true;
  3429. }
  3430. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3431. {
  3432. if (mBfIRBuilder->mIgnoreWrites)
  3433. return mBfIRBuilder->GetFakeVal();
  3434. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3435. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3436. BfIRValue* globalVariablePtr = NULL;
  3437. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3438. int numElements = 1;
  3439. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3440. {
  3441. numElements += mCompiler->mMaxInterfaceSlots;
  3442. auto maxIFaceVirtIdx = 0;
  3443. if (!typeInstance->IsInterface())
  3444. {
  3445. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3446. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3447. numElements += typeInstance->GetOrigVTableSize();
  3448. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3449. if (typeInstance->mHotTypeData != NULL)
  3450. {
  3451. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3452. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3453. }
  3454. numElements += ifaceMethodLen;
  3455. }
  3456. if (outNumElements != NULL)
  3457. *outNumElements = numElements;
  3458. }
  3459. StringT<128> classVDataName;
  3460. if ((mCompiler->IsHotCompile()) && (typeInstance->mTypeDef->mName->ToString() == "ClassC"))
  3461. {
  3462. NOP;
  3463. }
  3464. String memberName = "sBfClassVData";
  3465. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3466. {
  3467. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3468. memberName += "_";
  3469. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3470. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3471. }
  3472. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3473. if (outMangledName != NULL)
  3474. *outMangledName = classVDataName;
  3475. /*if (itr != mClassVDataRefs.end())
  3476. {
  3477. globalVariable = itr->second;
  3478. }*/
  3479. BfIRValue globalVariable;
  3480. if (globalVariablePtr != NULL)
  3481. {
  3482. globalVariable = *globalVariablePtr;
  3483. }
  3484. else
  3485. {
  3486. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3487. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3488. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3489. arrayType,
  3490. true,
  3491. BfIRLinkageType_External,
  3492. BfIRValue(),
  3493. classVDataName);
  3494. mClassVDataRefs[typeInstance] = globalVariable;
  3495. }
  3496. return globalVariable;
  3497. }
  3498. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3499. {
  3500. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3501. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3502. }
  3503. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3504. {
  3505. if (mBfIRBuilder->mIgnoreWrites)
  3506. return mBfIRBuilder->GetFakeVal();
  3507. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3508. BF_ASSERT(numElements >= 0);
  3509. if (numElements <= 0)
  3510. return BfIRValue();
  3511. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3512. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3513. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3514. BF_ASSERT(declTypeInst == implTypeInst);
  3515. else
  3516. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3517. if (declTypeInst != implTypeInst)
  3518. {
  3519. BfTypeInstance* highestImpl = declTypeInst;
  3520. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3521. {
  3522. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3523. break; // Start of an ext entry for another type
  3524. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3525. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3526. highestImpl = checkImplTypeInst;
  3527. }
  3528. if (highestImpl != implTypeInst)
  3529. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3530. }
  3531. BfVDataExtEntry mapEntry;
  3532. mapEntry.mDeclTypeInst = declTypeInst;
  3533. mapEntry.mImplTypeInst = implTypeInst;
  3534. BfIRValue* irValuePtr = NULL;
  3535. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3536. return *irValuePtr;
  3537. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3538. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3539. StringT<128> classVDataName;
  3540. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3541. if (declTypeInst != implTypeInst)
  3542. {
  3543. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3544. }
  3545. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3546. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3547. SizedArray<BfIRValue, 32> vData;
  3548. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3549. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3550. {
  3551. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3552. break; // Start of an ext entry for another type
  3553. BfIRValue vValue;
  3554. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3555. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3556. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3557. {
  3558. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3559. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3560. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3561. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3562. {
  3563. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3564. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3565. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3566. vValue = funcPtr;
  3567. }
  3568. }
  3569. if (!vValue)
  3570. vValue = voidPtrNull;
  3571. vData.Add(vValue);
  3572. }
  3573. BF_ASSERT((int)vData.size() == numElements);
  3574. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3575. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3576. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3577. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3578. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3579. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3580. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3581. mClassVDataExtRefs[mapEntry] = globalVariable;
  3582. return globalVariable;
  3583. }
  3584. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3585. {
  3586. if (mBfIRBuilder->mIgnoreWrites)
  3587. {
  3588. return mBfIRBuilder->CreateTypeOf(type);
  3589. }
  3590. BfIRValue globalVariable;
  3591. BfIRValue* globalVariablePtr = NULL;
  3592. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3593. {
  3594. globalVariable = *globalVariablePtr;
  3595. if (globalVariable)
  3596. return globalVariable;
  3597. }
  3598. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3599. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3600. auto typeInstance = type->ToTypeInstance();
  3601. StringT<128> typeDataName;
  3602. if (typeInstance != NULL)
  3603. {
  3604. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3605. }
  3606. else
  3607. {
  3608. typeDataName += "sBfTypeData.";
  3609. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3610. }
  3611. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3612. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3613. mTypeDataRefs[type] = globalVariable;
  3614. return globalVariable;
  3615. }
  3616. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3617. {
  3618. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3619. return BfIRValue();
  3620. BfIRValue* irValuePtr = NULL;
  3621. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3622. {
  3623. return *irValuePtr;
  3624. }
  3625. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3626. // BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef, BfPopulateType_Identity);
  3627. // mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3628. // PopulateType(typeInstanceType);
  3629. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3630. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3631. if (typeInstanceType == NULL)
  3632. {
  3633. AssertErrorState();
  3634. return BfIRValue();
  3635. }
  3636. BfIRValue typeTypeData;
  3637. int typeFlags = 0;
  3638. if (needsTypeData)
  3639. {
  3640. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3641. BfTypeInstance* typeDataSource = NULL;
  3642. if (typeInstance != NULL)
  3643. {
  3644. if (typeInstance->IsUnspecializedType())
  3645. {
  3646. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3647. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3648. }
  3649. else if (typeInstance->IsArray())
  3650. {
  3651. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3652. typeFlags |= BfTypeFlags_Array;
  3653. }
  3654. else if (typeInstance->IsGenericTypeInstance())
  3655. {
  3656. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3657. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3658. }
  3659. else
  3660. typeDataSource = typeInstanceTypeInstance;
  3661. }
  3662. else if (type->IsPointer())
  3663. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3664. else if (type->IsSizedArray())
  3665. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3666. else
  3667. typeDataSource = mContext->mBfTypeType;
  3668. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3669. {
  3670. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3671. }
  3672. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3673. }
  3674. else
  3675. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3676. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3677. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3678. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3679. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3680. BfType* typeIdType = intType;
  3681. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3682. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3683. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3684. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3685. SizedArray<BfIRValue, 4> typeValueParams;
  3686. GetConstClassValueParam(typeTypeData, typeValueParams);
  3687. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3688. StringT<128> typeDataName;
  3689. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3690. {
  3691. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3692. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3693. typeDataName += "@" + typeInstance->mTypeDef->mProject->mName;
  3694. }
  3695. else
  3696. {
  3697. typeDataName += "sBfTypeData.";
  3698. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3699. }
  3700. int typeCode = BfTypeCode_None;
  3701. if (typeInstance != NULL)
  3702. {
  3703. typeCode = typeInstance->mTypeDef->mTypeCode;
  3704. }
  3705. else if (type->IsPrimitiveType())
  3706. {
  3707. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3708. typeCode = primType->mTypeDef->mTypeCode;
  3709. }
  3710. else if (type->IsPointer())
  3711. {
  3712. typeCode = BfTypeCode_Pointer;
  3713. typeFlags |= BfTypeFlags_Pointer;
  3714. }
  3715. if (type->IsObject())
  3716. {
  3717. typeFlags |= BfTypeFlags_Object;
  3718. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3719. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3720. typeFlags |= BfTypeFlags_HasDestructor;
  3721. }
  3722. if (type->IsStruct())
  3723. typeFlags |= BfTypeFlags_Struct;
  3724. if (type->IsBoxed())
  3725. typeFlags |= BfTypeFlags_Boxed;
  3726. if (type->IsPrimitiveType())
  3727. typeFlags |= BfTypeFlags_Primitive;
  3728. if (type->IsTypedPrimitive())
  3729. typeFlags |= BfTypeFlags_TypedPrimitive;
  3730. if (type->IsTuple())
  3731. typeFlags |= BfTypeFlags_Tuple;
  3732. if (type->IsNullable())
  3733. typeFlags |= BfTypeFlags_Nullable;
  3734. if (type->IsSizedArray())
  3735. typeFlags |= BfTypeFlags_SizedArray;
  3736. if (type->IsSplattable())
  3737. typeFlags |= BfTypeFlags_Splattable;
  3738. if (type->IsUnion())
  3739. typeFlags |= BfTypeFlags_Union;
  3740. if (type->IsDelegate())
  3741. typeFlags |= BfTypeFlags_Delegate;
  3742. if (typeInstance != NULL)
  3743. {
  3744. if (typeInstance->mTypeDef == mCompiler->mPointerTTypeDef)
  3745. typeFlags |= BfTypeFlags_Sys_PointerT;
  3746. }
  3747. if (type->WantsGCMarking())
  3748. typeFlags |= BfTypeFlags_WantsMarking;
  3749. int memberDataOffset = 0;
  3750. if (typeInstance != NULL)
  3751. {
  3752. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3753. {
  3754. if (fieldInstance.mDataOffset != -1)
  3755. {
  3756. memberDataOffset = fieldInstance.mDataOffset;
  3757. break;
  3758. }
  3759. }
  3760. }
  3761. SizedArray<BfIRValue, 8> typeDataParams =
  3762. {
  3763. objectData,
  3764. GetConstValue(type->mSize, intType), // mSize
  3765. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3766. GetConstValue(typeFlags, intType), // mTypeFlags
  3767. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3768. GetConstValue(typeCode, byteType), // mTypeCode
  3769. GetConstValue(type->mAlign, byteType),
  3770. };
  3771. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3772. if (typeInstance == NULL)
  3773. {
  3774. BfIRValue typeDataVar;
  3775. if (needsTypeData)
  3776. {
  3777. if (type->IsPointer())
  3778. {
  3779. auto pointerType = (BfPointerType*)type;
  3780. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3781. {
  3782. typeData,
  3783. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3784. };
  3785. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3786. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3787. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3788. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3789. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3790. }
  3791. else if (type->IsSizedArray())
  3792. {
  3793. auto sizedArrayType = (BfSizedArrayType*)type;
  3794. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3795. {
  3796. typeData,
  3797. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3798. GetConstValue(sizedArrayType->mElementCount, intType)
  3799. };
  3800. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3801. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3802. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3803. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3804. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3805. }
  3806. else
  3807. {
  3808. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3809. BfIRLinkageType_External, typeData, typeDataName);
  3810. }
  3811. }
  3812. else
  3813. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3814. mTypeDataRefs[typeInstance] = typeDataVar;
  3815. return typeDataVar;
  3816. }
  3817. // Reserve position
  3818. mTypeDataRefs[typeInstance] = BfIRValue();
  3819. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3820. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3821. StringT<128> mangledName;
  3822. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance);
  3823. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3824. {
  3825. auto methodDef = typeDef->mMethods[methodIdx];
  3826. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3827. if (methodInstance == NULL)
  3828. continue;
  3829. if (typeInstance->IsUnspecializedType())
  3830. continue;
  3831. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3832. {
  3833. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3834. {
  3835. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3836. // We need to create an empty thunk for this chained method
  3837. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3838. mBfIRBuilder->SetActiveFunction(func);
  3839. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3840. mBfIRBuilder->SetInsertPoint(block);
  3841. mBfIRBuilder->CreateRetVoid();
  3842. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3843. }
  3844. }
  3845. }
  3846. SizedArray<BfIRValue, 32> vData;
  3847. BfIRValue classVDataVar;
  3848. String classVDataName;
  3849. if (typeInstance->mSlotNum >= 0)
  3850. {
  3851. // For interfaces we ONLY emit the slot num
  3852. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3853. StringT<128> slotVarName;
  3854. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3855. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3856. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3857. GetConstValue32(virtSlotIdx), slotVarName);
  3858. }
  3859. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3860. {
  3861. int dynCastDataElems = 0;
  3862. int numElements = 1;
  3863. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3864. numElements += mCompiler->mMaxInterfaceSlots;
  3865. if (!typeInstance->IsInterface())
  3866. {
  3867. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3868. numElements += mCompiler->GetDynCastVDataCount();
  3869. numElements += typeInstance->mVirtualMethodTableSize;
  3870. }
  3871. int expectNumElements = 0;
  3872. if (!typeDef->mIsStatic)
  3873. {
  3874. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3875. }
  3876. vData.push_back(BfIRValue()); // Type*
  3877. SizedArray<BfIRValue, 1> extVTableData;
  3878. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3879. if (!typeInstance->IsInterface())
  3880. {
  3881. Array<int32> dynCastData;
  3882. if (typeInstance->IsBoxed())
  3883. {
  3884. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3885. dynCastData.Add(underlyingType->mInheritanceId);
  3886. }
  3887. else
  3888. dynCastData.Add(typeInstance->mInheritanceId);
  3889. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3890. dynCastData.Add(0);
  3891. dynCastData.Add(0);
  3892. auto checkTypeInst = typeInstance;
  3893. while (checkTypeInst != NULL)
  3894. {
  3895. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3896. {
  3897. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3898. {
  3899. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3900. }
  3901. }
  3902. checkTypeInst = checkTypeInst->mBaseType;
  3903. }
  3904. if (mSystem->mPtrSize == 8)
  3905. {
  3906. int intPtrCount = (dynCastDataElems + 1) / 2;
  3907. vDataOfs += intPtrCount;
  3908. uint64* intPtrData = (uint64*)&dynCastData[0];
  3909. for (int i = 0; i < intPtrCount; i++)
  3910. {
  3911. uint64 val = intPtrData[i];
  3912. if (val == 0)
  3913. {
  3914. vData.push_back(voidPtrNull);
  3915. }
  3916. else
  3917. {
  3918. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3919. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3920. }
  3921. }
  3922. }
  3923. else
  3924. {
  3925. int intPtrCount = dynCastDataElems;
  3926. vDataOfs += intPtrCount;
  3927. uint32* intPtrData = (uint32*)&dynCastData[0];
  3928. for (int i = 0; i < intPtrCount; i++)
  3929. {
  3930. uint32 val = intPtrData[i];
  3931. if (val == 0)
  3932. {
  3933. vData.push_back(voidPtrNull);
  3934. }
  3935. else
  3936. {
  3937. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3938. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3939. }
  3940. }
  3941. }
  3942. }
  3943. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3944. vData.push_back(voidPtrNull);
  3945. struct _InterfaceMatchEntry
  3946. {
  3947. BfTypeInterfaceEntry* mEntry;
  3948. BfTypeInstance* mEntrySource;
  3949. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3950. };
  3951. int highestIFaceVirtIdx = 0;
  3952. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3953. auto checkTypeInst = typeInstance;
  3954. while (checkTypeInst != NULL)
  3955. {
  3956. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3957. {
  3958. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3959. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3960. continue;
  3961. _InterfaceMatchEntry* matchEntry = NULL;
  3962. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3963. {
  3964. auto prevEntry = matchEntry->mEntry;
  3965. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3966. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3967. if (isBetter == isWorse)
  3968. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3969. if (isBetter == isWorse)
  3970. {
  3971. if (matchEntry->mAmbiguousEntries.empty())
  3972. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3973. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3974. continue;
  3975. }
  3976. else if (isBetter)
  3977. {
  3978. matchEntry->mEntry = &interfaceEntry;
  3979. matchEntry->mEntrySource = checkTypeInst;
  3980. matchEntry->mAmbiguousEntries.Clear();
  3981. }
  3982. else
  3983. continue;
  3984. }
  3985. else
  3986. {
  3987. _InterfaceMatchEntry matchEntry;
  3988. matchEntry.mEntry = &interfaceEntry;
  3989. matchEntry.mEntrySource = checkTypeInst;
  3990. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  3991. }
  3992. }
  3993. checkTypeInst = checkTypeInst->mBaseType;
  3994. }
  3995. for (auto interfacePair : interfaceMap)
  3996. {
  3997. auto& interfaceMatchEntry = interfacePair.mValue;
  3998. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  3999. {
  4000. 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());
  4001. if (error != NULL)
  4002. {
  4003. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4004. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4005. }
  4006. }
  4007. }
  4008. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4009. {
  4010. int startTabIdx = (int)vData.size();
  4011. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4012. BfTypeInstance* checkTypeInst = typeInstance;
  4013. while (checkTypeInst != NULL)
  4014. {
  4015. origVirtTypeStack.push_back(checkTypeInst);
  4016. checkTypeInst = checkTypeInst->mBaseType;
  4017. }
  4018. Array<BfVirtualMethodEntry> origVTable;
  4019. int origVirtIdx = 0;
  4020. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4021. {
  4022. HashSet<String> reslotNames;
  4023. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4024. {
  4025. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4026. if (entry.mDeclaringMethod.mMethodNum == -1)
  4027. continue;
  4028. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4029. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4030. {
  4031. if (origVTable.empty())
  4032. origVTable = typeInstance->mVirtualMethodTable;
  4033. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4034. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4035. {
  4036. // Prepare to reslot...
  4037. entry.mImplementingMethod = entry.mDeclaringMethod;
  4038. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4039. }
  4040. else
  4041. {
  4042. // Decl isn't accessible, null out entry
  4043. entry.mImplementingMethod = BfMethodRef();
  4044. }
  4045. }
  4046. }
  4047. if (!reslotNames.IsEmpty())
  4048. {
  4049. BfAmbiguityContext ambiguityContext;
  4050. ambiguityContext.mTypeInstance = typeInstance;
  4051. ambiguityContext.mModule = this;
  4052. ambiguityContext.mIsProjectSpecific = true;
  4053. ambiguityContext.mIsReslotting = true;
  4054. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4055. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4056. {
  4057. auto methodInstance = methodGroup.mDefault;
  4058. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4059. continue;
  4060. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4061. continue;
  4062. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4063. continue;
  4064. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4065. continue;
  4066. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4067. }
  4068. ambiguityContext.Finish();
  4069. }
  4070. }
  4071. bool isInExts = false;
  4072. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4073. {
  4074. BfIRValue vValue = voidPtrNull;
  4075. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4076. BfModuleMethodInstance moduleMethodInst;
  4077. if (entry.mDeclaringMethod.mMethodNum == -1)
  4078. {
  4079. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4080. isInExts = true;
  4081. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4082. if (vExt)
  4083. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4084. }
  4085. else
  4086. {
  4087. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4088. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4089. {
  4090. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4091. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4092. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4093. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4094. {
  4095. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4096. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4097. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4098. vValue = funcPtr;
  4099. }
  4100. }
  4101. }
  4102. while (origVirtTypeStack.size() != 0)
  4103. {
  4104. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4105. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4106. {
  4107. // Moved past current base vtable size
  4108. origVirtTypeStack.pop_back();
  4109. continue;
  4110. }
  4111. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4112. {
  4113. // We are within the original vtable size
  4114. int idx = startTabIdx + origVirtIdx;
  4115. origVirtIdx++;
  4116. vData.push_back(vValue);
  4117. }
  4118. else
  4119. {
  4120. // This is a new entry, it only gets added to the ext
  4121. BF_ASSERT(isInExts);
  4122. }
  4123. break;
  4124. }
  4125. }
  4126. if (!origVTable.empty())
  4127. typeInstance->mVirtualMethodTable = origVTable;
  4128. }
  4129. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4130. if (typeInstance->mHotTypeData != NULL)
  4131. {
  4132. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4133. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4134. }
  4135. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4136. int iFaceMethodStartIdx = (int)vData.size();
  4137. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4138. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4139. vData[i] = voidPtrNull;
  4140. if (expectNumElements != 0)
  4141. BF_ASSERT(expectNumElements == vData.size());
  4142. //BF_ASSERT(vData.size() == expectNumElements);
  4143. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4144. // ifaceMethodExtData.Add(voidPtrNull);
  4145. int ifaceEntryIdx = iFaceMethodStartIdx;
  4146. for (auto& interfacePair : interfaceMap)
  4147. {
  4148. auto interfaceEntry = interfacePair.mValue.mEntry;
  4149. bool makeEmpty = false;
  4150. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4151. makeEmpty = true;
  4152. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4153. // for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4154. // {
  4155. // BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4156. // if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4157. // continue;
  4158. // endVirtualIdx = BF_MAX(endVirtualIdx, interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx);
  4159. // }
  4160. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4161. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4162. {
  4163. BfIRValue pushValue;
  4164. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4165. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4166. continue;
  4167. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4168. continue;
  4169. if (makeEmpty)
  4170. {
  4171. pushValue = voidPtrNull;
  4172. }
  4173. else
  4174. {
  4175. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4176. auto methodInstance = (BfMethodInstance*)methodRef;
  4177. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4178. {
  4179. BF_ASSERT(methodInstance->mIsReified);
  4180. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4181. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4182. BfMethodInstance* methodInstance = methodRef;
  4183. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4184. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4185. pushValue = funcPtr;
  4186. }
  4187. else
  4188. {
  4189. pushValue = voidPtrNull;
  4190. }
  4191. }
  4192. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4193. // if (!useExt)
  4194. // vData[iFaceMethodStartIdx + idx] = pushValue;
  4195. if (idx < ifaceMethodExtStart)
  4196. {
  4197. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4198. vData[iFaceMethodStartIdx + idx] = pushValue;
  4199. }
  4200. else
  4201. {
  4202. BF_ASSERT(useExt);
  4203. int extIdx = idx - ifaceMethodExtStart;
  4204. while (extIdx >= ifaceMethodExtData.size())
  4205. ifaceMethodExtData.Add(voidPtrNull);
  4206. ifaceMethodExtData[extIdx] = pushValue;
  4207. }
  4208. }
  4209. }
  4210. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4211. {
  4212. BfIRValue ifaceMethodExtVar;
  4213. if (!ifaceMethodExtData.IsEmpty())
  4214. {
  4215. StringT<128> classVDataName;
  4216. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4217. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4218. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4219. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4220. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4221. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4222. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4223. }
  4224. for (auto& ifaceInstPair : interfaceMap)
  4225. {
  4226. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4227. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4228. if (slotNum >= 0)
  4229. {
  4230. BfIRValue vtablePtr;
  4231. int idx = interfaceEntry->mStartVirtualIdx;
  4232. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4233. if (endVirtualIdx > ifaceMethodExtStart)
  4234. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4235. else
  4236. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4237. int slotVirtIdx = slotNum + vDataOfs;
  4238. if (vData[slotVirtIdx] == voidPtrNull)
  4239. {
  4240. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4241. }
  4242. else
  4243. {
  4244. if (mCompiler->IsHotCompile())
  4245. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4246. else
  4247. Fail("Interface slot collision error", typeDef->GetRefNode());
  4248. }
  4249. }
  4250. }
  4251. }
  4252. }
  4253. BfIRValue typeNameConst;
  4254. BfIRValue namespaceConst;
  4255. if (needsTypeNames)
  4256. {
  4257. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4258. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4259. }
  4260. else
  4261. {
  4262. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4263. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4264. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4265. }
  4266. int baseTypeId = 0;
  4267. if (typeInstance->mBaseType != NULL)
  4268. {
  4269. baseTypeId = typeInstance->mBaseType->mTypeId;
  4270. }
  4271. SizedArray<BfIRValue, 16> customAttrs;
  4272. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4273. BfIRValue castedClassVData;
  4274. if (classVDataVar)
  4275. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4276. else
  4277. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4278. bool freflectIncludeTypeData = false;
  4279. bool reflectIncludeAllFields = false;
  4280. bool reflectIncludeAllMethods = false;
  4281. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4282. {
  4283. reflectIncludeAllFields = true;
  4284. reflectIncludeAllMethods = true;
  4285. }
  4286. enum ReflectKind
  4287. {
  4288. ReflectKind_None = 0,
  4289. ReflectKind_Type = 1,
  4290. ReflectKind_NonStaticFields = 2,
  4291. ReflectKind_StaticFields = 4,
  4292. ReflectKind_DefaultConstructor = 8,
  4293. ReflectKind_Constructors = 0x10,
  4294. ReflectKind_StaticMethods = 0x20,
  4295. ReflectKind_Methods = 0x40,
  4296. ReflectKind_User = 0x80,
  4297. ReflectKind_All = 0x7F,
  4298. ReflectKind_ApplyToInnerTypes = 0x80
  4299. };
  4300. ReflectKind reflectKind = ReflectKind_Type;
  4301. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4302. {
  4303. ReflectKind reflectKind = ReflectKind_None;
  4304. if (attrType->mCustomAttributes != NULL)
  4305. {
  4306. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4307. {
  4308. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4309. {
  4310. for (auto& prop : customAttr.mSetProperties)
  4311. {
  4312. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4313. if (propDef->mName == "ReflectUser")
  4314. {
  4315. if (prop.mParam.mValue.IsConst())
  4316. {
  4317. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4318. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4319. }
  4320. }
  4321. }
  4322. // Check for Flags arg
  4323. if (customAttr.mCtorArgs.size() < 2)
  4324. continue;
  4325. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4326. if (constant == NULL)
  4327. continue;
  4328. if (constant->mTypeCode == BfTypeCode_Boolean)
  4329. continue;
  4330. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4331. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4332. }
  4333. }
  4334. }
  4335. return reflectKind;
  4336. };
  4337. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4338. {
  4339. ReflectKind reflectKind = ReflectKind_None;
  4340. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4341. if (customAttrs != NULL)
  4342. {
  4343. for (auto& attr : customAttrs->mAttributes)
  4344. {
  4345. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4346. }
  4347. }
  4348. return reflectKind;
  4349. };
  4350. //
  4351. {
  4352. auto checkTypeInstance = typeInstance;
  4353. while (checkTypeInstance != NULL)
  4354. {
  4355. if (checkTypeInstance->mCustomAttributes != NULL)
  4356. {
  4357. auto checkReflectKind = ReflectKind_None;
  4358. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4359. {
  4360. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4361. {
  4362. if (customAttr.mCtorArgs.size() > 0)
  4363. {
  4364. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4365. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4366. }
  4367. else
  4368. {
  4369. checkReflectKind = ReflectKind_All;
  4370. }
  4371. }
  4372. else
  4373. {
  4374. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4375. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4376. }
  4377. }
  4378. if ((checkTypeInstance == typeInstance) ||
  4379. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4380. {
  4381. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4382. }
  4383. }
  4384. checkTypeInstance = GetOuterType(checkTypeInstance);
  4385. }
  4386. }
  4387. // Fields
  4388. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4389. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4390. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4391. {
  4392. if (customAttributes == NULL)
  4393. return -1;
  4394. Array<BfCustomAttribute*> reflectAttributes;
  4395. for (auto& attr : customAttributes->mAttributes)
  4396. {
  4397. bool wantAttribute = false;
  4398. if (attr.mType->mCustomAttributes != NULL)
  4399. {
  4400. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4401. if (usageAttribute != NULL)
  4402. {
  4403. // Check for Flags arg
  4404. if (usageAttribute->mCtorArgs.size() < 2)
  4405. continue;
  4406. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4407. if (constant == NULL)
  4408. continue;
  4409. if (constant->mTypeCode == BfTypeCode_Boolean)
  4410. continue;
  4411. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4412. wantAttribute = true;
  4413. }
  4414. }
  4415. if ((wantAttribute) && (attr.mType->mIsReified))
  4416. {
  4417. reflectAttributes.Add(&attr);
  4418. }
  4419. }
  4420. if (reflectAttributes.size() == 0)
  4421. return -1;
  4422. #define PUSH_INT8(val) data.push_back((uint8)val)
  4423. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4424. #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); }
  4425. #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); \
  4426. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4427. SizedArray<uint8, 16> data;
  4428. int customAttrIdx = (int)customAttrs.size();
  4429. data.push_back((uint8)reflectAttributes.size());
  4430. for (auto attr : reflectAttributes)
  4431. {
  4432. // Size prefix
  4433. int sizeIdx = (int)data.size();
  4434. PUSH_INT16(0); // mSize
  4435. PUSH_INT32(attr->mType->mTypeId); // mType
  4436. PUSH_INT16(attr->mCtor->mIdx);
  4437. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4438. int argIdx = 0;
  4439. for (auto arg : attr->mCtorArgs)
  4440. {
  4441. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4442. bool handled = false;
  4443. if (constant != NULL)
  4444. {
  4445. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4446. if (argType->IsObject())
  4447. {
  4448. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4449. int stringId = constant->mInt32;
  4450. int* orderedIdPtr;
  4451. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4452. {
  4453. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4454. }
  4455. GetStringObjectValue(stringId);
  4456. PUSH_INT8(0xFF); // String
  4457. PUSH_INT32(*orderedIdPtr);
  4458. continue;
  4459. }
  4460. PUSH_INT8(constant->mTypeCode);
  4461. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4462. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4463. (constant->mTypeCode == BfTypeCode_Double))
  4464. {
  4465. PUSH_INT64(constant->mInt64);
  4466. }
  4467. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4468. (constant->mTypeCode == BfTypeCode_UInt32))
  4469. {
  4470. PUSH_INT32(constant->mInt32);
  4471. }
  4472. else if (constant->mTypeCode == BfTypeCode_Single)
  4473. {
  4474. float val = (float)constant->mDouble;
  4475. PUSH_INT32(*(int*)&val);
  4476. }
  4477. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4478. (constant->mTypeCode == BfTypeCode_UInt16))
  4479. {
  4480. PUSH_INT16(constant->mInt16);
  4481. }
  4482. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4483. (constant->mTypeCode == BfTypeCode_UInt8))
  4484. {
  4485. PUSH_INT8(constant->mInt8);
  4486. }
  4487. else if (constant->mTypeCode == BfTypeCode_Object)
  4488. {
  4489. BF_FATAL("Unhandled");
  4490. }
  4491. else
  4492. {
  4493. BF_FATAL("Unhandled");
  4494. }
  4495. }
  4496. else if (!handled)
  4497. {
  4498. BF_FATAL("Unhandled");
  4499. }
  4500. argIdx++;
  4501. }
  4502. int size = (int)data.size() - sizeIdx;
  4503. *((uint16*)&data[sizeIdx]) = size;
  4504. }
  4505. #undef PUSH_INT8
  4506. #undef PUSH_INT16
  4507. #undef PUSH_INT32
  4508. SizedArray<BfIRValue, 16> dataValues;
  4509. for (uint8 val : data)
  4510. dataValues.push_back(GetConstValue8(val));
  4511. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4512. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4513. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4514. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4515. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4516. customAttrs.push_back(customAttrArrayPtr);
  4517. return customAttrIdx;
  4518. };
  4519. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4520. SizedArray<int, 16> reflectFieldIndices;
  4521. for (int pass = 0; pass < 2; pass++)
  4522. {
  4523. bool skippedField = false;
  4524. reflectFieldIndices.clear();
  4525. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4526. {
  4527. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4528. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4529. if (fieldDef == NULL)
  4530. continue;
  4531. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4532. bool includeField = reflectIncludeAllFields;
  4533. if (fieldInstance->mCustomAttributes != NULL)
  4534. {
  4535. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4536. {
  4537. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4538. {
  4539. includeField = true;
  4540. }
  4541. else
  4542. {
  4543. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4544. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4545. }
  4546. }
  4547. }
  4548. if ((fieldReflectKind & ReflectKind_User) != 0)
  4549. includeField = true;
  4550. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4551. includeField = true;
  4552. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4553. includeField = true;
  4554. includeField |= forceReflectFields;
  4555. if (!includeField)
  4556. {
  4557. skippedField = true;
  4558. continue;
  4559. }
  4560. reflectFieldIndices.Add(fieldIdx);
  4561. }
  4562. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4563. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4564. // possible because we write out a SplatData structure containing just TypeIds in that case
  4565. if (pass == 0)
  4566. {
  4567. if (!typeInstance->IsSplattable())
  4568. break;
  4569. if (!skippedField)
  4570. break;
  4571. if (reflectFieldIndices.size() == 0)
  4572. break;
  4573. }
  4574. }
  4575. SizedArray<BfIRValue, 16> fieldTypes;
  4576. enum FieldFlags
  4577. {
  4578. FieldFlags_Protected = 3,
  4579. FieldFlags_Public = 6,
  4580. FieldFlags_Static = 0x10,
  4581. FieldFlags_Const = 0x40,
  4582. FieldFlags_SpecialName = 0x80,
  4583. FieldFlags_EnumPayload = 0x100,
  4584. FieldFlags_EnumDiscriminator = 0x200
  4585. };
  4586. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4587. {
  4588. BfType* payloadType = typeInstance->GetUnionInnerType();
  4589. if (!payloadType->IsValuelessType())
  4590. {
  4591. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4592. SizedArray<BfIRValue, 8> payloadFieldVals =
  4593. {
  4594. emptyValueType,
  4595. payloadNameConst, // mName
  4596. GetConstValue(0, longType), // mConstValue
  4597. GetConstValue(0, intType), // mDataOffset
  4598. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4599. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4600. GetConstValue(-1, intType), // mCustomAttributesIdx
  4601. };
  4602. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4603. fieldTypes.push_back(payloadFieldData);
  4604. }
  4605. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4606. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4607. SizedArray<BfIRValue, 8> dscrFieldVals =
  4608. {
  4609. emptyValueType,
  4610. dscrNameConst, // mName
  4611. GetConstValue(0, longType), // mConstValue
  4612. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4613. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4614. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4615. GetConstValue(-1, intType), // mCustomAttributesIdx
  4616. };
  4617. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4618. fieldTypes.push_back(dscrFieldData);
  4619. }
  4620. for (auto fieldIdx : reflectFieldIndices)
  4621. {
  4622. if (!needsTypeData)
  4623. break;
  4624. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4625. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4626. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4627. int typeId = 0;
  4628. auto fieldType = fieldInstance->GetResolvedType();
  4629. if (fieldType->IsGenericParam())
  4630. {
  4631. //TODO:
  4632. }
  4633. else
  4634. typeId = fieldType->mTypeId;
  4635. FieldFlags fieldFlags = (FieldFlags)0;
  4636. if (fieldDef->mProtection == BfProtection_Protected)
  4637. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4638. if (fieldDef->mProtection == BfProtection_Public)
  4639. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4640. if (fieldDef->mIsStatic)
  4641. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4642. if (fieldDef->mIsConst)
  4643. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4644. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4645. BfIRValue constValue = GetConstValue(0, longType);
  4646. if (fieldInstance->GetFieldDef()->mIsConst)
  4647. {
  4648. if (fieldInstance->mConstIdx != -1)
  4649. {
  4650. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4651. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4652. }
  4653. }
  4654. SizedArray<BfIRValue, 8> fieldVals =
  4655. {
  4656. emptyValueType,
  4657. fieldNameConst, // mName
  4658. constValue, // mConstValue
  4659. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4660. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4661. GetConstValue(fieldFlags, shortType), // mFlags
  4662. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4663. };
  4664. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4665. fieldTypes.push_back(fieldData);
  4666. }
  4667. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4668. BfIRValue fieldDataPtr;
  4669. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4670. if (fieldTypes.size() == 0)
  4671. {
  4672. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4673. {
  4674. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4675. SizedArray<BfIRValue, 3> splatTypes;
  4676. SizedArray<BfIRValue, 3> splatOffsets;
  4677. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4678. {
  4679. auto checkTypeInstance = checkType->ToTypeInstance();
  4680. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4681. PopulateType(checkTypeInstance);
  4682. if (checkType->IsStruct())
  4683. {
  4684. int dataEnd = offset;
  4685. if (checkTypeInstance->mBaseType != NULL)
  4686. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4687. if (checkTypeInstance->mIsUnion)
  4688. {
  4689. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4690. _CheckSplat(unionInnerType, offset);
  4691. }
  4692. else
  4693. {
  4694. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4695. {
  4696. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4697. if (fieldInstance->mDataIdx >= 0)
  4698. {
  4699. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4700. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4701. }
  4702. }
  4703. }
  4704. if (checkTypeInstance->IsEnum())
  4705. {
  4706. // Add discriminator
  4707. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4708. if (!checkTypeInstance->mIsPacked)
  4709. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4710. _CheckSplat(dscrType, dataEnd);
  4711. }
  4712. }
  4713. else if (checkType->IsMethodRef())
  4714. {
  4715. // auto methodRefType = (BfMethodRefType*)checkType;
  4716. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4717. // {
  4718. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4719. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4720. // else
  4721. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4722. // }
  4723. }
  4724. else if (!checkType->IsValuelessType())
  4725. {
  4726. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4727. splatOffsets.Add(GetConstValue(offset, intType));
  4728. }
  4729. };
  4730. _CheckSplat(type, 0);
  4731. while (splatTypes.size() < 3)
  4732. {
  4733. splatTypes.Add(GetConstValue(0, typeIdType));
  4734. splatOffsets.Add(GetConstValue(0, intType));
  4735. }
  4736. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4737. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4738. SizedArray<BfIRValue, 8> splatVals =
  4739. {
  4740. emptyValueType,
  4741. splatTypesConst,
  4742. splatOffsetsConst
  4743. };
  4744. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4745. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4746. fieldSplatData, typeDataName + ".splats");
  4747. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4748. }
  4749. else
  4750. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4751. }
  4752. else
  4753. {
  4754. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4755. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4756. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4757. fieldDataConst, "fields." + typeDataName);
  4758. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4759. }
  4760. /// Methods
  4761. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4762. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4763. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4764. SizedArray<BfIRValue, 16> methodTypes;
  4765. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4766. {
  4767. if (!needsTypeData)
  4768. break;
  4769. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4770. if (!methodInstanceGroup->IsImplemented())
  4771. continue;
  4772. auto methodDef = typeDef->mMethods[methodIdx];
  4773. if (methodDef->mNoReflect)
  4774. continue;
  4775. auto defaultMethod = methodInstanceGroup->mDefault;
  4776. if (defaultMethod == NULL)
  4777. continue;
  4778. if (defaultMethod->mIsUnspecialized)
  4779. continue;
  4780. if (!defaultMethod->mIsReified)
  4781. continue;
  4782. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4783. continue;
  4784. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4785. continue;
  4786. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4787. bool includeMethod = reflectIncludeAllMethods;
  4788. BfCustomAttributes* methodCustomAttributes = NULL;
  4789. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4790. {
  4791. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4792. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4793. {
  4794. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4795. {
  4796. includeMethod = true;
  4797. }
  4798. else
  4799. {
  4800. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4801. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4802. }
  4803. }
  4804. }
  4805. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4806. continue;
  4807. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4808. {
  4809. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4810. {
  4811. if (paramDecl->mAttributes != NULL)
  4812. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4813. }
  4814. if (methodDeclaration->mReturnAttributes != NULL)
  4815. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4816. }
  4817. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4818. includeMethod = true;
  4819. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4820. includeMethod = true;
  4821. if (!includeMethod)
  4822. continue;
  4823. BfModuleMethodInstance moduleMethodInstance;
  4824. BfIRValue funcVal = voidPtrNull;
  4825. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4826. (!typeInstance->IsUnspecializedType()) &&
  4827. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4828. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4829. (!methodDef->mIsAbstract) &&
  4830. (methodDef->mGenericParams.size() == 0))
  4831. {
  4832. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4833. if (moduleMethodInstance.mFunc)
  4834. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4835. }
  4836. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4837. enum MethodFlags
  4838. {
  4839. MethodFlags_Protected = 3,
  4840. MethodFlags_Public = 6,
  4841. MethodFlags_Static = 0x10,
  4842. MethodFlags_Virtual = 0x40,
  4843. MethodFlags_StdCall = 0x1000,
  4844. MethodFlags_FastCall = 0x2000,
  4845. MethodFlags_Mutating = 0x4000,
  4846. };
  4847. MethodFlags methodFlags = (MethodFlags)0;
  4848. if (methodDef->mProtection == BfProtection_Protected)
  4849. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4850. if (methodDef->mProtection == BfProtection_Public)
  4851. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4852. if (methodDef->mIsStatic)
  4853. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4854. if (methodDef->mIsVirtual)
  4855. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4856. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4857. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4858. if (methodDef->mIsMutating)
  4859. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4860. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4861. enum ParamFlags
  4862. {
  4863. ParamFlag_None = 0,
  4864. ParamFlag_Splat = 1,
  4865. ParamFlag_Implicit = 2,
  4866. };
  4867. SizedArray<BfIRValue, 8> paramVals;
  4868. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4869. {
  4870. String paramName = defaultMethod->GetParamName(paramIdx);
  4871. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4872. ParamFlags paramFlags = ParamFlag_None;
  4873. if (defaultMethod->GetParamIsSplat(paramIdx))
  4874. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4875. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4876. SizedArray<BfIRValue, 8> paramDataVals =
  4877. {
  4878. emptyValueType,
  4879. paramNameConst,
  4880. GetConstValue(paramType->mTypeId, typeIdType),
  4881. GetConstValue((int32)paramFlags, shortType),
  4882. GetConstValue(customAttrIdx, intType) // defaultIdx
  4883. };
  4884. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4885. paramVals.Add(paramData);
  4886. }
  4887. BfIRValue paramsVal;
  4888. if (paramVals.size() > 0)
  4889. {
  4890. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4891. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4892. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4893. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4894. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4895. }
  4896. else
  4897. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4898. int vDataVal = -1;
  4899. if (defaultMethod->mVirtualTableIdx != -1)
  4900. {
  4901. int vDataIdx = -1;
  4902. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4903. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4904. {
  4905. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4906. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4907. if (extMethodIdx >= 0)
  4908. {
  4909. // Extension?
  4910. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4911. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4912. }
  4913. else
  4914. {
  4915. // Map this new virtual index back to the original index
  4916. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4917. }
  4918. }
  4919. else
  4920. {
  4921. vDataIdx += defaultMethod->mVirtualTableIdx;
  4922. }
  4923. if (vDataVal == -1)
  4924. vDataVal = vDataIdx * mSystem->mPtrSize;
  4925. }
  4926. SizedArray<BfIRValue, 8> methodDataVals =
  4927. {
  4928. emptyValueType,
  4929. methodNameConst, // mName
  4930. funcVal, // mFuncPtr
  4931. paramsVal,
  4932. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4933. GetConstValue((int)paramVals.size(), shortType),
  4934. GetConstValue(methodFlags, shortType),
  4935. GetConstValue(vDataVal, intType),
  4936. GetConstValue(-1, intType),
  4937. };
  4938. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4939. methodTypes.push_back(methodData);
  4940. }
  4941. BfIRValue methodDataPtr;
  4942. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4943. if (methodTypes.size() == 0)
  4944. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4945. else
  4946. {
  4947. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4948. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4949. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4950. methodDataConst, "methods." + typeDataName);
  4951. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4952. }
  4953. /////
  4954. int underlyingType = 0;
  4955. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4956. {
  4957. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4958. }
  4959. int outerTypeId = 0;
  4960. auto outerType = GetOuterType(typeInstance);
  4961. if (outerType != NULL)
  4962. outerTypeId = outerType->mTypeId;
  4963. BfIRValue customAttrDataPtr;
  4964. if (customAttrs.size() > 0)
  4965. {
  4966. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  4967. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  4968. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  4969. customAttrsConst, "customAttrs." + typeDataName);
  4970. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  4971. }
  4972. else
  4973. {
  4974. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  4975. }
  4976. SizedArray<BfIRValue, 32> typeDataVals =
  4977. {
  4978. typeData,
  4979. castedClassVData, // mTypeClassVData
  4980. typeNameConst, // mName
  4981. namespaceConst, // mNamespace
  4982. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  4983. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  4984. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  4985. GetConstValue(baseTypeId, typeIdType), // mBaseType
  4986. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  4987. GetConstValue(outerTypeId, typeIdType), // mOuterType
  4988. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  4989. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  4990. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  4991. GetConstValue(0, byteType), // mInterfaceCount
  4992. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  4993. GetConstValue(0, shortType), // mPropertyDataCount
  4994. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  4995. GetConstValue(0, shortType), // mConstructorDataCount
  4996. voidPtrNull, // mInterfaceDataPtr
  4997. methodDataPtr, // mMethodDataPtr
  4998. voidPtrNull, // mPropertyDataPtr
  4999. fieldDataPtr, // mFieldDataPtr
  5000. voidPtrNull, // mConstructorDataPtr
  5001. customAttrDataPtr, // mCustomAttrDataPtr
  5002. };
  5003. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5004. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5005. if (!needsTypeData)
  5006. {
  5007. // No need for anything beyond typeInstanceData
  5008. }
  5009. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5010. {
  5011. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5012. SizedArray<BfIRValue, 4> unspecializedData =
  5013. {
  5014. typeInstanceData,
  5015. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5016. };
  5017. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5018. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5019. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5020. }
  5021. else if (typeInstance->IsGenericTypeInstance())
  5022. {
  5023. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5024. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5025. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5026. SizedArray<BfIRValue, 4> resolvedTypes;
  5027. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5028. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5029. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5030. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5031. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5032. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5033. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5034. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5035. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5036. SizedArray<BfIRValue, 3> specGenericData =
  5037. {
  5038. typeInstanceData,
  5039. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5040. resovledTypesPtr, // mFieldDataPtr
  5041. };
  5042. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5043. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5044. if (typeInstance->IsArray())
  5045. {
  5046. auto arrayType = (BfArrayType*)typeInstance;
  5047. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5048. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5049. SizedArray<BfIRValue, 4> arrayData =
  5050. {
  5051. typeInstanceData,
  5052. GetConstValue(elementType->mSize, intType), // mElementSize
  5053. GetConstValue(1, byteType), // mRank
  5054. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5055. };
  5056. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5057. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5058. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5059. }
  5060. }
  5061. BfIRValue typeDataVar;
  5062. if (needsTypeData)
  5063. {
  5064. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5065. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5066. if (mBfIRBuilder->DbgHasInfo())
  5067. {
  5068. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5069. }
  5070. }
  5071. else
  5072. {
  5073. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5074. }
  5075. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5076. mTypeDataRefs[typeInstance] = typeDataVar;
  5077. if (classVDataVar)
  5078. {
  5079. BF_ASSERT(!classVDataName.IsEmpty());
  5080. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5081. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5082. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5083. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5084. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5085. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5086. else
  5087. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5088. if (mBfIRBuilder->DbgHasInfo())
  5089. {
  5090. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5091. BfType* voidPtrType = CreatePointerType(voidType);
  5092. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5093. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5094. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5095. }
  5096. }
  5097. return typeDataVar;
  5098. }
  5099. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5100. {
  5101. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5102. return value;
  5103. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5104. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5105. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5106. }
  5107. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5108. {
  5109. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5110. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5111. // When we access classes with static constructors FROM a static constructor,
  5112. // we call that other class's static constructor first. Recursion cannot occur, since
  5113. // we simply ignore subsequent attempts to re-enter the constructor
  5114. if (!typeInstance->mHasStaticInitMethod)
  5115. return;
  5116. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5117. return;
  5118. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5119. return;
  5120. auto checkTypeDef = typeInstance->mTypeDef;
  5121. checkTypeDef->PopulateMemberSets();
  5122. BfMethodDef* nextMethodDef = NULL;
  5123. BfMemberSetEntry* entry;
  5124. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5125. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5126. while (nextMethodDef != NULL)
  5127. {
  5128. auto checkMethod = nextMethodDef;
  5129. nextMethodDef = nextMethodDef->mNextWithSameName;
  5130. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5131. if (methodModule)
  5132. {
  5133. auto methodInstance = methodModule.mMethodInstance;
  5134. if ((methodInstance != NULL) &&
  5135. (methodInstance->mMethodDef->mIsStatic) &&
  5136. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5137. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5138. {
  5139. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5140. break;
  5141. }
  5142. }
  5143. }
  5144. }
  5145. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5146. {
  5147. auto methodOwner = methodInstance->GetOwner();
  5148. auto methodDef = methodInstance->mMethodDef;
  5149. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5150. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5151. if (!hasExternSpecifier)
  5152. return BfIRFunction();
  5153. if (methodInstance->GetCustomAttributes() == NULL)
  5154. return BfIRFunction();
  5155. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5156. {
  5157. String typeName = TypeToString(customAttribute.mType);
  5158. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5159. {
  5160. methodInstance->mIsIntrinsic = true;
  5161. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5162. String error;
  5163. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5164. {
  5165. int stringId = constant->mInt32;
  5166. auto entry = mContext->mStringObjectIdMap[stringId];
  5167. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5168. if (intrinId != -1)
  5169. {
  5170. if (intrinId == BfIRIntrinsic_Malloc)
  5171. {
  5172. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5173. }
  5174. else if (intrinId == BfIRIntrinsic_Free)
  5175. {
  5176. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5177. }
  5178. SizedArray<BfIRType, 2> paramTypes;
  5179. for (auto& param : methodInstance->mParams)
  5180. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5181. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5182. }
  5183. else if (reportFailure)
  5184. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5185. }
  5186. else if (reportFailure)
  5187. error = "Intrinsic name must be a constant string";
  5188. if (reportFailure)
  5189. {
  5190. BfAstNode* ref = methodDeclaration->mAttributes;
  5191. Fail(error, ref);
  5192. }
  5193. }
  5194. }
  5195. return BfIRFunction();
  5196. }
  5197. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5198. {
  5199. if (mBfIRBuilder->mIgnoreWrites)
  5200. return mBfIRBuilder->GetFakeFunction();
  5201. if (!mBuiltInFuncs[(int)funcTypeId])
  5202. {
  5203. SizedArray<BfIRType, 4> paramTypes;
  5204. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5205. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5206. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5207. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5208. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5209. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5210. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5211. BfIRFunctionType funcType;
  5212. BfIRFunction func;
  5213. switch (funcTypeId)
  5214. {
  5215. case BfBuiltInFuncType_PrintF:
  5216. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5217. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5218. break;
  5219. case BfBuiltInFuncType_Malloc:
  5220. {
  5221. if (mCompiler->mOptions.mDebugAlloc)
  5222. {
  5223. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5224. }
  5225. else
  5226. {
  5227. String funcName = mCompiler->mOptions.mMallocLinkName;
  5228. if (funcName.IsEmpty())
  5229. funcName = "malloc";
  5230. func = mBfIRBuilder->GetFunction(funcName);
  5231. if (!func)
  5232. {
  5233. paramTypes.clear();
  5234. paramTypes.push_back(intType);
  5235. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5236. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5237. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5238. }
  5239. }
  5240. }
  5241. break;
  5242. case BfBuiltInFuncType_Free:
  5243. {
  5244. if (mCompiler->mOptions.mDebugAlloc)
  5245. {
  5246. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5247. }
  5248. else
  5249. {
  5250. String funcName = mCompiler->mOptions.mFreeLinkName;
  5251. if (funcName.IsEmpty())
  5252. funcName = "free";
  5253. func = mBfIRBuilder->GetFunction(funcName);
  5254. if (!func)
  5255. {
  5256. paramTypes.clear();
  5257. paramTypes.push_back(nullPtrType);
  5258. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5259. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5260. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5261. }
  5262. }
  5263. }
  5264. break;
  5265. case BfBuiltInFuncType_LoadSharedLibraries:
  5266. paramTypes.clear();
  5267. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5268. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5269. break;
  5270. }
  5271. mBuiltInFuncs[(int)funcTypeId] = func;
  5272. return func;
  5273. }
  5274. return mBuiltInFuncs[(int)funcTypeId];
  5275. }
  5276. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5277. {
  5278. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5279. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5280. BfAutoComplete* bfAutocomplete = NULL;
  5281. if (mCompiler->mResolvePassData != NULL)
  5282. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5283. if (bfAutocomplete != NULL)
  5284. {
  5285. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5286. {
  5287. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5288. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5289. {
  5290. String filter = nameNode->ToString();
  5291. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5292. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5293. if (nameIdx != 0)
  5294. {
  5295. for (auto checkGenericParam : genericParamDefs)
  5296. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5297. }
  5298. }
  5299. }
  5300. }
  5301. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5302. {
  5303. if (bfAutocomplete != NULL)
  5304. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5305. //TODO: Constraints may refer to other generic params (of either type or method)
  5306. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5307. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5308. if (constraintType != NULL)
  5309. {
  5310. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5311. {
  5312. bool isValidTypeCode = false;
  5313. BfTypeCode typeCode = BfTypeCode_None;
  5314. if (constraintType->IsTypedPrimitive())
  5315. {
  5316. auto underlyingType = constraintType->GetUnderlyingType();
  5317. if (underlyingType->IsPrimitiveType())
  5318. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5319. }
  5320. if (constraintType->IsPrimitiveType())
  5321. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5322. switch (typeCode)
  5323. {
  5324. case BfTypeCode_Int8:
  5325. case BfTypeCode_UInt8:
  5326. case BfTypeCode_Int16:
  5327. case BfTypeCode_UInt16:
  5328. case BfTypeCode_Int32:
  5329. case BfTypeCode_UInt32:
  5330. case BfTypeCode_Int64:
  5331. case BfTypeCode_UInt64:
  5332. case BfTypeCode_IntPtr:
  5333. case BfTypeCode_UIntPtr:
  5334. case BfTypeCode_IntUnknown:
  5335. case BfTypeCode_UIntUnknown:
  5336. case BfTypeCode_Single:
  5337. case BfTypeCode_Double:
  5338. case BfTypeCode_Char8:
  5339. case BfTypeCode_Char16:
  5340. case BfTypeCode_Char32:
  5341. isValidTypeCode = true;
  5342. break;
  5343. }
  5344. if (isValidTypeCode)
  5345. {
  5346. genericParamInstance->mTypeConstraint = constraintType;
  5347. }
  5348. else
  5349. {
  5350. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5351. }
  5352. }
  5353. else
  5354. {
  5355. if (constraintType->IsPrimitiveType())
  5356. {
  5357. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5358. continue;
  5359. }
  5360. if (constraintType->IsArray())
  5361. {
  5362. 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);
  5363. continue;
  5364. }
  5365. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5366. {
  5367. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5368. continue;
  5369. }
  5370. if (constraintType->IsInterface())
  5371. {
  5372. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5373. }
  5374. else
  5375. {
  5376. auto constraintTypeInst = constraintType->ToTypeInstance();
  5377. if (genericParamInstance->mTypeConstraint != NULL)
  5378. {
  5379. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5380. {
  5381. // Allow more specific type
  5382. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5383. }
  5384. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5385. {
  5386. // Silently ignore less-specific type
  5387. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5388. {
  5389. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5390. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5391. }
  5392. }
  5393. else
  5394. {
  5395. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5396. return;
  5397. }
  5398. }
  5399. else
  5400. genericParamInstance->mTypeConstraint = constraintType;
  5401. }
  5402. }
  5403. }
  5404. }
  5405. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5406. (genericParamInstance->mTypeConstraint == NULL))
  5407. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5408. }
  5409. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5410. {
  5411. if (genericParamSource.mMethodInstance != NULL)
  5412. {
  5413. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5414. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5415. return MethodToString(methodInst);
  5416. }
  5417. else
  5418. {
  5419. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5420. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5421. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5422. return TypeToString(typeInst);
  5423. }
  5424. }
  5425. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5426. {
  5427. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5428. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5429. BfType* origCheckArgType = checkArgType;
  5430. if (origCheckArgType->IsRef())
  5431. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5432. bool argMayBeReferenceType = false;
  5433. int checkGenericParamFlags = 0;
  5434. if (checkArgType->IsGenericParam())
  5435. {
  5436. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5437. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5438. if (checkGenericParamInst->mTypeConstraint != NULL)
  5439. checkArgType = checkGenericParamInst->mTypeConstraint;
  5440. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5441. {
  5442. argMayBeReferenceType = false;
  5443. }
  5444. else
  5445. {
  5446. argMayBeReferenceType = true;
  5447. }
  5448. }
  5449. if (checkArgType->IsObjectOrInterface())
  5450. argMayBeReferenceType = true;
  5451. BfTypeInstance* typeConstraintInst = NULL;
  5452. if (genericParamInst->mTypeConstraint != NULL)
  5453. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5454. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5455. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5456. {
  5457. if (!ignoreErrors)
  5458. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5459. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5460. return false;
  5461. }
  5462. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5463. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5464. {
  5465. if (!ignoreErrors)
  5466. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5467. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5468. return false;
  5469. }
  5470. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5471. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5472. {
  5473. if (!ignoreErrors)
  5474. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5475. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5476. return false;
  5477. }
  5478. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5479. {
  5480. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5481. {
  5482. if (!ignoreErrors)
  5483. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5484. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5485. return false;
  5486. }
  5487. }
  5488. else
  5489. {
  5490. if (checkArgType->IsConstExprValue())
  5491. {
  5492. if (!ignoreErrors)
  5493. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5494. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5495. return false;
  5496. }
  5497. }
  5498. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5499. return true;
  5500. if (checkArgType->IsPointer())
  5501. {
  5502. auto ptrType = (BfPointerType*)checkArgType;
  5503. checkArgType = ptrType->mElementType;
  5504. }
  5505. if (genericParamInst->mTypeConstraint != NULL)
  5506. {
  5507. bool constraintMatched = false;
  5508. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5509. {
  5510. if (checkArgType->IsConstExprValue())
  5511. {
  5512. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5513. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5514. {
  5515. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5516. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5517. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5518. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5519. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5520. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5521. {
  5522. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5523. {
  5524. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5525. {
  5526. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5527. {
  5528. if (!ignoreErrors)
  5529. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5530. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5531. return false;
  5532. }
  5533. }
  5534. else
  5535. {
  5536. if (!ignoreErrors)
  5537. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5538. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5539. return false;
  5540. }
  5541. }
  5542. else
  5543. {
  5544. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5545. {
  5546. char valStr[64];
  5547. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5548. if (!ignoreErrors)
  5549. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5550. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5551. return false;
  5552. }
  5553. }
  5554. }
  5555. }
  5556. }
  5557. }
  5558. else
  5559. {
  5560. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5561. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5562. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5563. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5564. {
  5565. auto methodRefType = (BfMethodRefType*)checkArgType;
  5566. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5567. BfExprEvaluator exprEvaluator(this);
  5568. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5569. constraintMatched = true;
  5570. }
  5571. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5572. {
  5573. constraintMatched = true;
  5574. }
  5575. else if (origCheckArgType->IsWrappableType())
  5576. {
  5577. if (origCheckArgType->IsSizedArray())
  5578. {
  5579. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5580. if (convCheckConstraint->IsGenericTypeInstance())
  5581. {
  5582. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5583. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5584. {
  5585. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5586. {
  5587. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5588. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5589. constraintMatched = true;
  5590. }
  5591. }
  5592. }
  5593. }
  5594. if (!constraintMatched)
  5595. {
  5596. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5597. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5598. constraintMatched = true;
  5599. }
  5600. }
  5601. if (!constraintMatched)
  5602. {
  5603. if (!ignoreErrors)
  5604. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5605. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5606. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5607. return false;
  5608. }
  5609. }
  5610. }
  5611. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5612. {
  5613. PopulateType(origCheckArgType);
  5614. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5615. if (checkTypeInst->mTypeDef->mIsConcrete)
  5616. {
  5617. if (!ignoreErrors)
  5618. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5619. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5620. return false;
  5621. }
  5622. }
  5623. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5624. {
  5625. BfType* convCheckConstraint = checkConstraint;
  5626. if (convCheckConstraint->IsUnspecializedType())
  5627. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5628. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5629. bool implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5630. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5631. {
  5632. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5633. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5634. implementsInterface = true;
  5635. }
  5636. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5637. {
  5638. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5639. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5640. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5641. implementsInterface = true;
  5642. }
  5643. if (!implementsInterface)
  5644. {
  5645. if (!ignoreErrors)
  5646. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5647. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5648. return false;
  5649. }
  5650. }
  5651. return true;
  5652. }
  5653. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5654. {
  5655. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5656. {
  5657. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5658. return genericParamType;
  5659. }
  5660. auto genericParamType = new BfGenericParamType();
  5661. genericParamType->mContext = mContext;
  5662. genericParamType->mGenericParamKind = paramKind;
  5663. genericParamType->mGenericParamIdx = paramIdx;
  5664. PopulateType(genericParamType);
  5665. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5666. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5667. BfResolvedTypeSet::LookupContext lookupCtx;
  5668. lookupCtx.mModule = this;
  5669. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5670. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5671. BF_ASSERT(inserted);
  5672. typeEntry->mValue = genericParamType;
  5673. return genericParamType;
  5674. }
  5675. static int sValueFromExprIdx = 0;
  5676. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5677. {
  5678. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5679. if ((result) && (!ignoreNullable))
  5680. {
  5681. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5682. //TODO: Make this work, needed for 'void' and such
  5683. BfType* nullableType = NULL;
  5684. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5685. {
  5686. BfTypeVector typeVec;
  5687. typeVec.push_back(result.mType);
  5688. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5689. BF_ASSERT(nullableType != NULL);
  5690. }
  5691. // Go back to start and do any setup we need
  5692. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5693. BfTypedValue nullableTypedValue;
  5694. if (nullableType != NULL)
  5695. {
  5696. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5697. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5698. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5699. }
  5700. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5701. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5702. mBfIRBuilder->SetInsertPoint(notNullBB);
  5703. result = LoadValue(result);
  5704. if (nullableTypedValue)
  5705. {
  5706. auto elementType = nullableType->GetUnderlyingType();
  5707. if (elementType->IsValuelessType())
  5708. {
  5709. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5710. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5711. result = nullableTypedValue;
  5712. }
  5713. else
  5714. {
  5715. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5716. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5717. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5718. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5719. result = nullableTypedValue;
  5720. }
  5721. }
  5722. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5723. AddBasicBlock(pendingNullCond->mDoneBB);
  5724. if (nullableType == NULL)
  5725. {
  5726. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5727. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5728. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5729. result.mValue = phi;
  5730. }
  5731. }
  5732. else
  5733. {
  5734. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5735. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5736. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5737. AddBasicBlock(pendingNullCond->mDoneBB);
  5738. }
  5739. delete mCurMethodState->mPendingNullConditional;
  5740. mCurMethodState->mPendingNullConditional = NULL;
  5741. return result;
  5742. }
  5743. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5744. {
  5745. BfScopeData newScope;
  5746. newScope.mOuterIsConditional = true;
  5747. newScope.mAllowTargeting = false;
  5748. mCurMethodState->AddScope(&newScope);
  5749. NewScopeState();
  5750. exprEvaluator.mBfEvalExprFlags = flags;
  5751. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5752. RestoreScopeState();
  5753. }
  5754. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5755. {
  5756. //
  5757. {
  5758. BP_ZONE("CreateValueFromExpression:CheckStack");
  5759. StackHelper stackHelper;
  5760. if (!stackHelper.CanStackExpand(64 * 1024))
  5761. {
  5762. BfTypedValue result;
  5763. if (!stackHelper.Execute([&]()
  5764. {
  5765. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5766. }))
  5767. {
  5768. Fail("Expression too complex to compile", expr);
  5769. }
  5770. return result;
  5771. }
  5772. }
  5773. BP_ZONE("BfModule::CreateValueFromExpression");
  5774. if (outOrigType != NULL)
  5775. *outOrigType = NULL;
  5776. exprEvaluator.mExpectingType = wantTypeRef;
  5777. exprEvaluator.mBfEvalExprFlags = flags;
  5778. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5779. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5780. {
  5781. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5782. }
  5783. else
  5784. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5785. if (!exprEvaluator.mResult)
  5786. {
  5787. if (!mCompiler->mPassInstance->HasFailed())
  5788. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5789. return BfTypedValue();
  5790. }
  5791. auto typedVal = exprEvaluator.mResult;
  5792. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5793. {
  5794. BF_ASSERT(typedVal.mType->IsGenericParam());
  5795. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5796. bool handled = false;
  5797. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5798. {
  5799. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5800. if (genericTypeConstraint != NULL)
  5801. {
  5802. auto primType = genericTypeConstraint->ToPrimitiveType();
  5803. if (primType != NULL)
  5804. {
  5805. BfTypedValue result;
  5806. result.mKind = BfTypedValueKind_Value;
  5807. result.mType = genericTypeConstraint;
  5808. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5809. typedVal = result;
  5810. handled = true;
  5811. }
  5812. }
  5813. }
  5814. if (!handled)
  5815. {
  5816. //Fail("Only const generic parameters can be used as values", expr);
  5817. AssertErrorState();
  5818. return BfTypedValue();
  5819. }
  5820. }
  5821. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5822. FixIntUnknown(typedVal);
  5823. exprEvaluator.CheckResultForReading(typedVal);
  5824. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5825. {
  5826. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5827. {
  5828. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5829. bool allowRef = false;
  5830. BfExpression* checkExpr = expr;
  5831. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5832. checkExpr = parenExpr->mExpression;
  5833. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5834. {
  5835. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5836. allowRef = true;
  5837. }
  5838. if (!allowRef)
  5839. typedVal = RemoveRef(typedVal);
  5840. }
  5841. }
  5842. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5843. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5844. if (wantTypeRef != NULL)
  5845. {
  5846. if (outOrigType != NULL)
  5847. *outOrigType = typedVal.mType;
  5848. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5849. {
  5850. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5851. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5852. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5853. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5854. if (!typedVal)
  5855. return typedVal;
  5856. }
  5857. //WTF- why did we have this?
  5858. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5859. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5860. if (exprEvaluator.mIsVolatileReference)
  5861. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5862. }
  5863. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5864. // typedVal = MakeAddressable(typedVal);
  5865. //typedVal = AggregateSplat(typedVal);
  5866. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5867. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5868. return typedVal;
  5869. }
  5870. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5871. {
  5872. BfExprEvaluator exprEvaluator(this);
  5873. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5874. }
  5875. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5876. {
  5877. BfExprEvaluator exprEvaluator(this);
  5878. exprEvaluator.Evaluate(expr);
  5879. if (!exprEvaluator.mResult)
  5880. {
  5881. Fail("Invalid expression type", expr);
  5882. return BfTypedValue();
  5883. }
  5884. if (!exprEvaluator.mResult.IsAddr())
  5885. {
  5886. Fail("Cannot assign to value", expr);
  5887. return BfTypedValue();
  5888. }
  5889. return exprEvaluator.mResult;
  5890. }
  5891. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5892. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5893. {
  5894. auto typeInstance = typedValue.mType->ToTypeInstance();
  5895. if (zeroMemory)
  5896. {
  5897. int zeroAlign = typedValue.mType->mAlign;
  5898. if (typeInstance != NULL)
  5899. zeroAlign = typeInstance->mInstAlign;
  5900. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5901. }
  5902. if (!typedValue.mType->IsObject())
  5903. {
  5904. return;
  5905. }
  5906. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5907. return; // Handled in heap alloc funcs
  5908. auto typeDef = typeInstance->mTypeDef;
  5909. mBfIRBuilder->PopulateType(typedValue.mType);
  5910. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5911. bool isAutocomplete = mCompiler->IsAutocomplete();
  5912. BfIRValue vDataRef;
  5913. if (!isAutocomplete)
  5914. {
  5915. vDataRef = GetClassVDataPtr(typeInstance);
  5916. }
  5917. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5918. auto ptrType = CreatePointerType(i8Type);
  5919. auto ptrPtrType = CreatePointerType(ptrType);
  5920. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5921. PopulateType(ptrType, BfPopulateType_Declaration);
  5922. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5923. if (!isAutocomplete)
  5924. {
  5925. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5926. {
  5927. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5928. SizedArray<BfIRValue, 4> llvmArgs;
  5929. llvmArgs.push_back(objectPtr);
  5930. llvmArgs.push_back(vDataRef);
  5931. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5932. if (objectStackInitMethod)
  5933. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5934. }
  5935. else
  5936. {
  5937. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  5938. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  5939. mBfIRBuilder->CreateStore(srcVal, destAddr);
  5940. }
  5941. }
  5942. }
  5943. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  5944. {
  5945. BfIRValue result;
  5946. BfType* ptrType;
  5947. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  5948. ptrType = type;
  5949. else
  5950. ptrType = CreatePointerType(type);
  5951. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  5952. {
  5953. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  5954. SizedArray<BfExpression*, 2> argExprs;
  5955. BfTypedValueExpression typedValueExpr;
  5956. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  5957. typedValueExpr.mRefNode = refNode;
  5958. argExprs.push_back(&typedValueExpr);
  5959. BfTypedValueExpression appendSizeValueExpr;
  5960. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  5961. appendSizeValueExpr.mRefNode = refNode;
  5962. argExprs.push_back(&appendSizeValueExpr);
  5963. BfExprEvaluator exprEvaluator(this);
  5964. BfTypedValue allocResult;
  5965. if (allocTarget.mScopedInvocationTarget != NULL)
  5966. {
  5967. SizedArray<BfTypeReference*, 2> genericArgs;
  5968. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  5969. allocResult = LoadValue(exprEvaluator.mResult);
  5970. }
  5971. else if (allocTarget.mCustomAllocator)
  5972. {
  5973. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  5974. if (customTypeInst != NULL)
  5975. {
  5976. BfTypedValueExpression typeValueExpr;
  5977. String allocMethodName = "Alloc";
  5978. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  5979. {
  5980. allocMethodName = "AllocTyped";
  5981. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  5982. auto typeRefVal = CreateTypeDataRef(type);
  5983. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  5984. typeValueExpr.mRefNode = refNode;
  5985. argExprs.Insert(0, &typeValueExpr);
  5986. }
  5987. if (HasMixin(customTypeInst, allocMethodName, 2))
  5988. {
  5989. BfSizedArray<BfExpression*> argExprArr;
  5990. argExprArr.mSize = (int)argExprs.size();
  5991. argExprArr.mVals = &argExprs[0];
  5992. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  5993. allocResult = exprEvaluator.GetResult();
  5994. }
  5995. else
  5996. {
  5997. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  5998. BfResolvedArgs argValues(&sizedArgExprs);
  5999. exprEvaluator.ResolveArgValues(argValues);
  6000. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6001. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6002. }
  6003. }
  6004. }
  6005. if (allocResult)
  6006. {
  6007. if (allocResult.mType->IsVoidPtr())
  6008. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6009. else
  6010. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6011. return result;
  6012. }
  6013. }
  6014. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6015. return result;
  6016. if (mCompiler->mOptions.mDebugAlloc)
  6017. {
  6018. BfIRValue allocData = GetDbgRawAllocData(type);
  6019. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6020. SizedArray<BfIRValue, 2> llvmArgs;
  6021. llvmArgs.push_back(sizeValue);
  6022. llvmArgs.push_back(allocData);
  6023. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6024. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6025. }
  6026. BfModuleMethodInstance moduleMethodInstance;
  6027. moduleMethodInstance = GetInternalMethod("Malloc");
  6028. SizedArray<BfIRValue, 1> llvmArgs;
  6029. llvmArgs.push_back(sizeValue);
  6030. auto func = moduleMethodInstance.mFunc;
  6031. if ((!func) || (func.IsFake()))
  6032. {
  6033. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6034. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6035. }
  6036. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6037. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6038. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6039. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6040. return result;
  6041. }
  6042. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6043. {
  6044. if (type->IsStruct())
  6045. {
  6046. auto typeInstance = type->ToTypeInstance();
  6047. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6048. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6049. }
  6050. else if (type->IsObjectOrInterface())
  6051. {
  6052. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6053. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6054. BF_ASSERT(moduleMethodInst.mFunc);
  6055. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6056. }
  6057. else
  6058. {
  6059. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6060. BfExprEvaluator exprEvaluator(this);
  6061. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6062. BfResolvedArg resolvedArg;
  6063. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6064. resolvedArgs.Add(resolvedArg);
  6065. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6066. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6067. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6068. BF_ASSERT(moduleMethodInst.mFunc);
  6069. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6070. }
  6071. return BfIRValue();
  6072. }
  6073. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6074. {
  6075. BfIRValue allocDataValue;
  6076. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6077. return allocDataValue;
  6078. BfIRValue markFuncPtr;
  6079. if (type->WantsGCMarking())
  6080. markFuncPtr = GetMarkFuncPtr(type);
  6081. else
  6082. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6083. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6084. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6085. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6086. if (typeInstance == NULL)
  6087. {
  6088. typeInstance = GetWrappedStructType(type);
  6089. if (typeInstance != NULL)
  6090. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6091. }
  6092. if (typeInstance != NULL)
  6093. PopulateType(typeInstance);
  6094. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6095. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6096. {
  6097. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6098. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6099. }
  6100. SizedArray<BfIRValue, 2> dataValues;
  6101. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6102. dataValues.Add(typeDataRef);
  6103. dataValues.Add(markFuncPtr);
  6104. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6105. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6106. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6107. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6108. return allocDataValue;
  6109. }
  6110. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6111. {
  6112. BP_ZONE("AllocFromType");
  6113. BfScopeData* scopeData = allocTarget.mScopeData;
  6114. auto typeInstance = type->ToTypeInstance();
  6115. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6116. typeInstance = mContext->mBfObjectType;
  6117. bool isHeapAlloc = scopeData == NULL;
  6118. bool isScopeAlloc = scopeData != NULL;
  6119. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6120. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6121. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6122. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6123. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6124. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6125. {
  6126. BfPointerType* ptrType = CreatePointerType(type);
  6127. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6128. return val;
  6129. }
  6130. if (typeInstance != NULL)
  6131. mBfIRBuilder->PopulateType(typeInstance);
  6132. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6133. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6134. {
  6135. if (arraySize)
  6136. {
  6137. if (isRawArrayAlloc)
  6138. {
  6139. BfPointerType* ptrType = CreatePointerType(type);
  6140. return GetDefaultValue(ptrType);
  6141. }
  6142. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6143. return GetDefaultValue(arrayType);
  6144. }
  6145. if (type->IsValueType())
  6146. {
  6147. BfPointerType* ptrType = CreatePointerType(type);
  6148. return GetDefaultValue(ptrType);
  6149. }
  6150. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6151. }
  6152. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6153. BfIRValue sizeValue;
  6154. BfIRType allocType = mBfIRBuilder->MapType(type);
  6155. int allocSize = type->mSize;
  6156. int allocAlign = type->mAlign;
  6157. if (typeInstance != NULL)
  6158. {
  6159. if (!mBfIRBuilder->mIgnoreWrites)
  6160. typeInstance->mHasBeenInstantiated = true;
  6161. allocSize = typeInstance->mInstSize;
  6162. allocAlign = typeInstance->mInstAlign;
  6163. //if (typeInstance->IsEnum())
  6164. //allocType = typeInstance->mIRType;
  6165. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6166. }
  6167. if (alignOverride != -1)
  6168. allocAlign = alignOverride;
  6169. // The "dynSize" cases:
  6170. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6171. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6172. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6173. // though we'd expect their stack space to be released
  6174. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6175. {
  6176. MarkDynStack(scopeData);
  6177. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6178. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6179. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6180. BfType* voidPtrType = CreatePointerType(voidType);
  6181. if (!mCurMethodState->mDynStackRevIdx)
  6182. {
  6183. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6184. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6185. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6186. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6187. mBfIRBuilder->ClearDebugLocation(storeInst);
  6188. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6189. }
  6190. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6191. auto bytePtrType = CreatePointerType(byteType);
  6192. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6193. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6194. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6195. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6196. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6197. mBfIRBuilder->ClearDebugLocation(storeInst);
  6198. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6199. mBfIRBuilder->ClearDebugLocation(storeInst);
  6200. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6201. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6202. if (IsTargetingBeefBackend())
  6203. {
  6204. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6205. // to ensure there isn't any register collision during looping is just to not allow it to
  6206. // bind to a register at all
  6207. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6208. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6209. }
  6210. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6211. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6212. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6213. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6214. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6215. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6216. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6217. mBfIRBuilder->AddBlock(verCheckBB);
  6218. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6219. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6220. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6221. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6222. mBfIRBuilder->AddBlock(resizeBB);
  6223. mBfIRBuilder->SetInsertPoint(resizeBB);
  6224. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6225. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6226. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6227. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6228. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6229. mBfIRBuilder->CreateBr(endBB);
  6230. mBfIRBuilder->AddBlock(endBB);
  6231. mBfIRBuilder->SetInsertPoint(endBB);
  6232. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6233. };
  6234. if (isScopeAlloc)
  6235. {
  6236. if (arraySize)
  6237. {
  6238. bool isConstantArraySize = arraySize.IsConst();
  6239. if (isRawArrayAlloc)
  6240. {
  6241. BfPointerType* ptrType = CreatePointerType(type);
  6242. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6243. {
  6244. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6245. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6246. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6247. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6248. }
  6249. else
  6250. {
  6251. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6252. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6253. if (!isDynAlloc)
  6254. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6255. else
  6256. {
  6257. MarkDynStack(scopeData);
  6258. SaveStackState(scopeData);
  6259. }
  6260. int typeSize = type->GetStride();
  6261. BfIRValue allocaInst;
  6262. BfIRValue result;
  6263. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6264. {
  6265. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6266. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6267. result = allocaInst;
  6268. }
  6269. else
  6270. {
  6271. if (typeInstance->IsStruct())
  6272. typeSize = typeInstance->GetInstStride();
  6273. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6274. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6275. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6276. auto ptrType = CreatePointerType(typeInstance);
  6277. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6278. if (!isDynAlloc)
  6279. mBfIRBuilder->ClearDebugLocation(result);
  6280. }
  6281. if (!isDynAlloc)
  6282. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6283. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6284. if (!isDynAlloc)
  6285. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6286. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6287. if (arraySize.IsConst())
  6288. {
  6289. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6290. if (constant->mInt64 == 0)
  6291. noDtorCall = true;
  6292. }
  6293. if (!noDtorCall)
  6294. {
  6295. bool isConstSize = arraySize.IsConst();
  6296. BfIRBlock clearBlock;
  6297. BfIRBlock contBlock;
  6298. if (!isConstSize)
  6299. {
  6300. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6301. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6302. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6303. mBfIRBuilder->AddBlock(clearBlock);
  6304. mBfIRBuilder->SetInsertPoint(clearBlock);
  6305. }
  6306. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6307. if (!isConstSize)
  6308. {
  6309. mBfIRBuilder->CreateBr(contBlock);
  6310. mBfIRBuilder->AddBlock(contBlock);
  6311. mBfIRBuilder->SetInsertPoint(contBlock);
  6312. }
  6313. }
  6314. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6315. return result;
  6316. }
  6317. }
  6318. else
  6319. {
  6320. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6321. {
  6322. // Generate and check new size
  6323. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6324. auto firstElementField = &arrayType->mFieldInstances.back();
  6325. int arrayClassSize = firstElementField->mDataOffset;
  6326. sizeValue = GetConstValue(arrayClassSize);
  6327. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6328. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6329. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6330. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6331. if (!noDtorCall)
  6332. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6333. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6334. return typedVal.mValue;
  6335. }
  6336. else
  6337. {
  6338. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6339. auto firstElementField = &arrayType->mFieldInstances.back();
  6340. int arrayClassSize = firstElementField->mDataOffset;
  6341. sizeValue = GetConstValue(arrayClassSize);
  6342. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6343. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6344. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6345. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6346. if (!isDynAlloc)
  6347. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6348. else
  6349. {
  6350. MarkDynStack(scopeData);
  6351. SaveStackState(scopeData);
  6352. }
  6353. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6354. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6355. if (!isDynAlloc)
  6356. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6357. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6358. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6359. mBfIRBuilder->ClearDebugLocation_Last();
  6360. if (!isDynAlloc)
  6361. mBfIRBuilder->SetInsertPoint(prevBlock);
  6362. if (!noDtorCall)
  6363. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6364. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6365. return typedVal.mValue;
  6366. }
  6367. }
  6368. }
  6369. else if (appendSizeValue)
  6370. {
  6371. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6372. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6373. // use the "dynSize" version conservatively
  6374. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6375. {
  6376. // Generate and check new size
  6377. sizeValue = GetConstValue(typeInstance->mInstSize);
  6378. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6379. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6380. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6381. if (!noDtorCall)
  6382. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6383. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6384. return typedVal.mValue;
  6385. }
  6386. else // stack alloc, unlooped, with append
  6387. {
  6388. sizeValue = GetConstValue(typeInstance->mInstSize);
  6389. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6390. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6391. bool wasDynAlloc = isDynAlloc;
  6392. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6393. if (!isDynAlloc)
  6394. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6395. else
  6396. {
  6397. MarkDynStack(scopeData);
  6398. SaveStackState(scopeData);
  6399. }
  6400. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6401. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6402. if (!isDynAlloc)
  6403. {
  6404. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6405. }
  6406. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6407. bool mayBeLarge = false;
  6408. if (sizeValue.IsConst())
  6409. {
  6410. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6411. if (constantInt->mInt64 >= 4096)
  6412. mayBeLarge = true;
  6413. }
  6414. else
  6415. mayBeLarge = true;
  6416. if (((type->IsObject() && (!mayBeLarge))) ||
  6417. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6418. ((zeroMemory) && (!mayBeLarge)))
  6419. {
  6420. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6421. }
  6422. BfIRValue castedVal;
  6423. if (!isDynAlloc)
  6424. {
  6425. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6426. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6427. mBfIRBuilder->ClearDebugLocation(castedVal);
  6428. mBfIRBuilder->SetInsertPoint(prevBlock);
  6429. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6430. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6431. }
  6432. else
  6433. {
  6434. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6435. }
  6436. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6437. if (!noDtorCall)
  6438. {
  6439. bool doCondAlloca = false;
  6440. if (!IsTargetingBeefBackend())
  6441. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6442. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6443. }
  6444. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6445. return typedVal.mValue;
  6446. }
  6447. }
  6448. else // "Normal" stack alloc
  6449. {
  6450. BF_ASSERT(!sizeValue);
  6451. //TODO: If sizeValue is a constant then do this in the head IR builder
  6452. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6453. if (!isLoopedAlloc)
  6454. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6455. else
  6456. {
  6457. MarkDynStack(scopeData);
  6458. SaveStackState(scopeData);
  6459. }
  6460. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6461. if (!isLoopedAlloc)
  6462. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6463. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6464. bool mayBeLarge = allocSize >= 4096;
  6465. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6466. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6467. ((zeroMemory) && (!mayBeLarge)))
  6468. {
  6469. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6470. // and memset is always safe
  6471. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6472. }
  6473. auto typedVal = BfTypedValue(allocaInst, type);
  6474. if (!isLoopedAlloc)
  6475. {
  6476. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6477. mBfIRBuilder->SetInsertPoint(prevBlock);
  6478. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6479. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6480. }
  6481. if (!noDtorCall)
  6482. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6483. if (typeInstance != NULL)
  6484. {
  6485. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6486. }
  6487. else
  6488. {
  6489. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6490. }
  6491. return allocaInst;
  6492. }
  6493. }
  6494. else if (arraySize)
  6495. {
  6496. if (isRawArrayAlloc)
  6497. {
  6498. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6499. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6500. }
  6501. else
  6502. {
  6503. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6504. typeInstance = arrayType;
  6505. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6506. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6507. appendSizeValue = elementDataSize;
  6508. if (!type->IsSizeAligned())
  6509. {
  6510. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6511. }
  6512. }
  6513. }
  6514. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6515. {
  6516. auto vDataRef = GetClassVDataPtr(typeInstance);
  6517. BfIRValue result;
  6518. bool isResultInitialized = false;
  6519. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6520. if (typeInstance->mTypeOptionsIdx != -1)
  6521. {
  6522. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6523. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6524. }
  6525. if (!sizeValue)
  6526. sizeValue = GetConstValue(typeInstance->mInstSize);
  6527. if (appendSizeValue)
  6528. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6529. BfIRValue origSizeValue = sizeValue;
  6530. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6531. if (isAllocEx)
  6532. {
  6533. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6534. if (prepareStackTraceMethod)
  6535. {
  6536. SizedArray<BfIRValue, 2> irArgs;
  6537. irArgs.Add(sizeValue);
  6538. irArgs.Add(GetConstValue(stackCount));
  6539. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6540. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6541. }
  6542. }
  6543. if (allocTarget.mCustomAllocator)
  6544. {
  6545. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6546. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6547. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6548. {
  6549. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6550. mBfIRBuilder->PopulateType(classVDataType);
  6551. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6552. mBfIRBuilder->PopulateType(typeInstType);
  6553. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6554. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6555. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6556. BfTypedValueExpression typedValueExpr;
  6557. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6558. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6559. BfExprEvaluator exprEvaluator(this);
  6560. SizedArray<BfExpression*, 2> argExprs;
  6561. argExprs.push_back(&typedValueExpr);
  6562. BfTypedValueExpression sizeValueExpr;
  6563. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6564. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6565. argExprs.push_back(&sizeValueExpr);
  6566. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6567. BfResolvedArgs argValues(&sizedArgExprs);
  6568. exprEvaluator.ResolveArgValues(argValues);
  6569. exprEvaluator.mNoBind = true;
  6570. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6571. if (allocResult)
  6572. {
  6573. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6574. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6575. else
  6576. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6577. isResultInitialized = true;
  6578. }
  6579. }
  6580. }
  6581. if (!result)
  6582. {
  6583. if (hasCustomAllocator)
  6584. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6585. }
  6586. if (result)
  6587. {
  6588. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6589. {
  6590. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6591. SizedArray<BfIRValue, 4> llvmArgs;
  6592. llvmArgs.push_back(objectPtr);
  6593. llvmArgs.push_back(origSizeValue);
  6594. llvmArgs.push_back(vDataRef);
  6595. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6596. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6597. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6598. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6599. }
  6600. else
  6601. {
  6602. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6603. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6604. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6605. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6606. }
  6607. }
  6608. else
  6609. {
  6610. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6611. return GetDefaultValue(typeInstance);
  6612. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6613. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6614. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6615. {
  6616. SizedArray<BfIRValue, 4> llvmArgs;
  6617. llvmArgs.push_back(vData);
  6618. llvmArgs.push_back(sizeValue);
  6619. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6620. llvmArgs.push_back(GetConstValue(stackCount));
  6621. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6622. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6623. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6624. }
  6625. else
  6626. {
  6627. SizedArray<BfIRValue, 4> llvmArgs;
  6628. llvmArgs.push_back(sizeValue);
  6629. BfIRFunction irFunc;
  6630. if (mCompiler->mOptions.mDebugAlloc)
  6631. {
  6632. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6633. irFunc = moduleMethodInstance.mFunc;
  6634. }
  6635. if (!irFunc)
  6636. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6637. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6638. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6639. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6640. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6641. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6642. }
  6643. }
  6644. if ((zeroMemory) && (arraySize))
  6645. {
  6646. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6647. typeInstance = arrayType;
  6648. auto firstElementField = &arrayType->mFieldInstances.back();
  6649. int arrayClassSize = firstElementField->mDataOffset;
  6650. BfIRValue elementDataSize;
  6651. bool skipZero = false;
  6652. if (arraySize.IsConst())
  6653. {
  6654. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6655. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6656. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6657. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6658. if (constVal->mInt64 <= 0)
  6659. skipZero = true;
  6660. }
  6661. else
  6662. {
  6663. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6664. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6665. }
  6666. if (!skipZero)
  6667. {
  6668. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6669. auto ptrType = CreatePointerType(i8Type);
  6670. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6671. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6672. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6673. appendSizeValue = elementDataSize;
  6674. }
  6675. }
  6676. return result;
  6677. }
  6678. else
  6679. {
  6680. if (!sizeValue)
  6681. sizeValue = GetConstValue(allocSize);
  6682. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6683. }
  6684. }
  6685. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6686. {
  6687. if ((type == NULL) || (refNode == NULL))
  6688. return;
  6689. auto typeInstance = type->ToTypeInstance();
  6690. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6691. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6692. }
  6693. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6694. {
  6695. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6696. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6697. }
  6698. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6699. {
  6700. if (sizeMultiple == 0)
  6701. sizeMultiple = align;
  6702. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6703. {
  6704. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6705. {
  6706. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6707. BF_ASSERT(localVar->mName == "appendIdx");
  6708. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6709. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6710. if (align > 1)
  6711. {
  6712. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6713. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6714. }
  6715. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6716. }
  6717. else
  6718. {
  6719. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6720. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6721. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6722. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6723. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6724. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6725. }
  6726. }
  6727. if (mCurMethodState->mCurAppendAlign == 0)
  6728. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6729. else
  6730. {
  6731. if (sizeMultiple % align == 0)
  6732. mCurMethodState->mCurAppendAlign = align;
  6733. else
  6734. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6735. }
  6736. }
  6737. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6738. {
  6739. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6740. BF_ASSERT(localVar->mName == "appendIdx");
  6741. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6742. BfIRValue retValue;
  6743. BfTypeInstance* retTypeInstance = NULL;
  6744. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6745. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6746. if (arraySize)
  6747. {
  6748. if (isRawArrayAlloc)
  6749. {
  6750. EmitAppendAlign(type->mAlign);
  6751. BfPointerType* ptrType = CreatePointerType(type);
  6752. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6753. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6754. if (mSystem->mPtrSize != 4)
  6755. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6756. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6757. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6758. if (zeroMemory)
  6759. {
  6760. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6761. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6762. }
  6763. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6764. }
  6765. else
  6766. {
  6767. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6768. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6769. auto firstElementField = &arrayType->mFieldInstances.back();
  6770. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6771. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6772. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6773. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6774. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6775. if (mSystem->mPtrSize != 4)
  6776. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6777. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6778. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6779. if (zeroMemory)
  6780. {
  6781. // Only zero out the actual elements
  6782. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6783. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6784. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6785. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6786. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6787. }
  6788. retTypeInstance = arrayType;
  6789. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6790. }
  6791. }
  6792. else
  6793. {
  6794. auto typeInst = type->ToTypeInstance();
  6795. BfIRValue sizeValue;
  6796. BfIRType toType;
  6797. if (typeInst != NULL)
  6798. {
  6799. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6800. sizeValue = GetConstValue(typeInst->mInstSize);
  6801. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6802. }
  6803. else
  6804. {
  6805. EmitAppendAlign(type->mAlign, type->mSize);
  6806. sizeValue = GetConstValue(type->mSize);
  6807. auto toPtrType = CreatePointerType(type);
  6808. toType = mBfIRBuilder->MapType(toPtrType);
  6809. }
  6810. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6811. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6812. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6813. retTypeInstance = typeInst;
  6814. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6815. }
  6816. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6817. {
  6818. mBfIRBuilder->PopulateType(retTypeInstance);
  6819. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6820. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6821. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6822. auto curThis = GetThis();
  6823. BfIRValue newFlags;
  6824. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6825. {
  6826. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6827. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6828. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6829. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6830. }
  6831. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6832. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6833. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6834. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6835. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6836. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6837. {
  6838. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6839. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6840. }
  6841. }
  6842. if (appendSizeValue)
  6843. {
  6844. EmitAppendAlign(appendAllocAlign);
  6845. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6846. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6847. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6848. }
  6849. return retValue;
  6850. }
  6851. bool BfModule::IsOptimized()
  6852. {
  6853. if (mProject == NULL)
  6854. return false;
  6855. int optLevel = GetModuleOptions().mOptLevel;
  6856. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6857. }
  6858. bool BfModule::IsTargetingBeefBackend()
  6859. {
  6860. if (mProject == NULL)
  6861. return false;
  6862. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6863. }
  6864. bool BfModule::HasCompiledOutput()
  6865. {
  6866. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6867. }
  6868. // We will skip the object access check for any occurances of this value
  6869. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6870. {
  6871. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6872. return;
  6873. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6874. return;
  6875. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6876. return;
  6877. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6878. }
  6879. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6880. {
  6881. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6882. return;
  6883. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6884. return;
  6885. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6886. auto typeOptions = GetTypeOptions();
  6887. if (typeOptions != NULL)
  6888. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6889. if (!emitObjectAccessCheck)
  6890. return;
  6891. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6892. {
  6893. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6894. return;
  6895. }
  6896. if (typedVal.IsAddr())
  6897. typedVal = LoadValue(typedVal);
  6898. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6899. }
  6900. void BfModule::EmitNop()
  6901. {
  6902. if (mProject == NULL)
  6903. return;
  6904. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()))
  6905. return;
  6906. mBfIRBuilder->CreateNop();
  6907. }
  6908. void BfModule::EmitEnsureInstructionAt()
  6909. {
  6910. if (mProject == NULL)
  6911. return;
  6912. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()))
  6913. return;
  6914. mBfIRBuilder->CreateEnsureInstructionAt();
  6915. }
  6916. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6917. {
  6918. if (mBfIRBuilder->mIgnoreWrites)
  6919. return; // Nothing needed here
  6920. auto irb = mBfIRBuilder;
  6921. auto checkBB = irb->CreateBlock("as.check");
  6922. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6923. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6924. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6925. auto intPtrType = CreatePointerType(intType);
  6926. auto intPtrPtrType = CreatePointerType(intPtrType);
  6927. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6928. auto int32PtrType = CreatePointerType(int32Type);
  6929. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6930. if (mCompiler->mOptions.mAllowHotSwapping)
  6931. {
  6932. BfExprEvaluator exprEvaluator(this);
  6933. AddBasicBlock(checkBB);
  6934. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6935. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  6936. SizedArray<BfIRValue, 4> irArgs;
  6937. irArgs.push_back(objectParam);
  6938. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  6939. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  6940. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  6941. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  6942. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  6943. }
  6944. else
  6945. {
  6946. AddBasicBlock(checkBB);
  6947. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  6948. vDataPtr = irb->CreateLoad(vDataPtr);
  6949. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6950. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6951. if (targetType->IsInterface())
  6952. {
  6953. auto targetTypeInst = targetType->ToTypeInstance();
  6954. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6955. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  6956. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  6957. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  6958. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  6959. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  6960. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  6961. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  6962. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  6963. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  6964. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  6965. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  6966. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  6967. }
  6968. else
  6969. {
  6970. if (!targetType->IsTypeInstance())
  6971. targetType = GetWrappedStructType(targetType);
  6972. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6973. int inheritanceIdOfs = mSystem->mPtrSize;
  6974. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  6975. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  6976. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  6977. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  6978. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  6979. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  6980. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  6981. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  6982. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  6983. fieldInst = &typeTypeInstance->mFieldInstances[10];
  6984. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  6985. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  6986. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  6987. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  6988. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  6989. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  6990. }
  6991. }
  6992. }
  6993. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  6994. {
  6995. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  6996. auto typeOptions = GetTypeOptions();
  6997. if (typeOptions != NULL)
  6998. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  6999. if (emitDynamicCastCheck)
  7000. {
  7001. int wantTypeId = 0;
  7002. if (!type->IsGenericParam())
  7003. wantTypeId = type->mTypeId;
  7004. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7005. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7006. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7007. AddBasicBlock(failBlock);
  7008. SizedArray<BfIRValue, 8> llvmArgs;
  7009. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7010. llvmArgs.push_back(bitAddr);
  7011. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7012. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7013. BF_ASSERT(objDynCheck);
  7014. if (objDynCheck)
  7015. {
  7016. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7017. }
  7018. mBfIRBuilder->CreateBr(endBlock);
  7019. AddBasicBlock(endBlock);
  7020. }
  7021. }
  7022. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7023. {
  7024. BP_ZONE("BoxValue");
  7025. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7026. if (typedVal.mType->IsNullable())
  7027. {
  7028. typedVal = MakeAddressable(typedVal);
  7029. auto innerType = typedVal.mType->GetUnderlyingType();
  7030. if (!innerType->IsValueType())
  7031. {
  7032. Fail("Only value types can be boxed", srcNode);
  7033. return BfTypedValue();
  7034. }
  7035. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7036. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7037. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7038. mBfIRBuilder->PopulateType(typedVal.mType);
  7039. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7040. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7041. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7042. auto boxedType = CreateBoxedType(innerType);
  7043. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7044. auto resultType = toType;
  7045. if (resultType == NULL)
  7046. resultType = boxedType;
  7047. mBfIRBuilder->AddBlock(boxBB);
  7048. mBfIRBuilder->SetInsertPoint(boxBB);
  7049. BfScopeData newScope;
  7050. newScope.mOuterIsConditional = true;
  7051. mCurMethodState->AddScope(&newScope);
  7052. NewScopeState();
  7053. BfIRValue nullableValueAddr;
  7054. BfIRValue loadedVal;
  7055. if (innerType->IsValuelessType())
  7056. {
  7057. loadedVal = mBfIRBuilder->GetFakeVal();
  7058. }
  7059. else
  7060. {
  7061. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7062. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7063. }
  7064. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7065. RestoreScopeState();
  7066. if (!boxedVal)
  7067. return BfTypedValue();
  7068. mBfIRBuilder->CreateBr(endBB);
  7069. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7070. mBfIRBuilder->AddBlock(endBB);
  7071. mBfIRBuilder->SetInsertPoint(endBB);
  7072. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7073. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7074. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7075. return BfTypedValue(phi, resultType);
  7076. }
  7077. if (fromStructTypeInstance == NULL)
  7078. {
  7079. auto primType = (BfPrimitiveType*) typedVal.mType;
  7080. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7081. }
  7082. if (fromStructTypeInstance == NULL)
  7083. return BfTypedValue();
  7084. BfTypeInstance* toTypeInstance = NULL;
  7085. if (toType != NULL)
  7086. toTypeInstance = toType->ToTypeInstance();
  7087. // Need to box it
  7088. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (CreateBoxedType(fromStructTypeInstance) == toType);
  7089. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7090. {
  7091. auto boxedType = CreateBoxedType(fromStructTypeInstance);
  7092. mBfIRBuilder->PopulateType(boxedType);
  7093. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7094. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7095. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7096. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7097. if (boxedType->IsUnspecializedType())
  7098. {
  7099. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7100. }
  7101. else
  7102. {
  7103. PopulateType(fromStructTypeInstance);
  7104. if (!fromStructTypeInstance->IsValuelessType())
  7105. {
  7106. typedVal = LoadValue(typedVal);
  7107. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7108. if (typedVal.mType != fromStructTypeInstance)
  7109. {
  7110. auto ptrType = CreatePointerType(typedVal.mType);
  7111. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7112. }
  7113. if (typedVal.IsSplat())
  7114. {
  7115. AggregateSplatIntoAddr(typedVal, valPtr);
  7116. }
  7117. else
  7118. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7119. }
  7120. }
  7121. if (toType == NULL)
  7122. {
  7123. return BfTypedValue(allocaInst, boxedType);
  7124. }
  7125. else
  7126. {
  7127. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7128. return BfTypedValue(castedValue, toType);
  7129. }
  7130. }
  7131. return BfTypedValue();
  7132. }
  7133. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7134. {
  7135. BfTypeInstance* checkTypeInst = typeInst;
  7136. while (checkTypeInst != NULL)
  7137. {
  7138. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7139. {
  7140. if (checkProp->mName == propDef->mName)
  7141. {
  7142. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7143. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7144. {
  7145. propDef = checkProp;
  7146. typeInst = checkTypeInst;
  7147. return true;
  7148. }
  7149. }
  7150. }
  7151. checkTypeInst = checkTypeInst->mBaseType;
  7152. }
  7153. return false;
  7154. }
  7155. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7156. {
  7157. if (!typeInstance->mResolvingVarField)
  7158. {
  7159. if (typeInstance->IsIncomplete())
  7160. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7161. }
  7162. else
  7163. {
  7164. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7165. {
  7166. AssertErrorState();
  7167. return NULL;
  7168. }
  7169. }
  7170. if (assertName != NULL)
  7171. {
  7172. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7173. }
  7174. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7175. if (methodGroup.mDefault == NULL)
  7176. {
  7177. if (!mCompiler->mIsResolveOnly)
  7178. {
  7179. BF_ASSERT(methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference);
  7180. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7181. // Get it from the owning module so we don't create a reference prematurely...
  7182. auto declModule = typeInstance->mModule;
  7183. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7184. }
  7185. else
  7186. {
  7187. auto declModule = typeInstance->mModule;
  7188. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7189. }
  7190. }
  7191. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7192. //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
  7193. // be from a call to the NON-raw version
  7194. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7195. // {
  7196. // methodInstance->mIsReified = mIsReified;
  7197. // if (methodInstance->mMethodProcessRequest == NULL)
  7198. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7199. // }
  7200. return methodInstance;
  7201. }
  7202. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7203. {
  7204. if (methodDef->mIsLocalMethod)
  7205. {
  7206. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7207. }
  7208. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7209. }
  7210. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7211. {
  7212. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7213. while (typeInstance != NULL)
  7214. {
  7215. typeInstance->mTypeDef->PopulateMemberSets();
  7216. BfMemberSetEntry* entry = NULL;
  7217. BfMethodDef* methodDef = NULL;
  7218. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7219. methodDef = (BfMethodDef*)entry->mMemberDef;
  7220. while (methodDef != NULL)
  7221. {
  7222. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7223. (methodDef->mGenericParams.size() == 0) &&
  7224. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7225. return GetRawMethodInstance(typeInstance, methodDef);
  7226. methodDef = methodDef->mNextWithSameName;
  7227. }
  7228. if (!checkBase)
  7229. break;
  7230. typeInstance = typeInstance->mBaseType;
  7231. }
  7232. return NULL;
  7233. }
  7234. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7235. {
  7236. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7237. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7238. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7239. if (!owner->IsGenericTypeInstance())
  7240. return methodInstance;
  7241. auto genericType = (BfGenericTypeInstance*)owner;
  7242. if (genericType->IsUnspecializedType())
  7243. return methodInstance;
  7244. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7245. if (unspecializedType == NULL)
  7246. {
  7247. AssertErrorState();
  7248. return methodInstance;
  7249. }
  7250. if (unspecializedType == NULL)
  7251. return methodInstance;
  7252. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7253. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7254. }
  7255. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7256. {
  7257. int genericCount = 0;
  7258. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7259. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7260. {
  7261. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7262. if (param->IsGenericParam())
  7263. genericCount++;
  7264. }
  7265. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7266. genericCount++;
  7267. return genericCount;
  7268. }
  7269. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7270. {
  7271. BF_ASSERT(!mIsScratchModule);
  7272. BF_ASSERT(mIsReified);
  7273. BfModule* mainModule = this;
  7274. if (mParentModule != NULL)
  7275. mainModule = mParentModule;
  7276. BfModule* specModule = NULL;
  7277. BfModule** specModulePtr = NULL;
  7278. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7279. {
  7280. return *specModulePtr;
  7281. }
  7282. else
  7283. {
  7284. String specModuleName = mModuleName;
  7285. for (auto bfProject : projectList)
  7286. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7287. specModule = new BfModule(mContext, specModuleName);
  7288. specModule->mProject = mainModule->mProject;
  7289. specModule->mParentModule = mainModule;
  7290. specModule->mIsSpecializedMethodModuleRoot = true;
  7291. specModule->Init();
  7292. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7293. }
  7294. return specModule;
  7295. }
  7296. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7297. {
  7298. if (mCompiler->IsSkippingExtraResolveChecks())
  7299. return BfIRValue();
  7300. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7301. {
  7302. //BF_ASSERT(!methodInstance->mIRFunction);
  7303. return BfIRValue();
  7304. }
  7305. auto methodDef = methodInstance->mMethodDef;
  7306. StringT<128> methodName;
  7307. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7308. if (isInlined != methodInstance->mAlwaysInline)
  7309. {
  7310. if (isInlined)
  7311. methodName += "__INLINE";
  7312. else
  7313. methodName += "__NOINLINE";
  7314. }
  7315. if (tryExisting)
  7316. {
  7317. auto func = mBfIRBuilder->GetFunction(methodName);
  7318. if (func)
  7319. return func;
  7320. }
  7321. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7322. {
  7323. if (methodDeclaration->mExternSpecifier != NULL)
  7324. {
  7325. auto intrinsic = GetIntrinsic(methodInstance);
  7326. if (intrinsic)
  7327. return intrinsic;
  7328. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7329. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7330. if (func)
  7331. return func;*/
  7332. }
  7333. }
  7334. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7335. {
  7336. return CreateDllImportGlobalVar(methodInstance, false);
  7337. }
  7338. BfIRType returnType;
  7339. SizedArray<BfIRType, 8> paramTypes;
  7340. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7341. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7342. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7343. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7344. if (callingConv != BfIRCallingConv_CDecl)
  7345. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7346. SetupLLVMMethod(methodInstance, func, isInlined);
  7347. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7348. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7349. // {
  7350. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7351. // {
  7352. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7353. // }
  7354. // }
  7355. return func;
  7356. }
  7357. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7358. {
  7359. if (assertName != NULL)
  7360. {
  7361. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7362. }
  7363. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7364. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7365. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7366. {
  7367. // Can't use it, not reified
  7368. methodInstance = NULL;
  7369. }
  7370. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7371. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7372. {
  7373. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7374. return BfModuleMethodInstance(methodInstance, func);
  7375. }
  7376. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7377. }
  7378. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7379. {
  7380. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7381. while (typeInstance != NULL)
  7382. {
  7383. typeInstance->mTypeDef->PopulateMemberSets();
  7384. BfMemberSetEntry* entry = NULL;
  7385. BfMethodDef* methodDef = NULL;
  7386. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7387. methodDef = (BfMethodDef*)entry->mMemberDef;
  7388. while (methodDef != NULL)
  7389. {
  7390. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7391. (methodDef->mGenericParams.size() == 0) &&
  7392. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7393. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7394. methodDef = methodDef->mNextWithSameName;
  7395. }
  7396. if (!checkBase)
  7397. break;
  7398. typeInstance = typeInstance->mBaseType;
  7399. }
  7400. return BfModuleMethodInstance();
  7401. }
  7402. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7403. {
  7404. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7405. while (typeInstance != NULL)
  7406. {
  7407. typeInstance->mTypeDef->PopulateMemberSets();
  7408. BfMemberSetEntry* entry = NULL;
  7409. BfMethodDef* methodDef = NULL;
  7410. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7411. methodDef = (BfMethodDef*)entry->mMemberDef;
  7412. while (methodDef != NULL)
  7413. {
  7414. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7415. (methodDef->mGenericParams.size() == 0) &&
  7416. (paramTypes.size() == methodDef->mParams.size()))
  7417. {
  7418. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7419. if (moduleMethodInstance.mMethodInstance != NULL)
  7420. {
  7421. bool matches = true;
  7422. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7423. {
  7424. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7425. matches = false;
  7426. }
  7427. if (matches)
  7428. return moduleMethodInstance;
  7429. }
  7430. }
  7431. methodDef = methodDef->mNextWithSameName;
  7432. }
  7433. if (!checkBase)
  7434. break;
  7435. typeInstance = typeInstance->mBaseType;
  7436. }
  7437. return BfModuleMethodInstance();
  7438. }
  7439. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7440. {
  7441. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7442. PopulateType(internalType);
  7443. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7444. if (!moduleMethodInstance)
  7445. {
  7446. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7447. }
  7448. return moduleMethodInstance;
  7449. }
  7450. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7451. {
  7452. while (typeInstance != NULL)
  7453. {
  7454. typeInstance->mTypeDef->PopulateMemberSets();
  7455. BfMemberSetEntry* entry = NULL;
  7456. BfMethodDef* methodDef = NULL;
  7457. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7458. methodDef = (BfMethodDef*)entry->mMemberDef;
  7459. while (methodDef != NULL)
  7460. {
  7461. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7462. (methodDef->mGenericParams.size() == 0) &&
  7463. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7464. {
  7465. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7466. if (!methodInstanceGroup.IsImplemented())
  7467. return false;
  7468. if (methodInstanceGroup.mDefault == NULL)
  7469. return false;
  7470. return methodInstanceGroup.mDefault->mIsReified;
  7471. }
  7472. methodDef = methodDef->mNextWithSameName;
  7473. }
  7474. if (!checkBase)
  7475. break;
  7476. typeInstance = typeInstance->mBaseType;
  7477. }
  7478. return false;
  7479. }
  7480. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7481. {
  7482. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7483. while (typeInstance != NULL)
  7484. {
  7485. typeInstance->mTypeDef->PopulateMemberSets();
  7486. BfMemberSetEntry* entry = NULL;
  7487. BfMethodDef* methodDef = NULL;
  7488. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7489. methodDef = (BfMethodDef*)entry->mMemberDef;
  7490. while (methodDef != NULL)
  7491. {
  7492. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7493. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7494. return true;
  7495. methodDef = methodDef->mNextWithSameName;
  7496. }
  7497. if (!checkBase)
  7498. break;
  7499. typeInstance = typeInstance->mBaseType;
  7500. }
  7501. return BfModuleMethodInstance();
  7502. }
  7503. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7504. {
  7505. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7506. typeInstance->mTypeDef->PopulateMemberSets();
  7507. BfMemberSetEntry* entry = NULL;
  7508. BfFieldDef* fieldDef = NULL;
  7509. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7510. {
  7511. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7512. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7513. }
  7514. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7515. // {
  7516. // auto fieldDef = fieldInst.GetFieldDef();
  7517. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7518. // return &fieldInst;
  7519. // }
  7520. return NULL;
  7521. }
  7522. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7523. {
  7524. auto methodDef = methodInst->mMethodDef;
  7525. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7526. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7527. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7528. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7529. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7530. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7531. type = ResolveGenericType(type, *methodGenericArgs);
  7532. String methodName;
  7533. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7534. {
  7535. methodName = TypeToString(type, typeNameFlags);
  7536. if (methodName == "$")
  7537. methodName = "";
  7538. else
  7539. methodName += ".";
  7540. }
  7541. String accessorString;
  7542. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7543. if (methodInst->mMethodDef->mIsLocalMethod)
  7544. {
  7545. int atPos = (int)methodDefName.IndexOf('$');
  7546. methodDefName.RemoveToEnd(atPos);
  7547. methodDefName.Replace("@", ".");
  7548. }
  7549. else
  7550. {
  7551. int atPos = (int)methodDefName.IndexOf('$');
  7552. if (atPos != -1)
  7553. {
  7554. accessorString = methodDefName.Substring(0, atPos);
  7555. if ((accessorString == "get") || (accessorString == "set"))
  7556. {
  7557. methodDefName = methodDefName.Substring(atPos + 1);
  7558. }
  7559. else
  7560. accessorString = "";
  7561. }
  7562. }
  7563. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7564. {
  7565. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7566. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7567. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7568. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7569. methodName += ".";
  7570. }
  7571. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7572. {
  7573. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7574. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7575. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7576. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7577. methodName += ".";
  7578. }
  7579. if (methodDef->mMethodType == BfMethodType_Operator)
  7580. {
  7581. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7582. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7583. {
  7584. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7585. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7586. {
  7587. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7588. methodName += "explicit ";
  7589. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7590. methodName += "explicit ";
  7591. }*/
  7592. methodName += "operator ";
  7593. if (methodInst->mReturnType != NULL)
  7594. methodName += TypeToString(methodInst->mReturnType);
  7595. }
  7596. else
  7597. {
  7598. methodName += "operator";
  7599. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7600. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7601. }
  7602. }
  7603. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7604. {
  7605. if (methodDef->mIsStatic)
  7606. methodName += "__BfStaticCtor";
  7607. else
  7608. methodName += "this";
  7609. accessorString = "";
  7610. }
  7611. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7612. {
  7613. methodDef->GetRefNode()->ToString(methodName);
  7614. methodName += " get accessor";
  7615. return methodName;
  7616. }
  7617. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7618. {
  7619. methodDef->GetRefNode()->ToString(methodName);
  7620. methodName += " set accessor";
  7621. return methodName;
  7622. }
  7623. else
  7624. methodName += methodDefName;
  7625. BfTypeVector newMethodGenericArgs;
  7626. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7627. {
  7628. methodName += "<";
  7629. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7630. {
  7631. if (i > 0)
  7632. methodName += ", ";
  7633. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7634. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7635. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7636. if (allowResolveGenericParamNames)
  7637. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7638. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7639. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7640. {
  7641. bool hasEmpty = false;
  7642. for (auto arg : *methodGenericArgs)
  7643. {
  7644. if (arg == NULL)
  7645. hasEmpty = true;
  7646. }
  7647. if (hasEmpty)
  7648. {
  7649. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7650. {
  7651. auto arg = (*methodGenericArgs)[genericIdx];
  7652. if (arg != NULL)
  7653. newMethodGenericArgs.push_back(arg);
  7654. else
  7655. {
  7656. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7657. if (genericParamInst->mTypeConstraint != NULL)
  7658. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7659. else
  7660. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7661. }
  7662. }
  7663. methodGenericArgs = &newMethodGenericArgs;
  7664. }
  7665. if (type->IsUnspecializedType())
  7666. type = ResolveGenericType(type, *methodGenericArgs);
  7667. }
  7668. methodName += TypeToString(type, typeNameFlags);
  7669. }
  7670. methodName += ">";
  7671. }
  7672. if (accessorString.length() == 0)
  7673. {
  7674. int dispParamIdx = 0;
  7675. methodName += "(";
  7676. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7677. {
  7678. int paramKind = methodInst->GetParamKind(paramIdx);
  7679. if (paramKind == BfParamKind_ImplicitCapture)
  7680. continue;
  7681. if (dispParamIdx > 0)
  7682. methodName += ", ";
  7683. if (paramKind == BfParamKind_Params)
  7684. methodName += "params ";
  7685. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7686. BfType* type = methodInst->GetParamType(paramIdx);
  7687. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7688. type = ResolveGenericType(type, *methodGenericArgs);
  7689. methodName += TypeToString(type, typeNameFlags);
  7690. methodName += " ";
  7691. methodName += methodInst->GetParamName(paramIdx);
  7692. dispParamIdx++;
  7693. }
  7694. methodName += ")";
  7695. }
  7696. if (accessorString.length() != 0)
  7697. {
  7698. methodName += " " + accessorString;
  7699. }
  7700. return methodName;
  7701. }
  7702. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7703. {
  7704. if ((flagsLeft & checkFlag) == 0)
  7705. return;
  7706. if (!str.empty())
  7707. {
  7708. if (flagsLeft == checkFlag)
  7709. {
  7710. if ((int)str.IndexOf(',') != -1)
  7711. str += ", and ";
  7712. else
  7713. str += " and ";
  7714. }
  7715. else
  7716. str += ", ";
  7717. }
  7718. str += addString;
  7719. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7720. }
  7721. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7722. {
  7723. String resultStr;
  7724. auto flagsLeft = attrTarget;
  7725. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7726. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7727. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7728. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7729. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7730. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7731. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7732. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7733. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7734. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7735. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7736. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7737. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7738. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7739. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7740. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7741. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7742. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7743. if (resultStr.IsEmpty())
  7744. return "<nothing>";
  7745. return resultStr;
  7746. }
  7747. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7748. {
  7749. auto constant = mBfIRBuilder->GetConstant(irVal);
  7750. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7751. if (stringPoolIdx != -1)
  7752. {
  7753. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7754. return;
  7755. }
  7756. if (constant->mConstType == BfConstType_Array)
  7757. {
  7758. auto constArray = (BfConstantArray*)constant;
  7759. SizedArray<BfIRValue, 8> newVals;
  7760. for (auto val : constArray->mValues)
  7761. {
  7762. auto newVal = val;
  7763. CurrentAddToConstHolder(newVal);
  7764. newVals.push_back(newVal);
  7765. }
  7766. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7767. return;
  7768. }
  7769. auto origConst = irVal;
  7770. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7771. {
  7772. auto bitcast = (BfConstantBitCast*)constant;
  7773. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7774. }
  7775. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7776. }
  7777. void BfModule::ClearConstData()
  7778. {
  7779. mBfIRBuilder->ClearConstData();
  7780. mStringObjectPool.Clear();
  7781. mStringCharPtrPool.Clear();
  7782. mStringPoolRefs.Clear();
  7783. }
  7784. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7785. {
  7786. bool isString = false;
  7787. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7788. if (wantType->IsPointer())
  7789. isString = true;
  7790. if (!isString)
  7791. {
  7792. switch (constant->mTypeCode)
  7793. {
  7794. case BfTypeCode_Boolean:
  7795. case BfTypeCode_Int8:
  7796. case BfTypeCode_UInt8:
  7797. case BfTypeCode_Int16:
  7798. case BfTypeCode_UInt16:
  7799. case BfTypeCode_Int32:
  7800. case BfTypeCode_UInt32:
  7801. case BfTypeCode_Int64:
  7802. case BfTypeCode_UInt64:
  7803. case BfTypeCode_IntPtr:
  7804. case BfTypeCode_UIntPtr:
  7805. case BfTypeCode_IntUnknown:
  7806. case BfTypeCode_UIntUnknown:
  7807. case BfTypeCode_Char8:
  7808. case BfTypeCode_Char16:
  7809. case BfTypeCode_Char32:
  7810. case BfTypeCode_Single:
  7811. case BfTypeCode_Double:
  7812. {
  7813. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7814. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7815. if (typedValue.mType == wantType)
  7816. return typedValue;
  7817. if (wantType->IsTypedPrimitive())
  7818. {
  7819. if (typedValue.mType == wantType->GetUnderlyingType())
  7820. {
  7821. typedValue.mType = wantType;
  7822. return typedValue;
  7823. }
  7824. }
  7825. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7826. BF_ASSERT(castedTypedValue);
  7827. return castedTypedValue;
  7828. }
  7829. break;
  7830. }
  7831. }
  7832. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7833. BF_ASSERT(irValue);
  7834. if (!irValue)
  7835. return BfTypedValue();
  7836. return BfTypedValue(irValue, wantType, false);
  7837. }
  7838. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7839. {
  7840. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7841. {
  7842. return GetDefaultValue(wantType);
  7843. }
  7844. bool isString = false;
  7845. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7846. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7847. {
  7848. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7849. BfIRValue stringObjConst = GetStringObjectValue(str);
  7850. if (wantType->IsObject())
  7851. return stringObjConst;
  7852. return GetStringCharPtr(stringObjConst);
  7853. }
  7854. if (constant->mConstType == BfConstType_Array)
  7855. {
  7856. auto elementType = wantType->GetUnderlyingType();
  7857. auto constArray = (BfConstantArray*)constant;
  7858. SizedArray<BfIRValue, 8> newVals;
  7859. for (auto val : constArray->mValues)
  7860. {
  7861. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7862. }
  7863. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7864. }
  7865. return mBfIRBuilder->CreateConst(constant, constHolder);
  7866. }
  7867. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7868. {
  7869. if (attrTarget == BfAttributeTargets_SkipValidate)
  7870. return;
  7871. for (auto& customAttribute : customAttributes->mAttributes)
  7872. {
  7873. if (!customAttribute.mAwaitingValidation)
  7874. continue;
  7875. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7876. {
  7877. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7878. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7879. }
  7880. customAttribute.mAwaitingValidation = false;
  7881. }
  7882. }
  7883. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7884. {
  7885. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mName == "OpenAudio"))
  7886. {
  7887. NOP;
  7888. }
  7889. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7890. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7891. {
  7892. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7893. }
  7894. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7895. if (mCompiler->IsAutocomplete())
  7896. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7897. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7898. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7899. BfAutoComplete* autoComplete = NULL;
  7900. if (mCompiler->mResolvePassData != NULL)
  7901. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7902. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7903. {
  7904. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7905. BfCustomAttribute customAttribute;
  7906. customAttribute.mAwaitingValidation = true;
  7907. customAttribute.mRef = attributesDirective;
  7908. if (attributesDirective->mAttrOpenToken != NULL)
  7909. targetOverride = (BfAttributeTargets)0;
  7910. if (attributesDirective->mAttributeTypeRef == NULL)
  7911. {
  7912. AssertErrorState();
  7913. continue;
  7914. }
  7915. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7916. BfType* attrType = NULL;
  7917. BfAtomComposite nameComposite;
  7918. BfTypeDef* attrTypeDef = NULL;
  7919. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7920. {
  7921. BfTypeLookupError error;
  7922. error.mRefNode = attributesDirective->mAttributeTypeRef;
  7923. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  7924. }
  7925. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  7926. {
  7927. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  7928. if (attrTypeDef != NULL)
  7929. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  7930. }
  7931. if (attrTypeDef == NULL)
  7932. {
  7933. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  7934. continue;
  7935. }
  7936. bool isBypassedAttr = false;
  7937. if (attrTypeDef != NULL)
  7938. {
  7939. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  7940. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  7941. // We solve it by having a 'bypass' for known attributes that Object depends on
  7942. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  7943. {
  7944. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  7945. {
  7946. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  7947. for (auto methodDef : attrTypeDef->mMethods)
  7948. {
  7949. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  7950. {
  7951. customAttribute.mType = attrType->ToTypeInstance();
  7952. customAttribute.mCtor = methodDef;
  7953. isBypassedAttr = true;
  7954. break;
  7955. }
  7956. }
  7957. }
  7958. }
  7959. if (isBypassedAttr)
  7960. {
  7961. customAttribute.mAwaitingValidation = false;
  7962. customAttributes->mAttributes.push_back(customAttribute);
  7963. continue;
  7964. }
  7965. if (mContext->mCurTypeState != NULL)
  7966. {
  7967. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  7968. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  7969. }
  7970. else
  7971. {
  7972. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  7973. }
  7974. }
  7975. // Don't allow this
  7976. /*else if (mContext->mCurTypeState != NULL)
  7977. {
  7978. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  7979. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  7980. }
  7981. else
  7982. {
  7983. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  7984. }*/
  7985. BfTypeInstance* attrTypeInst = NULL;
  7986. if (attrType == NULL)
  7987. continue;
  7988. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  7989. attrTypeInst = attrType->ToTypeInstance();
  7990. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  7991. {
  7992. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  7993. continue;
  7994. }
  7995. if (mCurTypeInstance != NULL)
  7996. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  7997. customAttribute.mType = attrTypeInst;
  7998. BfConstResolver constResolver(this);
  7999. bool inPropSet = false;
  8000. SizedArray<BfResolvedArg, 2> argValues;
  8001. for (BfExpression* arg : attributesDirective->mArguments)
  8002. {
  8003. if (arg == NULL)
  8004. {
  8005. continue;
  8006. }
  8007. if (autoComplete != NULL)
  8008. autoComplete->mShowAttributeProperties = attrTypeInst;
  8009. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8010. {
  8011. inPropSet = true;
  8012. if (autoComplete != NULL)
  8013. autoComplete->CheckNode(assignExpr->mLeft);
  8014. String findName = assignExpr->mLeft->ToString();
  8015. BfPropertyDef* bestProp = NULL;
  8016. BfTypeInstance* bestPropTypeInst = NULL;
  8017. BfFieldDef* bestField = NULL;
  8018. BfTypeInstance* bestFieldTypeInst = NULL;
  8019. auto checkTypeInst = attrTypeInst;
  8020. while (checkTypeInst != NULL)
  8021. {
  8022. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8023. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8024. {
  8025. if (prop->mName == findName)
  8026. {
  8027. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8028. {
  8029. bestProp = prop;
  8030. bestPropTypeInst = checkTypeInst;
  8031. }
  8032. }
  8033. }
  8034. for (auto field : checkTypeInst->mTypeDef->mFields)
  8035. {
  8036. if (field->mName == findName)
  8037. {
  8038. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8039. {
  8040. bestField = field;
  8041. bestFieldTypeInst = checkTypeInst;
  8042. }
  8043. }
  8044. }
  8045. if ((bestProp != NULL) || (bestField != NULL))
  8046. break;
  8047. checkTypeInst = checkTypeInst->mBaseType;
  8048. }
  8049. bool handledExpr = false;
  8050. if (bestField != NULL)
  8051. {
  8052. handledExpr = true;
  8053. if (mCompiler->mResolvePassData != NULL)
  8054. {
  8055. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8056. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8057. {
  8058. autoComplete->mDefField = bestField;
  8059. autoComplete->mDefType = attrTypeDef;
  8060. }
  8061. }
  8062. if (bestField->mProtection != BfProtection_Public)
  8063. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8064. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8065. BfCustomAttributeSetField setField;
  8066. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8067. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8068. if (assignExpr->mRight != NULL)
  8069. {
  8070. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8071. if (result)
  8072. {
  8073. CurrentAddToConstHolder(result.mValue);
  8074. setField.mParam = result;
  8075. customAttribute.mSetField.push_back(setField);
  8076. }
  8077. }
  8078. }
  8079. else if (bestProp == NULL)
  8080. {
  8081. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8082. }
  8083. else
  8084. {
  8085. BfMethodDef* setMethod = NULL;
  8086. for (auto methodDef : bestProp->mMethods)
  8087. {
  8088. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8089. {
  8090. setMethod = methodDef;
  8091. break;
  8092. }
  8093. }
  8094. if (setMethod == NULL)
  8095. {
  8096. Fail("Property has no setter", assignExpr->mLeft);
  8097. }
  8098. else
  8099. {
  8100. if (mCompiler->mResolvePassData != NULL)
  8101. {
  8102. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8103. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8104. {
  8105. autoComplete->mDefProp = bestProp;
  8106. autoComplete->mDefType = attrTypeDef;
  8107. }
  8108. }
  8109. handledExpr = true;
  8110. if (bestProp->mProtection != BfProtection_Public)
  8111. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8112. BfResolvedArg resolvedArg;
  8113. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8114. BfCustomAttributeSetProperty setProperty;
  8115. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8116. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8117. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8118. if (methodInstance.mMethodInstance != NULL)
  8119. {
  8120. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8121. if (assignExpr->mRight != NULL)
  8122. {
  8123. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8124. if (result)
  8125. {
  8126. BF_ASSERT(result.mType == propType);
  8127. CurrentAddToConstHolder(result.mValue);
  8128. setProperty.mParam = result;
  8129. customAttribute.mSetProperties.push_back(setProperty);
  8130. }
  8131. }
  8132. }
  8133. }
  8134. }
  8135. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8136. constResolver.Resolve(assignExpr->mRight);
  8137. }
  8138. else
  8139. {
  8140. if (inPropSet)
  8141. {
  8142. Fail("Named attribute argument expected", arg); // CS1016
  8143. }
  8144. BfDeferEvalChecker deferEvalChecker;
  8145. arg->Accept(&deferEvalChecker);
  8146. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8147. BfResolvedArg resolvedArg;
  8148. resolvedArg.mExpression = arg;
  8149. if (deferParamEval)
  8150. {
  8151. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8152. }
  8153. else
  8154. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8155. if (!inPropSet)
  8156. argValues.push_back(resolvedArg);
  8157. }
  8158. if (autoComplete != NULL)
  8159. autoComplete->mShowAttributeProperties = NULL;
  8160. }
  8161. auto wasCapturingMethodInfo = false;
  8162. if (autoComplete != NULL)
  8163. {
  8164. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8165. if (attributesDirective->mCtorOpenParen != NULL)
  8166. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8167. }
  8168. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8169. attrTypeDef = attrTypeInst->mTypeDef;
  8170. bool success = true;
  8171. bool isFailurePass = false;
  8172. for (int pass = 0; pass < 2; pass++)
  8173. {
  8174. bool isFailurePass = pass == 1;
  8175. for (auto checkMethod : attrTypeDef->mMethods)
  8176. {
  8177. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8178. continue; // Don't match private default ctor if there's a user-defined one
  8179. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8180. continue;
  8181. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8182. continue;
  8183. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8184. }
  8185. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8186. break;
  8187. }
  8188. if (autoComplete != NULL)
  8189. {
  8190. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8191. {
  8192. autoComplete->mIsCapturingMethodMatchInfo = true;
  8193. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8194. }
  8195. else
  8196. autoComplete->mIsCapturingMethodMatchInfo = false;
  8197. }
  8198. if (methodMatcher.mBestMethodDef == NULL)
  8199. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8200. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8201. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8202. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8203. {
  8204. Fail("Custom attribute circular reference", attributesDirective);
  8205. }
  8206. if (mCurTypeInstance != NULL)
  8207. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8208. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8209. success = false;
  8210. for (auto& arg : argValues)
  8211. {
  8212. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8213. {
  8214. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8215. constResolver.Resolve(expr);
  8216. }
  8217. }
  8218. // Move all those to the constHolder
  8219. for (auto& ctorArg : customAttribute.mCtorArgs)
  8220. {
  8221. CurrentAddToConstHolder(ctorArg);
  8222. }
  8223. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8224. {
  8225. targetOverride = BfAttributeTargets_ReturnValue;
  8226. if (attrTarget != BfAttributeTargets_Method)
  8227. {
  8228. 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.",
  8229. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8230. }
  8231. success = false;
  8232. }
  8233. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8234. {
  8235. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8236. {
  8237. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8238. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8239. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8240. if (success)
  8241. {
  8242. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8243. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8244. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8245. }
  8246. }
  8247. else
  8248. {
  8249. // Failed - ignore
  8250. success = false;
  8251. }
  8252. }
  8253. if (success)
  8254. {
  8255. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8256. {
  8257. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8258. {
  8259. if (prevCustomAttribute.mType == attrTypeInst)
  8260. {
  8261. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8262. }
  8263. }
  8264. }
  8265. }
  8266. if (success)
  8267. {
  8268. customAttributes->mAttributes.push_back(customAttribute);
  8269. }
  8270. }
  8271. ValidateCustomAttributes(customAttributes, attrTarget);
  8272. }
  8273. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8274. {
  8275. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8276. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8277. return customAttributes;
  8278. }
  8279. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8280. {
  8281. if (mCurTypeInstance->mCustomAttributes != NULL)
  8282. {
  8283. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8284. {
  8285. String typeName = TypeToString(customAttribute.mType);
  8286. if (typeName == "System.PackedAttribute")
  8287. {
  8288. isPacked = true;
  8289. }
  8290. else if (typeName == "System.UnionAttribute")
  8291. {
  8292. isUnion = true;
  8293. }
  8294. else if (typeName == "System.CReprAttribute")
  8295. {
  8296. isCRepr = true;
  8297. isOrdered = true;
  8298. }
  8299. else if (typeName == "System.OrderedAttribute")
  8300. {
  8301. isOrdered = true;
  8302. }
  8303. else if (typeName == "System.AlwaysIncludeAttribute")
  8304. {
  8305. for (auto setProp : customAttribute.mSetProperties)
  8306. {
  8307. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8308. if (propertyDef->mName == "AssumeInstantiated")
  8309. {
  8310. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8311. if ((constant != NULL) && (constant->mBool))
  8312. mCurTypeInstance->mHasBeenInstantiated = true;
  8313. }
  8314. }
  8315. }
  8316. }
  8317. }
  8318. }
  8319. // Checking to see if we're an attribute or not
  8320. void BfModule::ProcessCustomAttributeData()
  8321. {
  8322. bool isAttribute = false;
  8323. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8324. while (checkTypeInst != NULL)
  8325. {
  8326. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8327. isAttribute = true;
  8328. checkTypeInst = checkTypeInst->mBaseType;
  8329. }
  8330. if (!isAttribute)
  8331. return;
  8332. auto attributeData = new BfAttributeData();
  8333. bool hasCustomAttribute = false;
  8334. if (mCurTypeInstance->mCustomAttributes != NULL)
  8335. {
  8336. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8337. {
  8338. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8339. {
  8340. if (customAttribute.mCtorArgs.size() > 0)
  8341. {
  8342. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8343. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8344. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8345. }
  8346. for (auto& setProp : customAttribute.mSetProperties)
  8347. {
  8348. BfPropertyDef* propDef = setProp.mPropertyRef;
  8349. if (propDef->mName == "AllowMultiple")
  8350. {
  8351. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8352. if (constant != NULL)
  8353. attributeData->mAllowMultiple = constant->mBool;
  8354. }
  8355. else if (propDef->mName == "Inherited")
  8356. {
  8357. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8358. if (constant != NULL)
  8359. attributeData->mInherited = constant->mBool;
  8360. }
  8361. else if (propDef->mName == "ValidOn")
  8362. {
  8363. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8364. if (constant != NULL)
  8365. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8366. }
  8367. }
  8368. hasCustomAttribute = true;
  8369. }
  8370. }
  8371. }
  8372. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8373. {
  8374. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8375. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8376. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8377. }
  8378. mCurTypeInstance->mAttributeData = attributeData;
  8379. }
  8380. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8381. {
  8382. auto constant = constHolder->GetConstant(irValue);
  8383. if (constant == NULL)
  8384. return false;
  8385. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8386. return false;
  8387. int stringId = constant->mInt32;
  8388. BfStringPoolEntry* entry = NULL;
  8389. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8390. {
  8391. str = entry->mString;
  8392. }
  8393. else
  8394. {
  8395. BF_DBG_FATAL("Failed to find string by id");
  8396. }
  8397. return true;
  8398. }
  8399. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8400. {
  8401. BfVariant variant;
  8402. variant.mTypeCode = BfTypeCode_None;
  8403. BfType* primType = NULL;
  8404. if (value.mType->IsPrimitiveType())
  8405. primType = (BfPrimitiveType*)value.mType;
  8406. else if (value.mType->IsTypedPrimitive())
  8407. primType = value.mType->GetUnderlyingType();
  8408. if (primType)
  8409. {
  8410. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8411. if (constant != NULL)
  8412. {
  8413. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8414. {
  8415. variant.mTypeCode = BfTypeCode_Let;
  8416. return variant;
  8417. }
  8418. switch (constant->mTypeCode)
  8419. {
  8420. case BfTypeCode_Int8:
  8421. case BfTypeCode_UInt8:
  8422. case BfTypeCode_Int16:
  8423. case BfTypeCode_UInt16:
  8424. case BfTypeCode_Int32:
  8425. case BfTypeCode_UInt32:
  8426. case BfTypeCode_Int64:
  8427. case BfTypeCode_UInt64:
  8428. case BfTypeCode_IntPtr:
  8429. case BfTypeCode_UIntPtr:
  8430. case BfTypeCode_IntUnknown:
  8431. case BfTypeCode_UIntUnknown:
  8432. case BfTypeCode_Single:
  8433. case BfTypeCode_Double:
  8434. case BfTypeCode_Char8:
  8435. case BfTypeCode_Char16:
  8436. case BfTypeCode_Char32:
  8437. variant.mTypeCode = constant->mTypeCode;
  8438. variant.mInt64 = constant->mInt64;
  8439. break;
  8440. default:
  8441. if (refNode != NULL)
  8442. Fail("Invalid const expression type", refNode);
  8443. break;
  8444. }
  8445. }
  8446. }
  8447. return variant;
  8448. }
  8449. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8450. {
  8451. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8452. {
  8453. auto elementType = typedValue.mType->GetUnderlyingType();
  8454. if (typedValue.IsAddr())
  8455. {
  8456. if (elementType->IsValuelessType())
  8457. {
  8458. BF_ASSERT(!typedValue.mValue);
  8459. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8460. }
  8461. else
  8462. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8463. }
  8464. else
  8465. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8466. if (typedValue.mType->IsValuelessType())
  8467. {
  8468. BF_ASSERT(typedValue.mValue.IsFake());
  8469. }
  8470. }
  8471. return typedValue;
  8472. }
  8473. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8474. {
  8475. if (!typedValue.IsAddr())
  8476. return typedValue;
  8477. if (typedValue.mType->IsValuelessType())
  8478. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8479. BfIRValue loadedVal = typedValue.mValue;
  8480. if (loadedVal)
  8481. {
  8482. /*if (isVolatile)
  8483. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8484. PopulateType(typedValue.mType, BfPopulateType_Data);
  8485. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8486. }
  8487. return BfTypedValue(loadedVal, typedValue.mType, false);
  8488. }
  8489. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8490. {
  8491. if (typedValue.IsSplat())
  8492. return AggregateSplat(typedValue);
  8493. if (typedValue.IsAddr())
  8494. return LoadValue(typedValue);
  8495. return typedValue;
  8496. }
  8497. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8498. {
  8499. if (!typedValue.IsSplat())
  8500. return typedValue;
  8501. if (typedValue.mType->IsValuelessType())
  8502. return typedValue;
  8503. int elementIdx = 0;
  8504. auto _ExtractValue = [&](BfType* checkType)
  8505. {
  8506. if (valueArrPtr != NULL)
  8507. return valueArrPtr[elementIdx++];
  8508. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8509. };
  8510. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8511. {
  8512. if (checkType->IsStruct())
  8513. {
  8514. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8515. auto checkTypeInstance = checkType->ToTypeInstance();
  8516. if (checkTypeInstance->mBaseType != NULL)
  8517. {
  8518. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8519. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8520. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8521. }
  8522. if (checkTypeInstance->mIsUnion)
  8523. {
  8524. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8525. if (!unionInnerType->IsValuelessType())
  8526. {
  8527. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8528. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8529. }
  8530. if (checkTypeInstance->IsEnum())
  8531. {
  8532. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8533. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8534. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8535. }
  8536. }
  8537. else
  8538. {
  8539. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8540. {
  8541. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8542. if (fieldInstance->mDataIdx >= 0)
  8543. {
  8544. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8545. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8546. }
  8547. }
  8548. }
  8549. return curValue;
  8550. }
  8551. else if (checkType->IsMethodRef())
  8552. {
  8553. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8554. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8555. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8556. {
  8557. BfIRValue fieldValue;
  8558. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8559. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8560. {
  8561. fieldValue = checkTypeLambda(checkType);
  8562. }
  8563. else
  8564. {
  8565. fieldValue = _ExtractValue(checkType);
  8566. }
  8567. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8568. }
  8569. return curValue;
  8570. }
  8571. else if (!checkType->IsValuelessType())
  8572. {
  8573. return _ExtractValue(checkType);
  8574. }
  8575. return BfIRValue();
  8576. };
  8577. BfIRValue value = checkTypeLambda(typedValue.mType);
  8578. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8579. }
  8580. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8581. {
  8582. if (!typedValue.IsSplat())
  8583. return;
  8584. if (typedValue.mType->IsValuelessType())
  8585. return;
  8586. /*static int sCallIdx = 0;
  8587. if (!mCompiler->mIsResolveOnly)
  8588. sCallIdx++;
  8589. int callIdx = sCallIdx;*/
  8590. int elementIdx = 0;
  8591. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8592. {
  8593. if (checkType->IsStruct())
  8594. {
  8595. auto checkTypeInstance = checkType->ToTypeInstance();
  8596. if (checkTypeInstance->mBaseType != NULL)
  8597. {
  8598. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8599. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8600. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8601. }
  8602. if (checkTypeInstance->mIsUnion)
  8603. {
  8604. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8605. if (!unionInnerType->IsValuelessType())
  8606. {
  8607. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8608. checkTypeLambda(unionInnerType, fieldAddrVal);
  8609. }
  8610. if (checkTypeInstance->IsEnum())
  8611. {
  8612. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8613. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8614. checkTypeLambda(dscrType, fieldAddrVal);
  8615. }
  8616. }
  8617. else
  8618. {
  8619. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8620. {
  8621. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8622. if (fieldInstance->mDataIdx >= 0)
  8623. {
  8624. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8625. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8626. }
  8627. }
  8628. }
  8629. }
  8630. else if (checkType->IsMethodRef())
  8631. {
  8632. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8633. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8634. {
  8635. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8636. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8637. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8638. {
  8639. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8640. }
  8641. else
  8642. {
  8643. // static int sItrCount = 0;
  8644. // sItrCount++;
  8645. // int curItr = sItrCount;
  8646. // if (curItr == 1)
  8647. // {
  8648. // NOP;
  8649. // }
  8650. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8651. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8652. }
  8653. }
  8654. }
  8655. else if (!checkType->IsValuelessType())
  8656. {
  8657. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8658. mBfIRBuilder->CreateStore(val, curAddrVal);
  8659. }
  8660. };
  8661. checkTypeLambda(typedValue.mType, addrVal);
  8662. }
  8663. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8664. {
  8665. bool wasReadOnly = typedVal.IsReadOnly();
  8666. if ((typedVal.mType->IsValueType()) &&
  8667. (!typedVal.mType->IsValuelessType()))
  8668. {
  8669. wasReadOnly = true; // Any non-addr is implicitly read-only
  8670. //static int gCallIdx = 0;
  8671. if (typedVal.IsAddr())
  8672. return typedVal;
  8673. BfType* type = typedVal.mType;
  8674. PopulateType(type);
  8675. auto tempVar = CreateAlloca(type);
  8676. if (typedVal.IsSplat())
  8677. AggregateSplatIntoAddr(typedVal, tempVar);
  8678. else
  8679. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8680. return BfTypedValue(tempVar, type,
  8681. typedVal.IsThis() ?
  8682. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8683. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8684. }
  8685. return LoadValue(typedVal);
  8686. }
  8687. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8688. {
  8689. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8690. typedValue.mKind = BfTypedValueKind_Addr;
  8691. return typedValue;
  8692. }
  8693. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8694. {
  8695. BfIRValue val;
  8696. if (typedValue.mValue.IsArg())
  8697. {
  8698. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8699. if (isAddr != NULL)
  8700. {
  8701. if (wantType != NULL)
  8702. *isAddr = wantType->IsComposite();
  8703. else
  8704. *isAddr = false;
  8705. }
  8706. else if (wantType->IsComposite())
  8707. val = mBfIRBuilder->CreateLoad(val);
  8708. }
  8709. if (!val)
  8710. {
  8711. auto checkMethodState = mCurMethodState;
  8712. while (checkMethodState != NULL)
  8713. {
  8714. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8715. {
  8716. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8717. if (decompAddr == typedValue.mValue)
  8718. {
  8719. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8720. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8721. {
  8722. // This is really backing for a POINTER to a composite inside a methodRef
  8723. val = mBfIRBuilder->CreateLoad(val);
  8724. }
  8725. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8726. {
  8727. *isAddr = true;
  8728. return val;
  8729. }
  8730. else
  8731. {
  8732. val = mBfIRBuilder->CreateLoad(val);
  8733. break;
  8734. }
  8735. }
  8736. }
  8737. if (val)
  8738. break;
  8739. checkMethodState = checkMethodState->mPrevMethodState;
  8740. }
  8741. }
  8742. if (val)
  8743. {
  8744. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8745. {
  8746. BF_ASSERT(wantType != NULL);
  8747. if (wantType != NULL)
  8748. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8749. }
  8750. return val;
  8751. }
  8752. BF_FATAL("Splat not found");
  8753. return BfIRValue();
  8754. }
  8755. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8756. {
  8757. int useFieldIdx = fieldIdx;
  8758. BfType* fieldType = NULL;
  8759. if (fieldInstance != NULL)
  8760. {
  8761. fieldType = fieldInstance->mResolvedType;
  8762. if (typedValue.mType->IsUnion())
  8763. {
  8764. if (fieldIdx == 1)
  8765. {
  8766. if (typedValue.IsSplat())
  8767. {
  8768. BfTypedValue innerVal = typedValue;
  8769. innerVal.mType = fieldType;
  8770. return innerVal;
  8771. }
  8772. }
  8773. }
  8774. }
  8775. else
  8776. {
  8777. if (typedValue.mType->IsPayloadEnum())
  8778. {
  8779. auto typeInst = typedValue.mType->ToTypeInstance();
  8780. if (fieldIdx == 1)
  8781. fieldType = typeInst->GetUnionInnerType();
  8782. else if (fieldIdx == 2)
  8783. {
  8784. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8785. }
  8786. }
  8787. else if (typedValue.mType->IsUnion())
  8788. {
  8789. if (fieldIdx == 1)
  8790. {
  8791. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8792. if (typedValue.IsSplat())
  8793. {
  8794. BfTypedValue innerVal = typedValue;
  8795. innerVal.mType = fieldType;
  8796. return innerVal;
  8797. }
  8798. }
  8799. }
  8800. }
  8801. BF_ASSERT(typedValue.mType->IsStruct());
  8802. if (typedValue.IsSplat())
  8803. {
  8804. if (typedValue.mType->IsPayloadEnum())
  8805. {
  8806. if (fieldIdx == 1)
  8807. {
  8808. // Payload
  8809. auto typeInst = typedValue.mType->ToTypeInstance();
  8810. auto unionInnerType = typeInst->GetUnionInnerType();
  8811. bool isAddr = false;
  8812. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8813. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8814. }
  8815. if (fieldIdx == 2)
  8816. {
  8817. // Discriminator
  8818. auto typeInst = typedValue.mType->ToTypeInstance();
  8819. auto unionInnerType = typeInst->GetUnionInnerType();
  8820. auto dscrType = typeInst->GetDiscriminatorType();
  8821. int argIdx = typedValue.mValue.mId;
  8822. int componentIdx = 0;
  8823. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8824. bool isAddr;
  8825. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8826. return BfTypedValue(irVal, dscrType, isAddr);
  8827. }
  8828. }
  8829. int componentIdx = 0;
  8830. BfTypedValue retVal;
  8831. BfFieldInstance* wantFieldInstance = fieldInstance;
  8832. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8833. {
  8834. if (checkType->IsStruct())
  8835. {
  8836. auto checkTypeInstance = checkType->ToTypeInstance();
  8837. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8838. {
  8839. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8840. fieldType = checkTypeInstance->GetUnionInnerType();
  8841. checkTypeLambda(fieldType);
  8842. if (checkType->IsEnum())
  8843. {
  8844. // Past discriminator...
  8845. componentIdx++;
  8846. }
  8847. return;
  8848. }
  8849. if (checkTypeInstance->mBaseType != NULL)
  8850. checkTypeLambda(checkTypeInstance->mBaseType);
  8851. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8852. {
  8853. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8854. if (fieldInstance == wantFieldInstance)
  8855. {
  8856. bool isAddr = false;
  8857. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8858. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8859. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8860. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8861. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8862. {
  8863. retVal = LoadValue(retVal);
  8864. }
  8865. break;
  8866. }
  8867. if (fieldInstance->mDataIdx >= 0)
  8868. checkTypeLambda(fieldInstance->GetResolvedType());
  8869. }
  8870. }
  8871. else if (!checkType->IsValuelessType())
  8872. {
  8873. componentIdx++;
  8874. //argIdx++;
  8875. }
  8876. };
  8877. checkTypeLambda(typedValue.mType);
  8878. BF_ASSERT(retVal);
  8879. return retVal;
  8880. }
  8881. if (typedValue.IsAddr())
  8882. {
  8883. BF_ASSERT(fieldType != NULL);
  8884. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8885. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8886. }
  8887. else
  8888. {
  8889. BF_ASSERT(fieldType != NULL);
  8890. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8891. }
  8892. }
  8893. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8894. {
  8895. if (typedValue.IsAddr())
  8896. {
  8897. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8898. return mBfIRBuilder->CreateLoad(addrVal);
  8899. }
  8900. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8901. }
  8902. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8903. {
  8904. if (elementType->IsSizeAligned())
  8905. {
  8906. if (isElementIndex)
  8907. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8908. else
  8909. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8910. }
  8911. auto ptrType = CreatePointerType(elementType);
  8912. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8913. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8914. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8915. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8916. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8917. }
  8918. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8919. {
  8920. if (elementType->IsSizeAligned())
  8921. {
  8922. if (isElementIndex)
  8923. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  8924. else
  8925. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8926. }
  8927. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  8928. }
  8929. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  8930. {
  8931. if (modifyType == NULL)
  8932. modifyType = "modify";
  8933. if (typedValue.mType->IsVar())
  8934. return true;
  8935. if (typedValue.IsReadOnly())
  8936. {
  8937. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  8938. return false;
  8939. }
  8940. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  8941. {
  8942. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8943. return false;
  8944. }
  8945. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  8946. {
  8947. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8948. return false;
  8949. }
  8950. return true;
  8951. }
  8952. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  8953. {
  8954. if (methodA->mMethodDef->mIsLocalMethod)
  8955. {
  8956. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  8957. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  8958. if (sepPosA != sepPosB)
  8959. return false;
  8960. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  8961. return false;
  8962. }
  8963. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  8964. return false;
  8965. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  8966. return false;
  8967. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  8968. {
  8969. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  8970. return false;
  8971. }
  8972. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  8973. {
  8974. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  8975. return false;
  8976. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  8977. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  8978. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  8979. return false;
  8980. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  8981. return false;
  8982. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  8983. {
  8984. if (methodA->mReturnType != methodB->mReturnType)
  8985. return false;
  8986. }
  8987. }
  8988. int implicitParamCountA = methodA->GetImplicitParamCount();
  8989. int implicitParamCountB = methodB->GetImplicitParamCount();
  8990. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  8991. return false;
  8992. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  8993. return false;
  8994. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  8995. {
  8996. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  8997. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  8998. return false;
  8999. }
  9000. // Compare generic params. Generic params are part of the method signature here
  9001. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9002. return false;
  9003. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9004. {
  9005. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9006. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9007. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9008. return false;
  9009. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9010. return false;
  9011. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9012. return false;
  9013. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9014. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9015. return false;
  9016. }
  9017. return true;
  9018. }
  9019. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9020. {
  9021. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9022. return false;
  9023. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9024. return false;
  9025. if (iMethodInst->mMethodDef->mIsOperator)
  9026. {
  9027. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9028. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9029. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9030. return false;
  9031. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9032. return false;
  9033. }
  9034. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9035. return false;
  9036. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9037. {
  9038. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9039. return false;
  9040. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9041. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9042. if (iParamType->IsSelf())
  9043. {
  9044. if (methodParamType != methodInstance->GetOwner())
  9045. return false;
  9046. }
  9047. else if (!iParamType->IsGenericParam())
  9048. {
  9049. if (methodParamType != iParamType)
  9050. return false;
  9051. }
  9052. else
  9053. {
  9054. if (!methodParamType->IsGenericParam())
  9055. return false;
  9056. auto genericParamType = (BfGenericParamType*)methodParamType;
  9057. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9058. return false;
  9059. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9060. bool hadInterface = false;
  9061. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9062. if (interfaceConstraint == iParamType)
  9063. hadInterface = true;
  9064. if (!hadInterface)
  9065. return false;
  9066. }
  9067. }
  9068. return true;
  9069. }
  9070. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9071. {
  9072. BfMethodInstance* methodInstance = methodRef;
  9073. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9074. {
  9075. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9076. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9077. {
  9078. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9079. BfMethodRef methodRef = methodInstance;
  9080. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9081. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9082. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9083. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9084. (mIsReified))
  9085. {
  9086. specializedMethodRefInfo->mHasReifiedRef = true;
  9087. }
  9088. }
  9089. }
  9090. }
  9091. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9092. {
  9093. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9094. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9095. if (mBfIRBuilder == NULL)
  9096. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9097. if (methodInstance->GetOwner()->IsFunction())
  9098. {
  9099. // No actual ref needed- not an actual generated function
  9100. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9101. }
  9102. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9103. if (!isGenFunction)
  9104. AddMethodReference(methodInstance, flags);
  9105. if (mBfIRBuilder->mIgnoreWrites)
  9106. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9107. if (mCompiler->IsSkippingExtraResolveChecks())
  9108. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9109. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9110. {
  9111. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9112. }
  9113. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9114. BfMethodRef methodRef = methodInstance;
  9115. if (isInlined)
  9116. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9117. else
  9118. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9119. if (!isGenFunction)
  9120. {
  9121. BfIRValue* irFuncPtr = NULL;
  9122. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9123. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9124. }
  9125. if (mAwaitingInitFinish)
  9126. FinishInit();
  9127. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9128. if (!isGenFunction)
  9129. mFuncReferences[methodRef] = func;
  9130. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9131. if ((isInlined) && (!mIsScratchModule))
  9132. {
  9133. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9134. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9135. // type instance
  9136. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9137. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9138. for (auto ownedTypeInst : mOwnedTypeInstances)
  9139. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9140. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9141. {
  9142. mIncompleteMethodCount++;
  9143. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9144. inlineMethodRequest->mType = methodInstance->GetOwner();
  9145. inlineMethodRequest->mFromModule = this;
  9146. inlineMethodRequest->mFunc = func;
  9147. inlineMethodRequest->mFromModuleRevision = mRevision;
  9148. inlineMethodRequest->mMethodInstance = methodInstance;
  9149. BF_ASSERT(mIsModuleMutable);
  9150. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9151. }
  9152. }
  9153. return BfModuleMethodInstance(methodInstance, func);
  9154. }
  9155. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9156. {
  9157. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9158. if (HasCompiledOutput())
  9159. {
  9160. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  9161. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  9162. {
  9163. StartExtension();
  9164. }
  9165. }
  9166. else
  9167. {
  9168. EnsureIRBuilder();
  9169. }
  9170. BfModule* declareModule = this;
  9171. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9172. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9173. declareModule = declareModule->mParentModule;
  9174. // Check for attributes
  9175. if (typeInst == mContext->mBfObjectType)
  9176. {
  9177. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9178. if (methodDecl != NULL)
  9179. {
  9180. auto attributesDirective = methodDecl->mAttributes;
  9181. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9182. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9183. {
  9184. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9185. }
  9186. }
  9187. }
  9188. else
  9189. {
  9190. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9191. GetMethodCustomAttributes(methodInstance);
  9192. }
  9193. BF_ASSERT(mModuleOptions == NULL);
  9194. if (methodInstance->GetCustomAttributes() != NULL)
  9195. {
  9196. auto project = typeInst->mTypeDef->mProject;
  9197. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9198. BfModuleOptions wantOptions = moduleOptions;
  9199. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9200. if (typeOptions != NULL)
  9201. {
  9202. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9203. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9204. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9205. }
  9206. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9207. {
  9208. StringT<128> attrName;
  9209. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9210. {
  9211. attrName.Clear();
  9212. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9213. Array<int>* arrPtr;
  9214. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9215. {
  9216. for (auto optionsIdx : *arrPtr)
  9217. {
  9218. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9219. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9220. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9221. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9222. }
  9223. }
  9224. }
  9225. }
  9226. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9227. {
  9228. auto lastCheckModule = this;
  9229. auto checkModule = this->mNextAltModule;
  9230. while (checkModule != NULL)
  9231. {
  9232. if (*checkModule->mModuleOptions == wantOptions)
  9233. {
  9234. declareModule = checkModule;
  9235. break;
  9236. }
  9237. lastCheckModule = checkModule;
  9238. checkModule = checkModule->mNextAltModule;
  9239. }
  9240. // Not found?
  9241. if (declareModule == this)
  9242. {
  9243. String specModuleName = mModuleName + "@@";
  9244. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9245. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9246. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9247. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9248. declareModule = new BfModule(mContext, specModuleName);
  9249. declareModule->mProject = project;
  9250. declareModule->mModuleOptions = new BfModuleOptions();
  9251. *declareModule->mModuleOptions = wantOptions;
  9252. declareModule->mParentModule = lastCheckModule;
  9253. declareModule->Init();
  9254. lastCheckModule->mNextAltModule = declareModule;
  9255. }
  9256. }
  9257. }
  9258. return declareModule;
  9259. }
  9260. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9261. {
  9262. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9263. {
  9264. // Don't bother inlining for resolve-only
  9265. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9266. }
  9267. bool processNow = false;
  9268. bool keepInCurrentModule = false;
  9269. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9270. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9271. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9272. {
  9273. return BfModuleMethodInstance();
  9274. }
  9275. if (methodDef->mIsLocalMethod)
  9276. {
  9277. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9278. BfLocalMethod* localMethod;
  9279. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9280. {
  9281. // Handle the def in the correct method state
  9282. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9283. }
  9284. BF_FATAL("Cannot find local method");
  9285. return BfModuleMethodInstance();
  9286. }
  9287. #ifdef _DEBUG
  9288. for (auto arg : methodGenericArguments)
  9289. BF_ASSERT(!arg->IsVar());
  9290. #endif
  9291. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9292. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9293. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9294. // a FinishInit
  9295. if ((typeInst->IsIncomplete()) &&
  9296. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9297. {
  9298. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9299. // for resolve-only because we don't differentiate between reified/unreified there
  9300. PopulateType(typeInst, BfPopulateType_Full);
  9301. }
  9302. bool tryModuleMethodLookup = false;
  9303. BfModuleMethodInstance moduleMethodInst;
  9304. BfModule* instModule = typeInst->mModule;
  9305. if (keepInCurrentModule)
  9306. {
  9307. // Stay here
  9308. instModule = this;
  9309. }
  9310. if (this == mContext->mUnreifiedModule)
  9311. {
  9312. // Stay in this 'resolve only' module here
  9313. }
  9314. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9315. {
  9316. BF_ASSERT(this == mContext->mUnreifiedModule);
  9317. }
  9318. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9319. {
  9320. BF_ASSERT(instModule == mParentModule);
  9321. }
  9322. else if (instModule != this)
  9323. {
  9324. if ((!mIsReified) && (instModule->mIsReified))
  9325. {
  9326. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9327. // A resolve-only module is specializing a method from a type in a reified module,
  9328. // we need to take care that this doesn't cause anything new to become reified
  9329. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9330. }
  9331. else
  9332. {
  9333. if ((mIsReified) && (!instModule->mIsReified))
  9334. {
  9335. if (!instModule->mReifyQueued)
  9336. {
  9337. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9338. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9339. mContext->mReifyModuleWorkList.Add(instModule);
  9340. instModule->mReifyQueued = true;
  9341. }
  9342. // This ensures that the method will actually be created when it gets reified
  9343. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9344. specializationRequest->mFromModule = typeInst->mModule;
  9345. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9346. specializationRequest->mMethodDef = methodDef;
  9347. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9348. specializationRequest->mType = typeInst;
  9349. }
  9350. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9351. // Not extern
  9352. // Create the instance in the proper module and then create a reference in this one
  9353. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9354. tryModuleMethodLookup = true;
  9355. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9356. {
  9357. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9358. }
  9359. }
  9360. }
  9361. if (tryModuleMethodLookup)
  9362. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9363. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9364. {
  9365. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9366. if (moduleMethodInstance)
  9367. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9368. return moduleMethodInst;
  9369. }
  9370. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9371. bool hadConcreteInterfaceGenericArgument = false;
  9372. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9373. isReified = false;
  9374. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9375. {
  9376. isReified = false;
  9377. }
  9378. BfTypeVector sanitizedMethodGenericArguments;
  9379. Array<BfProject*> projectList;
  9380. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9381. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9382. isUnspecializedPass = false;
  9383. // 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
  9384. bool isExternalExtensionMethod = false;
  9385. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9386. {
  9387. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9388. {
  9389. auto specProject = methodDef->mDeclaringType->mProject;
  9390. isExternalExtensionMethod = true;
  9391. if (typeInst->IsGenericTypeInstance())
  9392. {
  9393. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9394. if (genericTypeInst->mProjectsReferenced.empty())
  9395. genericTypeInst->GenerateProjectsReferenced();
  9396. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9397. {
  9398. // This is a generic type where a generic param is already confined to the project in question
  9399. isExternalExtensionMethod = false;
  9400. }
  9401. }
  9402. if (isExternalExtensionMethod)
  9403. {
  9404. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9405. projectList.push_back(methodDef->mDeclaringType->mProject);
  9406. }
  9407. }
  9408. }
  9409. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9410. {
  9411. int typeProjectsCounts = 0;
  9412. if (typeInst->IsGenericTypeInstance())
  9413. {
  9414. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9415. if (genericTypeInst->mProjectsReferenced.empty())
  9416. genericTypeInst->GenerateProjectsReferenced();
  9417. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9418. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9419. }
  9420. else
  9421. {
  9422. typeProjectsCounts = 1;
  9423. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9424. }
  9425. isUnspecializedPass = true;
  9426. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9427. {
  9428. auto genericArgType = methodGenericArguments[genericArgIdx];
  9429. //BF_ASSERT(!genericArgType->IsRef());
  9430. if (genericArgType->IsConcreteInterfaceType())
  9431. {
  9432. hadConcreteInterfaceGenericArgument = true;
  9433. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9434. genericArgType = concreteInterfaceType->mInterface;
  9435. }
  9436. if (genericArgType->IsGenericParam())
  9437. {
  9438. auto genericParam = (BfGenericParamType*) genericArgType;
  9439. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9440. isUnspecializedPass = false;
  9441. }
  9442. else
  9443. {
  9444. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9445. isUnspecializedPass = false;
  9446. }
  9447. sanitizedMethodGenericArguments.push_back(genericArgType);
  9448. }
  9449. if ((int)projectList.size() > typeProjectsCounts)
  9450. {
  9451. // Just leave the new items
  9452. projectList.RemoveRange(0, typeProjectsCounts);
  9453. std::sort(projectList.begin(), projectList.end());
  9454. }
  9455. else
  9456. {
  9457. projectList.Clear();
  9458. }
  9459. }
  9460. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9461. BfMethodInstanceGroup* methodInstGroup = NULL;
  9462. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9463. {
  9464. BF_ASSERT(!typeInst->IsInterface());
  9465. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9466. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9467. {
  9468. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9469. // if (checkGroup.mDefault == NULL)
  9470. // {
  9471. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9472. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9473. // methodInstGroup = &checkGroup;
  9474. // break;
  9475. // }
  9476. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9477. {
  9478. methodInstGroup = &checkGroup;
  9479. break;
  9480. }
  9481. }
  9482. if (methodInstGroup == NULL)
  9483. {
  9484. // Allocate a new entry
  9485. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9486. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9487. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9488. methodInstGroup->mOwner = typeInst;
  9489. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9490. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9491. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9492. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9493. else
  9494. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9495. }
  9496. }
  9497. else
  9498. {
  9499. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9500. }
  9501. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9502. {
  9503. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9504. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9505. }
  9506. BfIRFunction prevIRFunc;
  9507. bool doingRedeclare = false;
  9508. BfMethodInstance* methodInstance = NULL;
  9509. auto _SetReified = [&]()
  9510. {
  9511. methodInstance->mIsReified = true;
  9512. };
  9513. if (lookupMethodGenericArguments.size() == 0)
  9514. {
  9515. methodInstance = methodInstGroup->mDefault;
  9516. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9517. {
  9518. MarkDerivedDirty(typeInst);
  9519. if (mIsScratchModule)
  9520. {
  9521. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9522. _SetReified();
  9523. CheckHotMethod(methodInstance, "");
  9524. }
  9525. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9526. {
  9527. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9528. // the specializations to handle that for us
  9529. return BfModuleMethodInstance(methodInstance);
  9530. }
  9531. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9532. {
  9533. if (methodDef->mIsAbstract)
  9534. {
  9535. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9536. _SetReified();
  9537. }
  9538. else
  9539. {
  9540. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9541. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9542. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9543. doingRedeclare = true;
  9544. mOnDemandMethodCount++;
  9545. }
  9546. }
  9547. else
  9548. {
  9549. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9550. // We haven't processed it yet
  9551. _SetReified();
  9552. CheckHotMethod(methodInstance, "");
  9553. if (methodInstance->mDeclModule == this)
  9554. {
  9555. if (methodInstance->mMethodProcessRequest != NULL)
  9556. {
  9557. // Disconnect method process request
  9558. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9559. }
  9560. }
  9561. else
  9562. {
  9563. if (methodInstance->mMethodProcessRequest != NULL)
  9564. {
  9565. // Disconnect method process request
  9566. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9567. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9568. methodInstance->mMethodProcessRequest = NULL;
  9569. }
  9570. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9571. {
  9572. // Add new request in proper module
  9573. methodInstance->mDeclModule = this;
  9574. }
  9575. else
  9576. {
  9577. if (methodInstance->mDeclModule == NULL)
  9578. {
  9579. //
  9580. }
  9581. else if (methodInstance->mDeclModule != this)
  9582. {
  9583. // Is from specialized module?
  9584. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9585. }
  9586. }
  9587. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9588. {
  9589. methodInstance->mIRFunction = BfIRFunction();
  9590. if (!mIsModuleMutable)
  9591. StartExtension();
  9592. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9593. {
  9594. StringT<128> mangledName;
  9595. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9596. bool isIntrinsic = false;
  9597. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9598. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9599. }
  9600. }
  9601. AddMethodToWorkList(methodInstance);
  9602. }
  9603. }
  9604. }
  9605. }
  9606. else
  9607. {
  9608. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9609. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9610. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9611. BfMethodInstance** methodInstancePtr = NULL;
  9612. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9613. {
  9614. methodInstance = *methodInstancePtr;
  9615. if ((isReified) && (!methodInstance->mIsReified))
  9616. {
  9617. MarkDerivedDirty(typeInst);
  9618. if (methodInstance->mHasBeenProcessed)
  9619. {
  9620. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9621. delete methodInstance;
  9622. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9623. methodInstance = NULL;
  9624. }
  9625. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9626. {
  9627. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9628. delete methodInstance;
  9629. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9630. methodInstance = NULL;
  9631. }
  9632. else
  9633. {
  9634. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9635. // We haven't processed it yet
  9636. _SetReified();
  9637. CheckHotMethod(methodInstance, "");
  9638. }
  9639. }
  9640. }
  9641. }
  9642. if ((methodInstance != NULL) && (!doingRedeclare))
  9643. {
  9644. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9645. {
  9646. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9647. BF_ASSERT(!methodInstance->mIsReified);*/
  9648. if (methodInstance->mIsReified != isReified)
  9649. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9650. if ((!isReified) &&
  9651. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9652. {
  9653. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9654. methodInstance->mIRFunction = BfIRFunction();
  9655. }
  9656. methodInstance->mIsReified = isReified;
  9657. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9658. {
  9659. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9660. }
  9661. if (!methodInstance->mMethodDef->mIsAbstract)
  9662. {
  9663. AddMethodToWorkList(methodInstance);
  9664. }
  9665. else
  9666. {
  9667. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9668. }
  9669. }
  9670. if (mExtensionCount > 0)
  9671. {
  9672. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9673. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9674. {
  9675. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9676. if ((methodInstance->mMethodDef->mName == "Unwrap") && (mModuleName == "System_Result_PTR_void"))
  9677. {
  9678. NOP;
  9679. }
  9680. if (mAwaitingInitFinish)
  9681. FinishInit();
  9682. // We need to refer to a function that was defined in a prior module
  9683. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9684. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9685. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9686. methodInstance->mDeclModule = this;
  9687. // Add this inlined def to ourselves
  9688. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9689. {
  9690. mIncompleteMethodCount++;
  9691. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9692. inlineMethodRequest->mType = typeInst;
  9693. inlineMethodRequest->mFromModule = this;
  9694. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9695. inlineMethodRequest->mFromModuleRevision = mRevision;
  9696. inlineMethodRequest->mMethodInstance = methodInstance;
  9697. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9698. BF_ASSERT(mIsModuleMutable);
  9699. }
  9700. }
  9701. }
  9702. if (mCompiler->IsSkippingExtraResolveChecks())
  9703. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9704. else
  9705. {
  9706. if (methodInstance->mDeclModule != this)
  9707. return ReferenceExternalMethodInstance(methodInstance, flags);
  9708. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9709. {
  9710. auto importKind = methodInstance->GetImportCallKind();
  9711. if (importKind != BfImportCallKind_None)
  9712. {
  9713. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9714. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9715. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9716. }
  9717. }
  9718. return BfModuleMethodInstance(methodInstance);
  9719. }
  9720. }
  9721. if (!doingRedeclare)
  9722. {
  9723. BfModule* specModule = NULL;
  9724. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9725. {
  9726. specModule = GetSpecializedMethodModule(projectList);
  9727. }
  9728. if ((specModule != NULL) && (specModule != this))
  9729. {
  9730. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9731. if (mAwaitingInitFinish)
  9732. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9733. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9734. }
  9735. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9736. {
  9737. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9738. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9739. }
  9740. }
  9741. if (methodInstance == NULL)
  9742. {
  9743. if (lookupMethodGenericArguments.size() == 0)
  9744. {
  9745. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9746. methodInstance = new BfMethodInstance();
  9747. methodInstGroup->mDefault = methodInstance;
  9748. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9749. }
  9750. else
  9751. {
  9752. BfMethodInstance** methodInstancePtr = NULL;
  9753. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9754. BF_ASSERT(added);
  9755. methodInstance = new BfMethodInstance();
  9756. *methodInstancePtr = methodInstance;
  9757. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9758. }
  9759. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9760. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9761. }
  9762. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9763. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9764. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9765. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9766. methodInstance->mMethodDef = methodDef;
  9767. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9768. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9769. methodInstance->mIsReified = isReified;
  9770. SetupMethodIdHash(methodInstance);
  9771. if (hadConcreteInterfaceGenericArgument)
  9772. methodInstance->mIgnoreBody = true;
  9773. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9774. {
  9775. methodInstance->mIsForeignMethodDef = true;
  9776. BF_ASSERT(foreignType != NULL);
  9777. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9778. }
  9779. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9780. {
  9781. if (!lookupMethodGenericArguments.empty())
  9782. {
  9783. auto compareType = lookupMethodGenericArguments[0];
  9784. PopulateType(compareType, BfPopulateType_Data);
  9785. if (compareType->IsSplattable())
  9786. methodInstance->mAlwaysInline = true;
  9787. }
  9788. }
  9789. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9790. {
  9791. // With extensions we can have multiple definitions of the same method
  9792. //methodInstance->mMangleWithIdx = true;
  9793. }
  9794. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9795. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9796. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9797. if (isUnspecializedPass)
  9798. {
  9799. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9800. {
  9801. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9802. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9803. }
  9804. }
  9805. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9806. {
  9807. if (!sanitizedMethodGenericArguments.IsEmpty())
  9808. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9809. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9810. {
  9811. Fail("Internal error");
  9812. BF_FATAL("Generic method argument counts mismatch");
  9813. return NULL;
  9814. }
  9815. for (auto genericArg : sanitizedMethodGenericArguments)
  9816. {
  9817. if (genericArg->IsPrimitiveType())
  9818. genericArg = GetWrappedStructType(genericArg);
  9819. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9820. if (genericArg->IsMethodRef())
  9821. {
  9822. auto methodRefType = (BfMethodRefType*)genericArg;
  9823. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9824. }
  9825. }
  9826. }
  9827. // Generic constraints
  9828. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9829. {
  9830. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9831. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9832. }
  9833. bool addToWorkList = !processNow;
  9834. if (mCompiler->GetAutoComplete() != NULL)
  9835. {
  9836. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9837. addToWorkList = false;
  9838. }
  9839. BF_ASSERT(declareModule != NULL);
  9840. methodInstance->mDeclModule = declareModule;
  9841. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9842. {
  9843. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9844. // of a reified module -
  9845. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9846. // BUT if we don't reify it then we have to remove the body after processing.
  9847. // 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
  9848. // the proper reified module.
  9849. declareModule = mContext->mUnreifiedModule;
  9850. }
  9851. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9852. {
  9853. BF_ASSERT(!methodInstance->mIsReified);
  9854. declareModule = mContext->mUnreifiedModule;
  9855. }
  9856. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9857. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9858. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9859. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9860. if (processNow)
  9861. {
  9862. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9863. ProcessMethod(methodInstance);
  9864. }
  9865. if (mCompiler->IsSkippingExtraResolveChecks())
  9866. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9867. return BfModuleMethodInstance(methodInstance);
  9868. }
  9869. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9870. {
  9871. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9872. if (methodInstance->mIsForeignMethodDef)
  9873. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9874. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9875. }
  9876. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9877. {
  9878. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9879. return NULL;
  9880. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9881. if (outerLocal == NULL)
  9882. return NULL;
  9883. BfTypeVector genericArgs;
  9884. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9885. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9886. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9887. }
  9888. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9889. {
  9890. HashContext hashCtx;
  9891. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9892. {
  9893. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9894. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9895. if (methodInstance->GetNumGenericArguments() != 0)
  9896. {
  9897. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9898. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9899. hashCtx.Mixin(methodGenericArg->mTypeId);
  9900. }
  9901. };
  9902. _MixinMethodInstance(methodInstance);
  9903. if (methodInstance->mMethodDef->mIsLocalMethod)
  9904. {
  9905. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9906. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9907. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9908. }
  9909. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9910. }
  9911. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9912. {
  9913. BfIRValue globalValue;
  9914. BfIRValue* globalValuePtr = NULL;
  9915. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9916. {
  9917. globalValue = *globalValuePtr;
  9918. }
  9919. if (!globalValue)
  9920. {
  9921. // This is necessary to reify the interface type
  9922. PopulateType(ifaceType);
  9923. StringT<128> slotVarName;
  9924. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9925. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9926. BfIRValue value;
  9927. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9928. {
  9929. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  9930. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  9931. int virtSlotIdx = ifaceType->mSlotNum + 1;
  9932. value = GetConstValue32(virtSlotIdx);*/
  9933. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  9934. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  9935. }
  9936. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  9937. mInterfaceSlotRefs[ifaceType] = globalValue;
  9938. }
  9939. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  9940. }
  9941. void BfModule::HadSlotCountDependency()
  9942. {
  9943. if (mCompiler->mIsResolveOnly)
  9944. return;
  9945. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  9946. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  9947. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  9948. }
  9949. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  9950. {
  9951. if (mIsScratchModule)
  9952. {
  9953. // Just fake it for the extern and unspecialized modules
  9954. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  9955. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  9956. }
  9957. BfIRValue globalValue;
  9958. auto fieldDef = fieldInstance->GetFieldDef();
  9959. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  9960. {
  9961. if (fieldInstance->mConstIdx != -1)
  9962. {
  9963. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  9964. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  9965. }
  9966. else
  9967. {
  9968. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  9969. }
  9970. }
  9971. BfIRValue* globalValuePtr = NULL;
  9972. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  9973. {
  9974. globalValue = *globalValuePtr;
  9975. BF_ASSERT(globalValue);
  9976. }
  9977. else
  9978. {
  9979. StringT<128> staticVarName;
  9980. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  9981. auto typeType = fieldInstance->GetResolvedType();
  9982. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  9983. {
  9984. typeType = typeType->GetUnderlyingType();
  9985. }
  9986. PopulateType(typeType);
  9987. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  9988. {
  9989. globalValue = mBfIRBuilder->CreateGlobalVariable(
  9990. mBfIRBuilder->MapType(typeType),
  9991. false,
  9992. BfIRLinkageType_External,
  9993. BfIRValue(),
  9994. staticVarName,
  9995. IsThreadLocal(fieldInstance));
  9996. if (!mBfIRBuilder->mIgnoreWrites)
  9997. {
  9998. // Only store this if we actually did the creation
  9999. BF_ASSERT(globalValue);
  10000. mStaticFieldRefs[fieldInstance] = globalValue;
  10001. }
  10002. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10003. }
  10004. }
  10005. auto type = fieldInstance->GetResolvedType();
  10006. if (type->IsValuelessType())
  10007. return BfTypedValue(globalValue, type);
  10008. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10009. }
  10010. BfTypedValue BfModule::GetThis()
  10011. {
  10012. auto useMethodState = mCurMethodState;
  10013. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10014. {
  10015. useMethodState = useMethodState->mPrevMethodState;
  10016. }
  10017. if (useMethodState != NULL)
  10018. {
  10019. // Fake a 'this' for var field resolution
  10020. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10021. {
  10022. auto thisType = mCurTypeInstance;
  10023. if (thisType->IsValueType())
  10024. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10025. else
  10026. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10027. }
  10028. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10029. {
  10030. return BfTypedValue();
  10031. }
  10032. }
  10033. else
  10034. {
  10035. //TODO: Do we allow useMethodState to be NULL anymore?
  10036. return BfTypedValue();
  10037. }
  10038. // if (useMethodState->HasNonStaticMixin())
  10039. // {
  10040. // auto checkMethodState = useMethodState;
  10041. // while (checkMethodState != NULL)
  10042. // {
  10043. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10044. // {
  10045. // auto varDecl = checkMethodState->mLocals[localIdx];
  10046. // if (varDecl->mName == "this")
  10047. // {
  10048. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10049. // if (varDecl->mIsSplat)
  10050. // {
  10051. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10052. // }
  10053. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10054. // {
  10055. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10056. // }
  10057. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10058. // }
  10059. // }
  10060. //
  10061. // checkMethodState = checkMethodState->mPrevMethodState;
  10062. // }
  10063. // }
  10064. // Check mixin state for 'this'
  10065. {
  10066. auto checkMethodState = useMethodState;
  10067. while (checkMethodState != NULL)
  10068. {
  10069. if (checkMethodState->mMixinState != NULL)
  10070. {
  10071. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10072. if (thisValue)
  10073. {
  10074. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10075. if (!thisValue.mType->IsValueType())
  10076. thisValue = LoadValue(thisValue);
  10077. return thisValue;
  10078. }
  10079. }
  10080. checkMethodState = checkMethodState->mPrevMethodState;
  10081. }
  10082. }
  10083. auto curMethodInstance = mCurMethodInstance;
  10084. if (useMethodState->mMethodInstance != NULL)
  10085. curMethodInstance = useMethodState->mMethodInstance;
  10086. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10087. {
  10088. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10089. {
  10090. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10091. if (constLocal.mIsThis)
  10092. {
  10093. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10094. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10095. }
  10096. }
  10097. return BfTypedValue();
  10098. }
  10099. bool preferValue = !IsTargetingBeefBackend();
  10100. if (useMethodState->mLocals.IsEmpty())
  10101. {
  10102. // 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
  10103. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10104. return BfTypedValue();
  10105. }
  10106. auto thisLocal = useMethodState->mLocals[0];
  10107. BF_ASSERT(thisLocal->mIsThis);
  10108. BfIRValue thisValue;
  10109. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10110. thisValue = thisLocal->mValue;
  10111. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10112. thisValue = thisLocal->mAddr;
  10113. else
  10114. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10115. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10116. if (useMethodState->mClosureState != NULL)
  10117. {
  10118. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10119. if (closureTypeInst != NULL)
  10120. {
  10121. if (closureTypeInst->mFieldInstances.size() > 0)
  10122. {
  10123. auto& field = closureTypeInst->mFieldInstances[0];
  10124. auto fieldDef = field.GetFieldDef();
  10125. if (fieldDef->mName == "__this")
  10126. {
  10127. if (mCurMethodState->mClosureState->mCapturing)
  10128. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10129. // This is a captured 'this'
  10130. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10131. if (field.mResolvedType->IsRef())
  10132. {
  10133. auto refType = (BfRefType*)field.mResolvedType;
  10134. auto underlyingType = refType->GetUnderlyingType();
  10135. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10136. }
  10137. if (field.mResolvedType->IsObject())
  10138. {
  10139. result = LoadValue(result);
  10140. result.mKind = BfTypedValueKind_ThisValue;
  10141. }
  10142. else
  10143. {
  10144. if (fieldDef->mIsReadOnly)
  10145. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10146. else
  10147. result.mKind = BfTypedValueKind_ThisAddr;
  10148. }
  10149. return result;
  10150. }
  10151. }
  10152. return BfTypedValue();
  10153. }
  10154. if (useMethodState->mClosureState->mCapturing)
  10155. {
  10156. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10157. if (thisType->IsValueType())
  10158. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10159. else
  10160. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10161. }
  10162. }
  10163. auto localDef = useMethodState->mLocals[0];
  10164. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10165. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10166. {
  10167. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10168. {
  10169. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10170. }
  10171. if (localDef->mIsSplat)
  10172. {
  10173. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10174. }
  10175. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10176. }
  10177. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10178. }
  10179. BfLocalVariable* BfModule::GetThisVariable()
  10180. {
  10181. if (mCurMethodState == NULL)
  10182. return NULL;
  10183. auto methodState = mCurMethodState->GetNonCaptureState();
  10184. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10185. return methodState->mLocals[0];
  10186. return NULL;
  10187. }
  10188. bool BfModule::IsInGeneric()
  10189. {
  10190. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10191. }
  10192. bool BfModule::IsInSpecializedGeneric()
  10193. {
  10194. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10195. return false;
  10196. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10197. }
  10198. bool BfModule::IsInSpecializedSection()
  10199. {
  10200. return IsInSpecializedGeneric() ||
  10201. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10202. }
  10203. bool BfModule::IsInUnspecializedGeneric()
  10204. {
  10205. if (mCurMethodInstance != NULL)
  10206. return mCurMethodInstance->mIsUnspecialized;
  10207. return false;
  10208. }
  10209. //////////////////////////////////////////////////////////////////////////
  10210. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10211. {
  10212. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10213. if (type->IsValuelessType())
  10214. return mBfIRBuilder->GetFakeVal();
  10215. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10216. if (!doLifetimeEnd)
  10217. {
  10218. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10219. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10220. }
  10221. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10222. auto typeOptions = GetTypeOptions();
  10223. if (typeOptions != NULL)
  10224. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10225. // Local variable inits are implicitly handled in the Beef Backend
  10226. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10227. {
  10228. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10229. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10230. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10231. mBfIRBuilder->ClearDebugLocation(storeInst);
  10232. mBfIRBuilder->SetInsertPoint(prevBlock);
  10233. }
  10234. return allocaInst;
  10235. }
  10236. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10237. {
  10238. if (localVar->mResolvedType->IsVar())
  10239. {
  10240. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL));
  10241. }
  10242. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10243. mCurMethodState->mLocals.push_back(localVar);
  10244. BfLocalVarEntry* localVarEntryPtr;
  10245. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10246. {
  10247. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10248. localVarEntryPtr->mLocalVar = localVar;
  10249. }
  10250. }
  10251. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10252. {
  10253. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10254. {
  10255. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10256. {
  10257. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10258. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10259. }
  10260. }
  10261. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10262. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10263. (mHasFullDebugInfo) &&
  10264. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10265. {
  10266. auto varType = localVarDef->mResolvedType;
  10267. if (localVarDef->mResolvedType->IsValuelessType())
  10268. {
  10269. }
  10270. else
  10271. {
  10272. bool isByAddr = false;
  10273. auto diValue = localVarDef->mValue;
  10274. if (localVarDef->mConstValue)
  10275. diValue = localVarDef->mConstValue;
  10276. else if (localVarDef->mAddr)
  10277. {
  10278. diValue = localVarDef->mAddr;
  10279. isByAddr = true;
  10280. }
  10281. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10282. bool didConstToMem = false;
  10283. bool isConstant = false;
  10284. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10285. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10286. else if (localVarDef->mConstValue)
  10287. {
  10288. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10289. isConstant =
  10290. (constant->mConstType < BfConstType_GlobalVar) ||
  10291. (constant->mConstType == BfConstType_AggZero) ||
  10292. (constant->mConstType == BfConstType_Array);
  10293. if (isConstant)
  10294. {
  10295. if (localVarDef->mResolvedType->IsComposite())
  10296. {
  10297. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10298. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10299. if (IsTargetingBeefBackend())
  10300. {
  10301. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10302. didConstToMem = true;
  10303. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10304. }
  10305. else
  10306. {
  10307. isByAddr = true;
  10308. mBfIRBuilder->SaveDebugLocation();
  10309. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10310. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10311. mBfIRBuilder->ClearDebugLocation();
  10312. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10313. auto addrVal = CreateAlloca(ptrType);
  10314. mBfIRBuilder->CreateStore(constMem, addrVal);
  10315. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10316. diValue = addrVal;
  10317. didConstToMem = true;
  10318. mBfIRBuilder->SetInsertPoint(prevBlock);
  10319. mBfIRBuilder->RestoreDebugLocation();
  10320. }
  10321. }
  10322. if (mCompiler->mOptions.IsCodeView())
  10323. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10324. }
  10325. }
  10326. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10327. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10328. localVarDef->mDbgVarInst = diVariable;
  10329. if (mBfIRBuilder->HasDebugLocation())
  10330. {
  10331. if ((isConstant) && (!didConstToMem))
  10332. {
  10333. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10334. }
  10335. else
  10336. {
  10337. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10338. {
  10339. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10340. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10341. }
  10342. if (isByAddr)
  10343. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10344. else if (diValue)
  10345. {
  10346. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10347. }
  10348. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10349. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10350. }
  10351. }
  10352. }
  10353. }
  10354. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10355. DoAddLocalVariable(localVarDef);
  10356. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10357. if (localVarDef->mLocalVarId == -1)
  10358. {
  10359. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10360. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10361. }
  10362. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10363. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10364. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10365. {
  10366. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10367. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10368. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10369. }
  10370. return localVarDef;
  10371. }
  10372. void BfModule::CreateDIRetVal()
  10373. {
  10374. if (!WantsDebugInfo())
  10375. return;
  10376. /*if (!mCurMethodState->mRetVal)
  10377. {
  10378. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10379. return;
  10380. }*/
  10381. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10382. {
  10383. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10384. BfType* dbgType = mCurMethodInstance->mReturnType;
  10385. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10386. if (mCurMethodInstance->HasStructRet())
  10387. {
  10388. BF_ASSERT(mCurMethodState->mRetValAddr);
  10389. dbgType = CreatePointerType(dbgType);
  10390. dbgValue = mCurMethodState->mRetValAddr;
  10391. }
  10392. else
  10393. {
  10394. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10395. }
  10396. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10397. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10398. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10399. }
  10400. }
  10401. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10402. {
  10403. BfLocalVarEntry* localVarEntryPtr = NULL;
  10404. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10405. {
  10406. auto checkLocal = localVarEntryPtr->mLocalVar;
  10407. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10408. {
  10409. BfError* error;
  10410. if (checkLocal->mIsImplicitParam)
  10411. return; // Ignore 'redefinition'
  10412. if (checkLocal->IsParam())
  10413. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10414. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10415. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10416. else
  10417. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10418. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10419. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10420. return;
  10421. }
  10422. }
  10423. }
  10424. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState)
  10425. {
  10426. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10427. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10428. {
  10429. if (tokenNode->GetToken() == BfToken_Colon)
  10430. return &mCurMethodState->mHeadScope;
  10431. else if (tokenNode->GetToken() == BfToken_Mixin)
  10432. {
  10433. if (fromMixinState == NULL)
  10434. {
  10435. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10436. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10437. return mCurMethodState->mCurScope;
  10438. }
  10439. fromMixinState->mUsedInvocationScope = true;
  10440. return fromMixinState->mTargetScope;
  10441. }
  10442. else if (tokenNode->GetToken() == BfToken_New)
  10443. return NULL;
  10444. }
  10445. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10446. {
  10447. auto findLabel = scopeName->ToString();
  10448. auto checkScope = mCurMethodState->mCurScope;
  10449. while (checkScope != NULL)
  10450. {
  10451. if (checkScope->mLabel == findLabel)
  10452. return checkScope;
  10453. checkScope = checkScope->mPrevScope;
  10454. }
  10455. if (!inMixinDecl)
  10456. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10457. }
  10458. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10459. {
  10460. return FindScope(scopeNode->mTargetNode);
  10461. }
  10462. return mCurMethodState->mCurScope;
  10463. }
  10464. BfScopeData* BfModule::FindScope(BfAstNode* scopeName)
  10465. {
  10466. return FindScope(scopeName, mCurMethodState->mMixinState);
  10467. }
  10468. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10469. {
  10470. auto scopeData = FindScope(scopeName);
  10471. if (scopeData == NULL)
  10472. return NULL;
  10473. int scopeDepth = scopeData->GetDepth();
  10474. // Find the first break data that is at or below the depth of our requested scope
  10475. auto breakData = mCurMethodState->mBreakData;
  10476. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10477. {
  10478. breakData = breakData->mPrevBreakData;
  10479. }
  10480. return breakData;
  10481. }
  10482. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10483. {
  10484. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10485. if (!IsTargetingBeefBackend())
  10486. return;
  10487. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10488. {
  10489. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10490. }
  10491. }
  10492. void BfModule::ClearLifetimeEnds()
  10493. {
  10494. auto scopeData = mCurMethodState->mCurScope;
  10495. while (scopeData != NULL)
  10496. {
  10497. scopeData->mDeferredLifetimeEnds.Clear();
  10498. scopeData = scopeData->mPrevScope;
  10499. }
  10500. }
  10501. bool BfModule::WantsDebugInfo()
  10502. {
  10503. if ((mCurMethodInstance != NULL) &&
  10504. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10505. return false;
  10506. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10507. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10508. }
  10509. BfTypeOptions* BfModule::GetTypeOptions()
  10510. {
  10511. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10512. return mCurMethodState->mMethodTypeOptions;
  10513. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10514. }
  10515. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10516. {
  10517. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10518. while (checkScope != NULL)
  10519. {
  10520. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10521. return true;
  10522. if (checkScope == scope)
  10523. break;
  10524. checkScope = checkScope->mPrevScope;
  10525. }
  10526. return false;
  10527. }
  10528. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10529. {
  10530. // Is there anything we need to do here?
  10531. if (mBfIRBuilder->mIgnoreWrites)
  10532. {
  10533. // Just visit deferred blocks
  10534. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10535. while (checkScope != NULL)
  10536. {
  10537. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10538. while (deferredCallEntry != NULL)
  10539. {
  10540. if (deferredCallEntry->mDeferredBlock != NULL)
  10541. {
  10542. VisitChild(deferredCallEntry->mDeferredBlock);
  10543. }
  10544. deferredCallEntry = deferredCallEntry->mNext;
  10545. }
  10546. if (checkScope == scopeData)
  10547. break;
  10548. checkScope = checkScope->mPrevScope;
  10549. }
  10550. return;
  10551. }
  10552. // Why did we want to do SetIllegalSrcPos here?
  10553. // Don't we always want to step onto these instances?
  10554. // Find a case where we don't and perhaps only do it there.
  10555. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10556. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10557. //SetIllegalSrcPos();
  10558. bool setSrcPos = false;
  10559. bool wantsNop = true;
  10560. BfAstNode* deferCloseNode = NULL;
  10561. if (mCurMethodState->mInPostReturn)
  10562. {
  10563. // These won't get used, they are post-return
  10564. return;
  10565. }
  10566. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10567. BfScopeData* scopeJumpBlock = NULL;
  10568. bool hadExtraDeferredLifetimeEnds = false;
  10569. auto _FlushLifetimeEnds = [&]()
  10570. {
  10571. for (auto lifetimeEnd : deferredLifetimeEnds)
  10572. {
  10573. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10574. mBfIRBuilder->ClearDebugLocation_Last();
  10575. }
  10576. deferredLifetimeEnds.clear();
  10577. };
  10578. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10579. while (checkScope != NULL)
  10580. {
  10581. if (checkScope->mCloseNode != NULL)
  10582. deferCloseNode = checkScope->mCloseNode;
  10583. if (doneBlock)
  10584. {
  10585. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10586. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10587. {
  10588. if (checkHandler.mDoneBlock == doneBlock)
  10589. {
  10590. scopeJumpBlock = checkScope;
  10591. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10592. mBfIRBuilder->ClearDebugLocation_Last();
  10593. _FlushLifetimeEnds();
  10594. break;
  10595. }
  10596. }
  10597. if (scopeJumpBlock != NULL)
  10598. break;
  10599. }
  10600. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10601. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10602. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10603. if (hasWork)
  10604. {
  10605. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10606. if (deferCloseNode != NULL)
  10607. {
  10608. UpdateSrcPos(deferCloseNode);
  10609. }
  10610. if (doneBlock)
  10611. {
  10612. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10613. String blockName = "deferredCalls";
  10614. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10615. BfDeferredHandler deferredHandler;
  10616. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10617. {
  10618. mBfIRBuilder->SaveDebugLocation();
  10619. mBfIRBuilder->ClearDebugLocation();
  10620. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10621. mBfIRBuilder->RestoreDebugLocation();
  10622. }
  10623. else
  10624. {
  10625. // Definitely chain
  10626. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10627. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10628. mBfIRBuilder->ClearDebugLocation_Last();
  10629. _FlushLifetimeEnds();
  10630. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10631. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10632. }
  10633. deferredHandler.mDoneBlock = doneBlock;
  10634. if (!mBfIRBuilder->mIgnoreWrites)
  10635. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10636. if (checkScope == &mCurMethodState->mHeadScope)
  10637. {
  10638. if (!mCurMethodState->mDIRetVal)
  10639. {
  10640. // 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
  10641. // be scoped to the physical method
  10642. /*if (deferCloseNode != NULL)
  10643. {
  10644. UpdateSrcPos(deferCloseNode);
  10645. }*/
  10646. CreateDIRetVal();
  10647. }
  10648. }
  10649. if (checkScope != mCurMethodState->mTailScope)
  10650. {
  10651. if (deferredHandler.mHandlerBlock.IsFake())
  10652. {
  10653. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10654. }
  10655. if (!mBfIRBuilder->mIgnoreWrites)
  10656. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10657. }
  10658. }
  10659. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10660. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10661. while (deferredCallEntry != NULL)
  10662. {
  10663. BfDeferredCallEmitState deferredCallEmitState;
  10664. deferredCallEmitState.mCloseNode = deferCloseNode;
  10665. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10666. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10667. if (deferCloseNode != NULL)
  10668. {
  10669. UpdateSrcPos(deferCloseNode);
  10670. }
  10671. if (wantsNop)
  10672. EmitEnsureInstructionAt();
  10673. wantsNop = false;
  10674. if (deferredCallEntry->mDeferredBlock != NULL)
  10675. {
  10676. auto itr = handledSet.insert(deferredCallEntry);
  10677. if (!itr.second)
  10678. {
  10679. // Already handled, can happen if we defer again within the block
  10680. deferredCallEntry = deferredCallEntry->mNext;
  10681. continue;
  10682. }
  10683. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10684. EmitDeferredCall(*deferredCallEntry);
  10685. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10686. {
  10687. // The list changed, start over and ignore anything we've already handled
  10688. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10689. }
  10690. else
  10691. deferredCallEntry = deferredCallEntry->mNext;
  10692. }
  10693. else
  10694. {
  10695. EmitDeferredCall(*deferredCallEntry);
  10696. deferredCallEntry = deferredCallEntry->mNext;
  10697. }
  10698. }
  10699. if (checkScope->mSavedStack)
  10700. {
  10701. mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack);
  10702. if (mCurMethodState->mDynStackRevIdx)
  10703. {
  10704. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10705. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10706. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10707. }
  10708. }
  10709. }
  10710. if (!checkScope->mIsScopeHead)
  10711. {
  10712. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10713. if (!IsTargetingBeefBackend())
  10714. {
  10715. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10716. {
  10717. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10718. }
  10719. }
  10720. else
  10721. {
  10722. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10723. {
  10724. deferredLifetimeEnds.Add(lifetimeEnd);
  10725. }
  10726. }
  10727. }
  10728. if (checkScope == scopeData)
  10729. break;
  10730. checkScope = checkScope->mPrevScope;
  10731. }
  10732. if ((doneBlock) && (scopeJumpBlock == NULL))
  10733. {
  10734. mBfIRBuilder->CreateBr(doneBlock);
  10735. mBfIRBuilder->ClearDebugLocation_Last();
  10736. }
  10737. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10738. // may have been created when other scope lifetimes were available
  10739. _FlushLifetimeEnds();
  10740. // Emit lifetimeEnds after the branch for Beef
  10741. /*if (IsTargetingBeefBackend())
  10742. {
  10743. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10744. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10745. while (checkScope != NULL)
  10746. {
  10747. if (checkScope == scopeJumpBlock)
  10748. break;
  10749. if (!checkScope->mIsScopeHead)
  10750. {
  10751. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10752. {
  10753. if (needsEnsureInst)
  10754. {
  10755. needsEnsureInst = false;
  10756. }
  10757. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10758. }
  10759. }
  10760. if (checkScope == scopeData)
  10761. break;
  10762. checkScope = checkScope->mPrevScope;
  10763. }
  10764. }*/
  10765. }
  10766. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10767. {
  10768. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10769. {
  10770. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10771. while (deferredLocalAssignData != NULL)
  10772. {
  10773. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10774. break;
  10775. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10776. deferredLocalAssignData->mIsUnconditional = false;
  10777. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10778. }
  10779. }
  10780. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10781. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10782. // int b;
  10783. // if (cond) return;
  10784. // else b = 1;
  10785. // Use(b);
  10786. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10787. {
  10788. auto localDef = mCurMethodState->mLocals[localIdx];
  10789. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10790. mCurMethodState->LocalDefined(localDef);
  10791. }
  10792. }
  10793. void BfModule::CreateReturn(BfIRValue val)
  10794. {
  10795. if (mCurMethodInstance->mReturnType->IsComposite())
  10796. {
  10797. // Store to sret
  10798. BF_ASSERT(val);
  10799. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10800. mBfIRBuilder->CreateRetVoid();
  10801. }
  10802. else
  10803. {
  10804. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10805. {
  10806. mBfIRBuilder->CreateRetVoid();
  10807. }
  10808. else
  10809. {
  10810. BF_ASSERT(val);
  10811. mBfIRBuilder->CreateRet(val);
  10812. }
  10813. }
  10814. }
  10815. void BfModule::EmitReturn(BfIRValue val)
  10816. {
  10817. if (mCurMethodState->mIRExitBlock)
  10818. {
  10819. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10820. {
  10821. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10822. {
  10823. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10824. if (!mCurMethodState->mRetVal)
  10825. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10826. mBfIRBuilder->CreateStore(val, retVal);
  10827. }
  10828. }
  10829. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10830. }
  10831. else
  10832. {
  10833. EmitDeferredScopeCalls(false, NULL);
  10834. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10835. mBfIRBuilder->CreateRetVoid();
  10836. else
  10837. mBfIRBuilder->CreateRet(val);
  10838. }
  10839. mCurMethodState->SetHadReturn(true);
  10840. mCurMethodState->mLeftBlockUncond = true;
  10841. }
  10842. void BfModule::EmitDefaultReturn()
  10843. {
  10844. if (mCurMethodState->mIRExitBlock)
  10845. {
  10846. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10847. }
  10848. else
  10849. {
  10850. if (mCurMethodInstance->mReturnType->IsVoid())
  10851. mBfIRBuilder->CreateRetVoid();
  10852. else
  10853. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10854. }
  10855. mCurMethodState->SetHadReturn(true);
  10856. mCurMethodState->mLeftBlockUncond = true;
  10857. }
  10858. void BfModule::AssertErrorState()
  10859. {
  10860. if (mIgnoreErrors)
  10861. return;
  10862. if (mHadBuildError)
  10863. return;
  10864. if (mCurTypeInstance != NULL)
  10865. {
  10866. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10867. return;
  10868. }
  10869. if (mCurMethodInstance != NULL)
  10870. {
  10871. if (mCurMethodInstance->mIsUnspecializedVariation)
  10872. return;
  10873. }
  10874. // We want the module to be marked as failed even if it's just an error in the parser
  10875. if (mCurMethodInstance != NULL)
  10876. mCurMethodInstance->mHasFailed = true;
  10877. mHadBuildError = true;
  10878. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10879. if (mCurTypeInstance != NULL)
  10880. {
  10881. if (mCurTypeInstance->mTypeFailed)
  10882. return;
  10883. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10884. return;
  10885. }
  10886. if (mCurMethodInstance != NULL)
  10887. {
  10888. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10889. return;
  10890. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10891. return;
  10892. }
  10893. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10894. }
  10895. void BfModule::AssertParseErrorState()
  10896. {
  10897. if (mCompiler->mRevision == 1)
  10898. AssertErrorState();
  10899. }
  10900. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10901. {
  10902. BF_ASSERT(delegateType->IsDelegate());
  10903. auto typeInst = delegateType->ToTypeInstance();
  10904. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10905. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10906. return invokeMethodInstance->mReturnType;
  10907. }
  10908. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  10909. {
  10910. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  10911. }
  10912. void BfModule::CreateDelegateInvokeMethod()
  10913. {
  10914. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  10915. mBfIRBuilder->ClearDebugLocation();
  10916. auto typeInstance = mCurTypeInstance;
  10917. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  10918. SizedArray<BfIRType, 4> staticParamTypes;
  10919. SizedArray<BfIRValue, 4> staticFuncArgs;
  10920. SizedArray<BfIRValue, 4> memberFuncArgs;
  10921. auto multicastDelegateType = typeInstance->mBaseType;
  10922. if (multicastDelegateType->mFieldInstances.size() != 2)
  10923. {
  10924. AssertErrorState();
  10925. return;
  10926. }
  10927. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  10928. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  10929. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  10930. BfExprEvaluator exprEvaluator(this);
  10931. SizedArray<BfIRType, 8> origParamTypes;
  10932. BfIRType origReturnType;
  10933. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  10934. if (mCurMethodInstance->mReturnType->IsValueType())
  10935. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  10936. int thisIdx = 0;
  10937. if (mCurMethodInstance->HasStructRet())
  10938. {
  10939. thisIdx = 1;
  10940. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  10941. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  10942. }
  10943. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  10944. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  10945. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  10946. {
  10947. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  10948. exprEvaluator.PushArg(localVal, staticFuncArgs);
  10949. exprEvaluator.PushArg(localVal, memberFuncArgs);
  10950. }
  10951. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  10952. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  10953. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  10954. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  10955. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  10956. auto doneBB = mBfIRBuilder->CreateBlock("done");
  10957. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  10958. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  10959. BfIRValue nonStaticResult;
  10960. BfIRValue staticResult;
  10961. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  10962. /// Non-static invocation
  10963. {
  10964. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  10965. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  10966. mBfIRBuilder->SetInsertPoint(trueBB);
  10967. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  10968. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  10969. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  10970. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  10971. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  10972. if (callingConv != BfIRCallingConv_CDecl)
  10973. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  10974. mCurMethodState->SetHadReturn(false);
  10975. mCurMethodState->mLeftBlockUncond = false;
  10976. mCurMethodState->mLeftBlockCond = false;
  10977. mBfIRBuilder->CreateBr(doneBB);
  10978. }
  10979. // Static invocation
  10980. {
  10981. mBfIRBuilder->AddBlock(falseBB);
  10982. mBfIRBuilder->SetInsertPoint(falseBB);
  10983. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  10984. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  10985. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  10986. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  10987. if (callingConv == BfIRCallingConv_ThisCall)
  10988. callingConv = BfIRCallingConv_CDecl;
  10989. if (callingConv != BfIRCallingConv_CDecl)
  10990. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  10991. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  10992. // {
  10993. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  10994. //
  10995. // }
  10996. mCurMethodState->SetHadReturn(false);
  10997. mCurMethodState->mLeftBlockUncond = false;
  10998. mCurMethodState->mLeftBlockCond = false;
  10999. mBfIRBuilder->CreateBr(doneBB);
  11000. }
  11001. mBfIRBuilder->AddBlock(doneBB);
  11002. mBfIRBuilder->SetInsertPoint(doneBB);
  11003. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11004. {
  11005. mBfIRBuilder->CreateRetVoid();
  11006. }
  11007. else
  11008. {
  11009. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11010. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11011. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11012. mBfIRBuilder->CreateRet(phi);
  11013. }
  11014. }
  11015. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11016. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11017. {
  11018. auto typeDef = typeInstance->mTypeDef;
  11019. auto methodDeclaration = methodDef->mMethodDeclaration;
  11020. if (!mCompiler->mIsResolveOnly)
  11021. return true;
  11022. if (typeInstance->IsGenericTypeInstance())
  11023. {
  11024. // We only really want to process the unspecialized type for autocompletion
  11025. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11026. return false;
  11027. }
  11028. BfAstNode* checkNode = methodDeclaration;
  11029. if (methodDeclaration == NULL)
  11030. checkNode = methodDef->mBody;
  11031. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11032. {
  11033. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11034. return true;
  11035. }
  11036. return false;
  11037. }
  11038. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11039. {
  11040. methodInst->mAppendAllocAlign = 1;
  11041. }
  11042. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11043. {
  11044. BP_ZONE("BfModule::TryConstCalcAppend");
  11045. if (mCompiler->mIsResolveOnly)
  11046. return BfTypedValue();
  11047. // We want to regenerate all ctor calls when the method internals change
  11048. {
  11049. auto checkTypeInst = methodInst->GetOwner();
  11050. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11051. {
  11052. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11053. checkTypeInst = GetBaseType(checkTypeInst);
  11054. }
  11055. }
  11056. if (!methodInst->mMayBeConst)
  11057. return BfTypedValue();
  11058. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11059. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11060. bool wasAllConst = true;
  11061. int argIdx = 0;
  11062. int paramIdx = 0;
  11063. while (true)
  11064. {
  11065. if (argIdx >= (int)args.size())
  11066. break;
  11067. auto paramType = methodInst->GetParamType(paramIdx);
  11068. PopulateType(paramType);
  11069. int argCount = 0;
  11070. if (!paramType->IsValuelessType())
  11071. {
  11072. if (methodInst->GetParamIsSplat(paramIdx))
  11073. argCount = paramType->GetSplatCount();
  11074. else
  11075. argCount = 1;
  11076. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11077. {
  11078. auto arg = args[argIdx + argOfs];
  11079. if (!arg.IsConst())
  11080. {
  11081. wasAllConst = false;
  11082. if (!isFirstRun)
  11083. {
  11084. auto& param = methodInst->mParams[argIdx];
  11085. if (param.mReferencedInConstPass)
  11086. {
  11087. // If this param is required as part of the const calculation then
  11088. // we require that it be const...
  11089. return BfTypedValue();
  11090. }
  11091. }
  11092. }
  11093. }
  11094. }
  11095. paramIdx++;
  11096. argIdx += argCount;
  11097. }
  11098. auto methodDef = methodInst->mMethodDef;
  11099. auto methodDecl = methodDef->GetMethodDeclaration();
  11100. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11101. if (methodDeclBlock == NULL)
  11102. return BfTypedValue();
  11103. BfTypedValue constValue;
  11104. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11105. auto checkState = mCurMethodState->mConstResolveState;
  11106. while (checkState != NULL)
  11107. {
  11108. if (checkState->mMethodInstance == methodInst)
  11109. {
  11110. return BfTypedValue();
  11111. }
  11112. checkState = checkState->mPrevConstResolveState;
  11113. }
  11114. //auto accumValue = GetConstValue(0);
  11115. bool failed = false;
  11116. //
  11117. {
  11118. BfConstResolveState constResolveState;
  11119. constResolveState.mMethodInstance = methodInst;
  11120. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11121. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11122. BfMethodState methodState;
  11123. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11124. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11125. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11126. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11127. methodState.mConstResolveState = &constResolveState;
  11128. int argIdx = 0;
  11129. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11130. {
  11131. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11132. continue;
  11133. auto paramType = methodInst->GetParamType(paramIdx);
  11134. // Fix this after we allow structs to be consts
  11135. //BF_ASSERT(!paramType->IsSplattable());
  11136. BfLocalVariable* localVar = new BfLocalVariable();
  11137. localVar->mName = methodInst->GetParamName(paramIdx);
  11138. localVar->mResolvedType = paramType;
  11139. localVar->mConstValue = args[argIdx];
  11140. localVar->mParamIdx = paramIdx;
  11141. AddLocalVariableDef(localVar);
  11142. argIdx++;
  11143. }
  11144. AppendAllocVisitor appendAllocVisitor;
  11145. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11146. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11147. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11148. if (baseCtorAppendValue)
  11149. {
  11150. if (baseCtorAppendValue.mValue.IsFake())
  11151. appendAllocVisitor.mFailed = true;
  11152. else
  11153. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11154. }
  11155. appendAllocVisitor.mModule = this;
  11156. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11157. if (!appendAllocVisitor.mFailed)
  11158. constValue = appendAllocVisitor.mConstAccum;
  11159. if (isFirstRun)
  11160. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11161. if (isFirstRun)
  11162. {
  11163. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11164. {
  11165. auto localVar = mCurMethodState->mLocals[paramIdx];
  11166. if (localVar->mReadFromId != -1)
  11167. {
  11168. auto& param = methodInst->mParams[paramIdx];
  11169. param.mReferencedInConstPass = true;
  11170. }
  11171. }
  11172. }
  11173. }
  11174. mBfIRBuilder->SetInsertPoint(prevBlock);
  11175. if (!constValue)
  11176. {
  11177. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11178. // all-const args
  11179. if (wasAllConst)
  11180. {
  11181. methodInst->mMayBeConst = false;
  11182. }
  11183. }
  11184. return constValue;
  11185. }
  11186. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11187. {
  11188. // Any errors should only be shown in the actual CTOR call
  11189. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11190. auto methodDef = mCurMethodInstance->mMethodDef;
  11191. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11192. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11193. BfTypeInstance* targetType = NULL;
  11194. if (ctorDeclaration->mInitializer != NULL)
  11195. {
  11196. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11197. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11198. }
  11199. else
  11200. targetType = mCurTypeInstance->mBaseType;
  11201. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11202. return NULL;
  11203. auto targetRefNode = methodDef->GetRefNode();
  11204. BfType* targetThisType = targetType;
  11205. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11206. BfExprEvaluator exprEvaluator(this);
  11207. BfResolvedArgs argValues;
  11208. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11209. {
  11210. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11211. }
  11212. //
  11213. {
  11214. }
  11215. BfFunctionBindResult bindResult;
  11216. bindResult.mSkipThis = true;
  11217. bindResult.mWantsArgs = true;
  11218. {
  11219. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11220. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11221. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11222. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11223. }
  11224. if (bindResult.mMethodInstance == NULL)
  11225. {
  11226. AssertErrorState();
  11227. return BfTypedValue();
  11228. }
  11229. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11230. {
  11231. return BfTypedValue();
  11232. }
  11233. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11234. bindResult.mIRArgs.RemoveAt(0);
  11235. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11236. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11237. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11238. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11239. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11240. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11241. if (appendSizeTypedValue)
  11242. return appendSizeTypedValue;
  11243. if (constOnly)
  11244. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11245. bool needsRecalc = false;
  11246. for (auto irArg : bindResult.mIRArgs)
  11247. {
  11248. if (irArg.IsFake())
  11249. needsRecalc = true;
  11250. }
  11251. auto calcAppendArgs = bindResult.mIRArgs;
  11252. if (needsRecalc)
  11253. {
  11254. // Do it again, but without mIgnoreWrites set
  11255. BfResolvedArgs argValues;
  11256. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11257. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11258. BfFunctionBindResult bindResult;
  11259. bindResult.mSkipThis = true;
  11260. bindResult.mWantsArgs = true;
  11261. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11262. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11263. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11264. bindResult.mIRArgs.RemoveAt(0);
  11265. calcAppendArgs = bindResult.mIRArgs;
  11266. }
  11267. BF_ASSERT(calcAppendMethodModule.mFunc);
  11268. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11269. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11270. return appendSizeTypedValue;
  11271. }
  11272. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11273. void BfModule::EmitCtorCalcAppend()
  11274. {
  11275. if (mCompiler->mIsResolveOnly)
  11276. return;
  11277. auto methodDef = mCurMethodInstance->mMethodDef;
  11278. auto methodDecl = methodDef->GetMethodDeclaration();
  11279. Array<BfAstNode*> deferredNodeList;
  11280. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11281. if (methodDeclBlock == NULL)
  11282. return;
  11283. AppendAllocVisitor appendAllocVisitor;
  11284. auto baseCalcAppend = CallBaseCtorCalc(false);
  11285. if (baseCalcAppend)
  11286. {
  11287. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11288. }
  11289. appendAllocVisitor.mModule = this;
  11290. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11291. }
  11292. void BfModule::CreateStaticCtor()
  11293. {
  11294. auto typeDef = mCurTypeInstance->mTypeDef;
  11295. auto methodDef = mCurMethodInstance->mMethodDef;
  11296. BfIRBlock exitBB;
  11297. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11298. {
  11299. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11300. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11301. mBfIRBuilder->MapType(boolType),
  11302. false,
  11303. BfIRLinkageType_Internal,
  11304. GetDefaultValue(boolType),
  11305. "didStaticInit");
  11306. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11307. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11308. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11309. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11310. mBfIRBuilder->SetInsertPoint(initBB);
  11311. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11312. }
  11313. // Do DLL imports
  11314. if (!mDllImportEntries.empty())
  11315. {
  11316. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11317. PopulateType(internalType);
  11318. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11319. if (!getSharedProcAddressInstance)
  11320. {
  11321. if (!mCompiler->mPassInstance->HasFailed())
  11322. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11323. }
  11324. }
  11325. // Fill in initializer values
  11326. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11327. {
  11328. for (auto fieldDef : typeDef->mFields)
  11329. {
  11330. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11331. {
  11332. // For extensions, only handle these fields in the appropriate extension
  11333. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11334. continue;
  11335. UpdateSrcPos(fieldDef->mInitializer);
  11336. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11337. if (!fieldInst->mFieldIncluded)
  11338. continue;
  11339. auto assignValue = GetFieldInitializerValue(fieldInst);
  11340. if (assignValue)
  11341. {
  11342. assignValue = LoadValue(assignValue);
  11343. if (!assignValue.mType->IsValuelessType())
  11344. {
  11345. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11346. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11347. }
  11348. }
  11349. }
  11350. }
  11351. }
  11352. else
  11353. {
  11354. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11355. {
  11356. if (tempTypeDef->mFullName == typeDef->mFullName)
  11357. {
  11358. for (auto fieldDef : tempTypeDef->mFields)
  11359. {
  11360. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11361. {
  11362. if (fieldDef->mInitializer != NULL)
  11363. {
  11364. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11365. {
  11366. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11367. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11368. }
  11369. BfType* wantType = NULL;
  11370. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11371. {
  11372. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11373. }
  11374. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11375. }
  11376. }
  11377. }
  11378. }
  11379. }
  11380. }
  11381. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11382. CallChainedMethods(mCurMethodInstance, false);
  11383. }
  11384. void BfModule::EmitDtorBody()
  11385. {
  11386. if (mCurTypeInstance->IsClosure())
  11387. {
  11388. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11389. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11390. auto thisVal = GetThis();
  11391. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11392. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11393. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11394. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11395. SizedArray<BfIRValue, 1> args;
  11396. args.push_back(thisVal.mValue);
  11397. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11398. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11399. // Fall through to Object::~this call
  11400. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11401. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11402. SizedArray<BfIRValue, 1> vals = { basePtr };
  11403. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11404. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11405. mBfIRBuilder->SetTailCall(result);
  11406. return;
  11407. }
  11408. auto typeDef = mCurTypeInstance->mTypeDef;
  11409. auto methodDef = mCurMethodInstance->mMethodDef;
  11410. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11411. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11412. CallChainedMethods(mCurMethodInstance, true);
  11413. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11414. {
  11415. VisitCodeBlock(bodyBlock);
  11416. if (bodyBlock->mCloseBrace != NULL)
  11417. {
  11418. UpdateSrcPos(bodyBlock->mCloseBrace);
  11419. }
  11420. }
  11421. else
  11422. {
  11423. if (methodDeclaration != NULL)
  11424. UpdateSrcPos(methodDeclaration);
  11425. else if (typeDef->mTypeDeclaration != NULL)
  11426. UpdateSrcPos(typeDef->mTypeDeclaration);
  11427. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11428. {
  11429. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11430. }
  11431. }
  11432. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11433. {
  11434. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11435. {
  11436. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11437. auto fieldDef = fieldInst->GetFieldDef();
  11438. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11439. {
  11440. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11441. {
  11442. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11443. }
  11444. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11445. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11446. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11447. continue;
  11448. UpdateSrcPos(fieldDtor);
  11449. BfScopeData scopeData;
  11450. mCurMethodState->AddScope(&scopeData);
  11451. NewScopeState();
  11452. UpdateSrcPos(fieldDtor);
  11453. bool hasDbgInfo = (!fieldDef->mIsConst);
  11454. if (hasDbgInfo)
  11455. {
  11456. mBfIRBuilder->SaveDebugLocation();
  11457. mBfIRBuilder->ClearDebugLocation();
  11458. }
  11459. BfIRValue value;
  11460. if (fieldDef->mIsStatic)
  11461. {
  11462. value = ReferenceStaticField(fieldInst).mValue;
  11463. }
  11464. else
  11465. {
  11466. if (!mCurTypeInstance->IsValueType())
  11467. {
  11468. auto thisValue = GetThis();
  11469. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11470. }
  11471. else
  11472. {
  11473. AssertErrorState();
  11474. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11475. }
  11476. }
  11477. BfIRValue staticVal;
  11478. if (hasDbgInfo)
  11479. {
  11480. BfIRValue dbgShowValue = value;
  11481. BfLocalVariable* localDef = new BfLocalVariable();
  11482. localDef->mName = "_";
  11483. localDef->mResolvedType = fieldInst->mResolvedType;
  11484. localDef->mAddr = value;
  11485. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11486. {
  11487. // Create another pointer indirection, a ref to the gep
  11488. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11489. auto allocaInst = CreateAlloca(refFieldType);
  11490. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11491. localDef->mResolvedType = refFieldType;
  11492. localDef->mAddr = allocaInst;
  11493. }
  11494. mBfIRBuilder->RestoreDebugLocation();
  11495. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11496. // Put back so we actually modify the correct value*/
  11497. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11498. defLocalVar->mAddr = value;
  11499. }
  11500. while (fieldDtor != NULL)
  11501. {
  11502. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11503. {
  11504. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11505. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11506. }
  11507. UpdateSrcPos(fieldDtor);
  11508. VisitEmbeddedStatement(fieldDtor->mBody);
  11509. fieldDtor = fieldDtor->mNextFieldDtor;
  11510. }
  11511. RestoreScopeState();
  11512. }
  11513. }
  11514. if (!methodDef->mIsStatic)
  11515. {
  11516. auto checkBaseType = mCurTypeInstance->mBaseType;
  11517. while (checkBaseType != NULL)
  11518. {
  11519. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11520. {
  11521. if (bodyBlock->mCloseBrace != NULL)
  11522. UpdateSrcPos(bodyBlock->mCloseBrace);
  11523. }
  11524. else
  11525. {
  11526. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11527. }
  11528. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11529. {
  11530. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11531. if (mCompiler->IsSkippingExtraResolveChecks())
  11532. {
  11533. // Nothing
  11534. }
  11535. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11536. {
  11537. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11538. {
  11539. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11540. SizedArray<BfIRValue, 1> vals = { basePtr };
  11541. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11542. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11543. }
  11544. }
  11545. else
  11546. {
  11547. // Invalid base dtor declaration
  11548. AssertErrorState();
  11549. }
  11550. break;
  11551. }
  11552. checkBaseType = checkBaseType->mBaseType;
  11553. }
  11554. }
  11555. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11556. }
  11557. else
  11558. {
  11559. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11560. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11561. // resolve pass, NOT the autocomplete expression
  11562. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11563. {
  11564. if (tempTypeDef->mFullName == typeDef->mFullName)
  11565. {
  11566. for (auto fieldDef : tempTypeDef->mFields)
  11567. {
  11568. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11569. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11570. {
  11571. BfType* fieldType = NULL;
  11572. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11573. {
  11574. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11575. auto curFieldDef = curFieldInstance->GetFieldDef();
  11576. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11577. fieldType = curFieldInstance->GetResolvedType();
  11578. }
  11579. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11580. BfScopeData scopeData;
  11581. mCurMethodState->AddScope(&scopeData);
  11582. NewScopeState();
  11583. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11584. if (fieldType != NULL)
  11585. {
  11586. BfLocalVariable* localDef = new BfLocalVariable();
  11587. localDef->mName = "_";
  11588. localDef->mResolvedType = fieldType;
  11589. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11590. localDef->mIsAssigned = true;
  11591. AddLocalVariableDef(localDef);
  11592. }
  11593. while (fieldDtor != NULL)
  11594. {
  11595. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11596. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11597. UpdateSrcPos(fieldDtor);
  11598. VisitEmbeddedStatement(fieldDtor->mBody);
  11599. fieldDtor = fieldDtor->mNextFieldDtor;
  11600. }
  11601. RestoreScopeState();
  11602. }
  11603. }
  11604. }
  11605. }
  11606. }
  11607. }
  11608. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11609. {
  11610. auto typeInstance = methodInstance->GetOwner();
  11611. bool foundDllImportAttr = false;
  11612. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11613. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11614. {
  11615. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11616. {
  11617. foundDllImportAttr = true;
  11618. }
  11619. }
  11620. if (!foundDllImportAttr)
  11621. {
  11622. AssertErrorState();
  11623. return BfIRValue();
  11624. }
  11625. String name = "bf_hs_preserve@";
  11626. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11627. name += "__imp";
  11628. BfIRType returnType;
  11629. SizedArray<BfIRType, 8> paramTypes;
  11630. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11631. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11632. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11633. BfIRValue initVal;
  11634. if (define)
  11635. {
  11636. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11637. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11638. }
  11639. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11640. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11641. {
  11642. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11643. auto ptrType = CreatePointerType(voidType);
  11644. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11645. }
  11646. return globalVar;
  11647. }
  11648. void BfModule::CreateDllImportMethod()
  11649. {
  11650. if (mBfIRBuilder->mIgnoreWrites)
  11651. return;
  11652. auto globalVar = mFuncReferences[mCurMethodInstance];
  11653. if (!globalVar)
  11654. return;
  11655. bool allowTailCall = true;
  11656. mBfIRBuilder->ClearDebugLocation();
  11657. bool isHotCompile = mCompiler->IsHotCompile();
  11658. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11659. if (isHotCompile)
  11660. {
  11661. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11662. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11663. }
  11664. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11665. BfIRType returnType;
  11666. SizedArray<BfIRType, 8> paramTypes;
  11667. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11668. SizedArray<BfIRValue, 8> args;
  11669. for (int i = 0; i < (int)paramTypes.size(); i++)
  11670. args.push_back(mBfIRBuilder->GetArgument(i));
  11671. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11672. if (isHotCompile)
  11673. {
  11674. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11675. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11676. if (callingConvention == BfIRCallingConv_StdCall)
  11677. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11678. else
  11679. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11680. if (allowTailCall)
  11681. mBfIRBuilder->SetTailCall(result);
  11682. CreateReturn(result);
  11683. mCurMethodState->mHadReturn = true;
  11684. }
  11685. if (HasCompiledOutput())
  11686. {
  11687. BfDllImportEntry dllImportEntry;
  11688. dllImportEntry.mFuncVar = globalVar;
  11689. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11690. mDllImportEntries.push_back(dllImportEntry);
  11691. }
  11692. }
  11693. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11694. {
  11695. if (mSystem->mPtrSize == 8)
  11696. return BfIRCallingConv_CDecl;
  11697. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11698. return BfIRCallingConv_StdCall;
  11699. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11700. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11701. return BfIRCallingConv_ThisCall;
  11702. return BfIRCallingConv_CDecl;
  11703. }
  11704. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11705. {
  11706. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11707. }
  11708. void BfModule::SetupLLVMMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11709. {
  11710. auto methodDef = methodInstance->mMethodDef;
  11711. if (!func)
  11712. return;
  11713. if (mCompiler->mOptions.mNoFramePointerElim)
  11714. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11715. if (methodDef->mImportKind == BfImportKind_Export)
  11716. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11717. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11718. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11719. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11720. if (methodDef->mNoReturn)
  11721. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11722. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11723. if (callingConv != BfIRCallingConv_CDecl)
  11724. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11725. if (isInlined)
  11726. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11727. int argIdx = 0;
  11728. int paramIdx = 0;
  11729. if (methodInstance->HasThis())
  11730. {
  11731. paramIdx = -1;
  11732. }
  11733. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11734. if (methodInstance->HasStructRet())
  11735. {
  11736. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11737. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11738. argIdx++;
  11739. }
  11740. while (argIdx < argCount)
  11741. {
  11742. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11743. paramIdx++;
  11744. BfType* resolvedTypeRef = NULL;
  11745. String paramName;
  11746. bool isSplattable = false;
  11747. bool isThis = paramIdx == -1;
  11748. if (isThis)
  11749. {
  11750. paramName = "this";
  11751. if (methodInstance->mIsClosure)
  11752. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11753. else
  11754. resolvedTypeRef = methodInstance->GetOwner();
  11755. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11756. }
  11757. else if (!methodDef->mNoSplat)
  11758. {
  11759. paramName = methodInstance->GetParamName(paramIdx);
  11760. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11761. if (resolvedTypeRef->IsMethodRef())
  11762. isSplattable = true;
  11763. else if (resolvedTypeRef->IsSplattable())
  11764. {
  11765. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11766. isSplattable = true;
  11767. }
  11768. }
  11769. //
  11770. {
  11771. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11772. if (loweredTypeCode != BfTypeCode_None)
  11773. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11774. }
  11775. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11776. {
  11777. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11778. int addDeref = -1;
  11779. if (resolvedTypeRef->IsRef())
  11780. {
  11781. auto refType = (BfRefType*)resolvedTypeRef;
  11782. auto elementType = refType->mElementType;
  11783. PopulateType(elementType, BfPopulateType_Data);
  11784. addDeref = elementType->mSize;
  11785. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11786. AssertErrorState();
  11787. }
  11788. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11789. {
  11790. if (mCompiler->mOptions.mAllowStructByVal)
  11791. {
  11792. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11793. }
  11794. else
  11795. {
  11796. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11797. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11798. addDeref = resolvedTypeRef->mSize;
  11799. }
  11800. }
  11801. else if (resolvedTypeRef->IsPrimitiveType())
  11802. {
  11803. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11804. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11805. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11806. }
  11807. if (addDeref >= 0)
  11808. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11809. argIdx++;
  11810. };
  11811. if (isSplattable)
  11812. {
  11813. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11814. {
  11815. if (checkType->IsStruct())
  11816. {
  11817. auto checkTypeInstance = checkType->ToTypeInstance();
  11818. if (checkTypeInstance->mBaseType != NULL)
  11819. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11820. if (checkTypeInstance->mIsUnion)
  11821. {
  11822. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11823. checkTypeLambda(unionInnerType, curName + "_data");
  11824. }
  11825. else
  11826. {
  11827. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11828. {
  11829. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11830. auto fieldDef = fieldInstance->GetFieldDef();
  11831. if (fieldInstance->mDataIdx >= 0)
  11832. {
  11833. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11834. }
  11835. }
  11836. }
  11837. if (checkTypeInstance->IsEnum())
  11838. {
  11839. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11840. argIdx++;
  11841. }
  11842. }
  11843. else if (checkType->IsMethodRef())
  11844. {
  11845. auto methodRefType = (BfMethodRefType*)checkType;
  11846. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11847. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11848. {
  11849. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11850. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11851. {
  11852. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11853. }
  11854. else
  11855. {
  11856. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11857. }
  11858. }
  11859. }
  11860. else if (!checkType->IsValuelessType())
  11861. {
  11862. _SetupParam(curName, checkType);
  11863. }
  11864. };
  11865. checkTypeLambda(resolvedTypeRef, paramName);
  11866. paramIdx++;
  11867. continue;
  11868. }
  11869. _SetupParam(paramName, resolvedTypeRef);
  11870. //argIdx++;
  11871. paramIdx++;
  11872. }
  11873. }
  11874. void BfModule::EmitCtorBody(bool& skipBody)
  11875. {
  11876. auto methodInstance = mCurMethodInstance;
  11877. auto methodDef = methodInstance->mMethodDef;
  11878. auto methodDeclaration = methodDef->mMethodDeclaration;
  11879. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11880. auto typeDef = mCurTypeInstance->mTypeDef;
  11881. // Prologue
  11882. mBfIRBuilder->ClearDebugLocation();
  11883. bool hadThisInitializer = false;
  11884. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11885. {
  11886. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11887. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11888. if (targetToken->GetToken() == BfToken_This)
  11889. {
  11890. hadThisInitializer = true;
  11891. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11892. mCurMethodState->LocalDefined(GetThisVariable());
  11893. }
  11894. }
  11895. // Zero out memory for default ctor
  11896. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11897. {
  11898. if (mCurTypeInstance->IsTypedPrimitive())
  11899. {
  11900. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11901. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  11902. }
  11903. else if (mCurTypeInstance->mInstSize > 0)
  11904. {
  11905. BfIRValue fillValue = GetConstValue8(0);
  11906. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  11907. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11908. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11909. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  11910. }
  11911. }
  11912. BfAstNode* baseCtorNode = NULL;
  11913. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  11914. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  11915. else if (methodDef->mBody != NULL)
  11916. baseCtorNode = methodDef->mBody;
  11917. else if (ctorDeclaration != NULL)
  11918. baseCtorNode = ctorDeclaration;
  11919. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  11920. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  11921. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  11922. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  11923. else
  11924. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  11925. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  11926. {
  11927. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  11928. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  11929. {
  11930. BfMethodDef* defaultCtor = NULL;
  11931. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  11932. {
  11933. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  11934. {
  11935. defaultCtor = methodDef;
  11936. }
  11937. }
  11938. if (defaultCtor != NULL)
  11939. {
  11940. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  11941. SetIllegalSrcPos();
  11942. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  11943. BfExprEvaluator exprEvaluator(this);
  11944. SizedArray<BfIRValue, 1> irArgs;
  11945. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  11946. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  11947. }
  11948. }
  11949. }
  11950. // Initialize fields (if applicable)
  11951. if (mCurTypeInstance->IsBoxed())
  11952. {
  11953. skipBody = true;
  11954. }
  11955. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  11956. {
  11957. // Field initializers occur in CtorNoBody methods for extensions
  11958. }
  11959. else if (!hadThisInitializer)
  11960. {
  11961. // If we had a 'this' initializer, that other ctor will have initialized our fields
  11962. if ((!mCompiler->mIsResolveOnly) ||
  11963. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  11964. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  11965. {
  11966. bool hadInlineInitBlock = false;
  11967. BfScopeData scopeData;
  11968. for (auto fieldDef : typeDef->mFields)
  11969. {
  11970. // For extensions, only handle these fields in the appropriate extension
  11971. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11972. continue;
  11973. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  11974. {
  11975. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11976. if (!fieldInst->mFieldIncluded)
  11977. continue;
  11978. if (fieldInst->mDataIdx < 0)
  11979. continue;
  11980. if (fieldDef->mInitializer == NULL)
  11981. {
  11982. if (fieldDef->mProtection != BfProtection_Hidden)
  11983. continue;
  11984. if (mCurTypeInstance->IsObject()) // Already zeroed out
  11985. continue;
  11986. }
  11987. if (fieldInst->mResolvedType == NULL)
  11988. {
  11989. BF_ASSERT(mHadBuildError);
  11990. continue;
  11991. }
  11992. if (fieldDef->mInitializer != NULL)
  11993. {
  11994. if (!hadInlineInitBlock)
  11995. {
  11996. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  11997. {
  11998. UpdateSrcPos(baseCtorNode);
  11999. // 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
  12000. EmitEnsureInstructionAt();
  12001. BfType* thisType = mCurTypeInstance;
  12002. if (thisType->IsValueType())
  12003. thisType = CreateRefType(thisType);
  12004. SizedArray<BfIRMDNode, 1> diParamTypes;
  12005. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12006. mCurMethodState->AddScope(&scopeData);
  12007. NewScopeState();
  12008. int flags = 0;
  12009. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12010. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12011. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12012. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12013. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12014. UpdateSrcPos(fieldDef->mInitializer);
  12015. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12016. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12017. //
  12018. {
  12019. auto loadedThis = GetThis();
  12020. // LLVM can't handle two variables pointing to the same value
  12021. BfIRValue copiedThisPtr;
  12022. copiedThisPtr = CreateAlloca(thisType);
  12023. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12024. mBfIRBuilder->ClearDebugLocation(storeInst);
  12025. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12026. }
  12027. hadInlineInitBlock = true;
  12028. }
  12029. }
  12030. UpdateSrcPos(fieldDef->mInitializer);
  12031. }
  12032. BfIRValue fieldAddr;
  12033. if (!mCurTypeInstance->IsTypedPrimitive())
  12034. {
  12035. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12036. }
  12037. else
  12038. {
  12039. AssertErrorState();
  12040. }
  12041. auto assignValue = GetFieldInitializerValue(fieldInst);
  12042. if ((fieldAddr) && (assignValue))
  12043. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12044. }
  12045. }
  12046. if (hadInlineInitBlock)
  12047. {
  12048. RestoreScopeState();
  12049. // This gets set to false because of AddScope but we actually are still in the head block
  12050. mCurMethodState->mInHeadScope = true;
  12051. }
  12052. }
  12053. else // Autocomplete case
  12054. {
  12055. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12056. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12057. // resolve pass, NOT the autocomplete expression
  12058. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12059. {
  12060. if (tempTypeDef->mFullName == typeDef->mFullName)
  12061. {
  12062. for (auto fieldDef : tempTypeDef->mFields)
  12063. {
  12064. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12065. {
  12066. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12067. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12068. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12069. if ((wantType != NULL) &&
  12070. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12071. wantType = NULL;
  12072. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12073. }
  12074. }
  12075. }
  12076. }
  12077. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12078. for (auto fieldDef : typeDef->mFields)
  12079. {
  12080. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12081. {
  12082. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12083. if (fieldDef->mInitializer != NULL)
  12084. MarkFieldInitialized(fieldInst);
  12085. }
  12086. }
  12087. }
  12088. }
  12089. // Call base ctor (if applicable)
  12090. BfTypeInstance* targetType = NULL;
  12091. BfAstNode* targetRefNode = NULL;
  12092. if (ctorDeclaration != NULL)
  12093. targetRefNode = ctorDeclaration->mInitializer;
  12094. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12095. targetRefNode = invocationExpr->mTarget;
  12096. if (baseCtorNode != NULL)
  12097. {
  12098. UpdateSrcPos(baseCtorNode);
  12099. }
  12100. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12101. {
  12102. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12103. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12104. }
  12105. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12106. {
  12107. auto baseType = mCurTypeInstance->mBaseType;
  12108. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12109. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12110. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12111. {
  12112. // Try to find a ctor without any params first
  12113. bool foundBaseCtor = false;
  12114. bool hadCtorWithAllDefaults = false;
  12115. for (int pass = 0; pass < 2; pass++)
  12116. {
  12117. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12118. {
  12119. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12120. // Allow calling of the default base ctor if it is implicitly defined
  12121. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12122. allowPriv = true;
  12123. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12124. {
  12125. if (checkMethodDef->mParams.size() == 0)
  12126. {
  12127. foundBaseCtor = true;
  12128. if (HasCompiledOutput())
  12129. {
  12130. SizedArray<BfIRValue, 1> args;
  12131. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12132. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12133. {
  12134. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12135. args.push_back(basePtr);
  12136. }
  12137. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12138. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12139. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12140. if (callingConv != BfIRCallingConv_CDecl)
  12141. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12142. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12143. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12144. break;
  12145. }
  12146. }
  12147. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12148. hadCtorWithAllDefaults = true;
  12149. }
  12150. }
  12151. if (foundBaseCtor)
  12152. break;
  12153. }
  12154. if (!foundBaseCtor)
  12155. {
  12156. targetType = mCurTypeInstance->mBaseType;
  12157. if (ctorDeclaration != NULL)
  12158. targetRefNode = ctorDeclaration->mThisToken;
  12159. else if (typeDef->mTypeDeclaration != NULL)
  12160. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12161. }
  12162. }
  12163. }
  12164. if (methodDef->mHasAppend)
  12165. {
  12166. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12167. }
  12168. if (targetType != NULL)
  12169. {
  12170. auto autoComplete = mCompiler->GetAutoComplete();
  12171. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12172. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12173. {
  12174. auto invocationExpr = ctorDeclaration->mInitializer;
  12175. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12176. }
  12177. BfType* targetThisType = targetType;
  12178. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12179. BfExprEvaluator exprEvaluator(this);
  12180. BfResolvedArgs argValues;
  12181. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12182. {
  12183. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12184. if (gDebugStuff)
  12185. {
  12186. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12187. }
  12188. }
  12189. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12190. BfTypedValue appendIdxVal;
  12191. if (methodDef->mHasAppend)
  12192. {
  12193. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12194. BF_ASSERT(localVar->mName == "appendIdx");
  12195. auto intRefType = CreateRefType(localVar->mResolvedType);
  12196. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12197. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12198. }
  12199. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12200. if (autoComplete != NULL)
  12201. {
  12202. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12203. {
  12204. if (autoComplete->mMethodMatchInfo != NULL)
  12205. autoComplete->mIsCapturingMethodMatchInfo = true;
  12206. else
  12207. autoComplete->mIsCapturingMethodMatchInfo = false;
  12208. }
  12209. else
  12210. autoComplete->mIsCapturingMethodMatchInfo = false;
  12211. }
  12212. }
  12213. }
  12214. void BfModule::EmitEnumToStringBody()
  12215. {
  12216. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12217. auto strVal = CreateAlloca(stringType);
  12218. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12219. BfExprEvaluator exprEvaluator(this);
  12220. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12221. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12222. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12223. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12224. BfType* discriminatorType = NULL;
  12225. BfTypedValue rawPayload;
  12226. BfIRValue enumVal;
  12227. if (mCurTypeInstance->IsPayloadEnum())
  12228. {
  12229. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12230. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12231. enumTypedValue = LoadValue(enumTypedValue);
  12232. enumVal = enumTypedValue.mValue;
  12233. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12234. }
  12235. else
  12236. enumVal = mBfIRBuilder->GetArgument(0);
  12237. Array<BfType*> paramTypes;
  12238. paramTypes.Add(stringType);
  12239. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12240. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12241. HashSet<int64> handledCases;
  12242. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12243. {
  12244. if (fieldInstance.mIsEnumPayloadCase)
  12245. {
  12246. int tagId = -fieldInstance.mDataIdx - 1;
  12247. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12248. mBfIRBuilder->AddBlock(caseBlock);
  12249. mBfIRBuilder->SetInsertPoint(caseBlock);
  12250. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12251. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12252. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12253. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12254. auto stringDestVal = LoadValue(stringDestAddr);
  12255. SizedArray<BfIRValue, 2> args;
  12256. args.Add(stringDestVal.mValue);
  12257. args.Add(caseStr);
  12258. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12259. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12260. BF_ASSERT(payloadType->IsTuple());
  12261. if (payloadType->mFieldInstances.size() != 0)
  12262. {
  12263. auto payload = rawPayload;
  12264. if (payload.mType != payloadType)
  12265. {
  12266. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12267. }
  12268. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12269. SizedArray<BfIRValue, 2> irArgs;
  12270. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12271. stringDestVal = LoadValue(stringDestAddr);
  12272. irArgs.Add(stringDestVal.mValue);
  12273. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12274. }
  12275. mBfIRBuilder->CreateBr(endBlock);
  12276. continue;
  12277. }
  12278. if (fieldInstance.mConstIdx == -1)
  12279. continue;
  12280. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12281. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12282. {
  12283. // Duplicate
  12284. continue;
  12285. }
  12286. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12287. mBfIRBuilder->AddBlock(caseBlock);
  12288. mBfIRBuilder->SetInsertPoint(caseBlock);
  12289. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12290. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12291. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12292. mBfIRBuilder->CreateStore(caseStr, strVal);
  12293. mBfIRBuilder->CreateBr(appendBlock);
  12294. }
  12295. mBfIRBuilder->AddBlock(appendBlock);
  12296. mBfIRBuilder->SetInsertPoint(appendBlock);
  12297. SizedArray<BfIRValue, 2> args;
  12298. auto stringDestVal = LoadValue(stringDestAddr);
  12299. args.Add(stringDestVal.mValue);
  12300. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12301. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12302. mBfIRBuilder->CreateBr(endBlock);
  12303. mBfIRBuilder->AddBlock(noMatchBlock);
  12304. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12305. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12306. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12307. args.clear();
  12308. args.Add(int64Val);
  12309. stringDestVal = LoadValue(stringDestAddr);
  12310. args.Add(stringDestVal.mValue);
  12311. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12312. mBfIRBuilder->CreateBr(endBlock);
  12313. mBfIRBuilder->AddBlock(endBlock);
  12314. mBfIRBuilder->SetInsertPoint(endBlock);
  12315. }
  12316. void BfModule::EmitTupleToStringBody()
  12317. {
  12318. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12319. BfExprEvaluator exprEvaluator(this);
  12320. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12321. Array<BfType*> paramTypes;
  12322. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12323. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12324. paramTypes.Clear();
  12325. paramTypes.Add(stringType);
  12326. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12327. auto _AppendChar = [&](char c)
  12328. {
  12329. SizedArray<BfIRValue, 2> args;
  12330. auto stringDestVal = LoadValue(stringDestRef);
  12331. args.Add(stringDestVal.mValue);
  12332. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12333. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12334. };
  12335. int fieldIdx = 0;
  12336. auto thisValue = GetThis();
  12337. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12338. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12339. BfIRValue commaStr;
  12340. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12341. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12342. _AppendChar('(');
  12343. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12344. {
  12345. if (fieldInstance.mDataIdx == -1)
  12346. continue;
  12347. if (fieldIdx > 0)
  12348. {
  12349. if (!commaStr)
  12350. commaStr = GetStringObjectValue(", ");
  12351. SizedArray<BfIRValue, 2> args;
  12352. auto stringDestVal = LoadValue(stringDestRef);
  12353. args.Add(stringDestVal.mValue);
  12354. args.Add(commaStr);
  12355. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12356. }
  12357. fieldIdx++;
  12358. if (fieldInstance.mResolvedType->IsValuelessType())
  12359. continue;
  12360. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12361. if (fieldValue.mType->IsPrimitiveType())
  12362. {
  12363. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12364. }
  12365. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12366. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12367. {
  12368. BfExprEvaluator exprEvaluator(this);
  12369. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12370. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12371. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12372. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12373. methodMatcher.TryDevirtualizeCall(fieldValue);
  12374. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12375. BfResolvedArg resolvedArg;
  12376. auto stringDestVal = LoadValue(stringDestRef);
  12377. resolvedArg.mTypedValue = stringDestVal;
  12378. resolvedArg.mResolvedType = stringDestVal.mType;
  12379. resolvedArgs.Add(resolvedArg);
  12380. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12381. continue;
  12382. }
  12383. if (fieldValue.mType->IsObjectOrInterface())
  12384. {
  12385. BF_ASSERT(!fieldValue.IsAddr());
  12386. SizedArray<BfIRValue, 2> args;
  12387. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12388. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12389. stringDestVal = LoadValue(stringDestVal);
  12390. args.Add(stringDestVal.mValue);
  12391. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12392. continue;
  12393. }
  12394. BfExprEvaluator exprEvaluator(this);
  12395. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12396. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12397. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12398. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12399. methodMatcher.TryDevirtualizeCall(fieldValue);
  12400. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12401. {
  12402. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12403. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12404. // Just append the type name
  12405. String typeName = TypeToString(fieldInstance.mResolvedType);
  12406. auto strVal = GetStringObjectValue(typeName);
  12407. SizedArray<BfIRValue, 2> args;
  12408. auto stringDestVal = LoadValue(stringDestRef);
  12409. args.Add(stringDestVal.mValue);
  12410. args.Add(strVal);
  12411. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12412. continue;
  12413. }
  12414. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12415. BfResolvedArg resolvedArg;
  12416. auto stringDestVal = LoadValue(stringDestRef);
  12417. resolvedArg.mTypedValue = stringDestVal;
  12418. resolvedArg.mResolvedType = stringDestVal.mType;
  12419. resolvedArgs.Add(resolvedArg);
  12420. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12421. }
  12422. _AppendChar(')');
  12423. }
  12424. void BfModule::EmitIteratorBlock(bool& skipBody)
  12425. {
  12426. auto methodInstance = mCurMethodInstance;
  12427. auto methodDef = methodInstance->mMethodDef;
  12428. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12429. auto typeDef = mCurTypeInstance->mTypeDef;
  12430. BfType* innerRetType = NULL;
  12431. BfTypeInstance* usingInterface = NULL;
  12432. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12433. if (retTypeInst != NULL)
  12434. {
  12435. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12436. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12437. {
  12438. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12439. }
  12440. }
  12441. if (innerRetType == NULL)
  12442. {
  12443. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12444. return;
  12445. }
  12446. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12447. if (blockBody == NULL)
  12448. return;
  12449. }
  12450. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12451. {
  12452. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12453. if (fieldTypeInst == NULL)
  12454. return;
  12455. if (!markVal.mType->IsComposite())
  12456. markVal = LoadValue(markVal);
  12457. BfExprEvaluator exprEvaluator(this);
  12458. PopulateType(markVal.mType, BfPopulateType_Data);
  12459. if (markVal.mType->IsObjectOrInterface())
  12460. {
  12461. BfIRValue val = markVal.mValue;
  12462. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12463. SizedArray<BfIRValue, 1> args;
  12464. args.push_back(val);
  12465. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12466. }
  12467. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12468. {
  12469. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12470. if (markMemberMethodInstance)
  12471. {
  12472. SizedArray<BfIRValue, 1> args;
  12473. //(1, markVal.mValue);
  12474. //exprEvaluator.PushArg(markVal, args);
  12475. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12476. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12477. }
  12478. }
  12479. }
  12480. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12481. {
  12482. Array<BfMethodInstance*> methodInstances;
  12483. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12484. {
  12485. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12486. auto chainedMethodInst = methodInstGroup.mDefault;
  12487. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12488. {
  12489. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12490. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12491. {
  12492. methodInstances.push_back(chainedMethodInst);
  12493. }
  12494. }
  12495. }
  12496. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12497. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12498. {
  12499. bool isBetter;
  12500. bool isWorse;
  12501. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12502. if (isBetter == isWorse)
  12503. {
  12504. return false;
  12505. }
  12506. return isWorse;
  12507. });
  12508. if (reverse)
  12509. std::reverse(methodInstances.begin(), methodInstances.end());
  12510. for (auto chainedMethodInst : methodInstances)
  12511. {
  12512. auto declModule = this;
  12513. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12514. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12515. BfExprEvaluator exprEvaluator(this);
  12516. SizedArray<BfIRValue, 1> args;
  12517. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12518. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12519. }
  12520. }
  12521. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12522. {
  12523. BF_ASSERT(mCurMethodInstance->mIsReified);
  12524. if (mCurTypeInstance->mHotTypeData == NULL)
  12525. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12526. auto hotMethod = mCurMethodInstance->mHotMethod;
  12527. for (auto depData : hotMethod->mReferences)
  12528. {
  12529. // Only virtual decls are allowed to already be there
  12530. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12531. }
  12532. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12533. int prevSize = (int)hotMethod->mReferences.size();
  12534. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12535. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12536. refCount++;
  12537. hotMethod->mReferences.Reserve(refCount);
  12538. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12539. {
  12540. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12541. hotThis->mRefCount++;
  12542. hotMethod->mReferences.Insert(0, hotThis);
  12543. prevSize++;
  12544. }
  12545. for (auto val : builder->mAllocatedData)
  12546. {
  12547. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12548. hotMethod->mReferences.Add(hotAllocation);
  12549. }
  12550. for (auto val : builder->mUsedData)
  12551. hotMethod->mReferences.Add(val);
  12552. for (auto val : builder->mCalledMethods)
  12553. hotMethod->mReferences.Add(val);
  12554. for (auto val : builder->mDevirtualizedCalledMethods)
  12555. {
  12556. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12557. hotMethod->mReferences.Add(devirtualizedMethod);
  12558. }
  12559. for (auto val : builder->mFunctionPtrs)
  12560. {
  12561. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12562. hotMethod->mReferences.Add(funcRef);
  12563. }
  12564. for (auto val : builder->mInnerMethods)
  12565. {
  12566. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12567. hotMethod->mReferences.Add(innerMethod);
  12568. }
  12569. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12570. {
  12571. auto depData = hotMethod->mReferences[refIdx];
  12572. BF_ASSERT(depData != NULL);
  12573. depData->mRefCount++;
  12574. }
  12575. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12576. }
  12577. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12578. {
  12579. auto methodDef = methodInstance->mMethodDef;
  12580. auto methodDeclaration = methodDef->mMethodDeclaration;
  12581. if (methodDef->mName == "GetIt")
  12582. {
  12583. NOP;
  12584. }
  12585. bool isThisStruct = false;
  12586. if (thisType != NULL)
  12587. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12588. int argIdx = 0;
  12589. if (methodInstance->HasStructRet())
  12590. argIdx++;
  12591. if (!methodDef->mIsStatic)
  12592. {
  12593. BfLocalVariable* paramVar = new BfLocalVariable();
  12594. paramVar->mResolvedType = thisType;
  12595. paramVar->mName = "this";
  12596. if (!thisType->IsValuelessType())
  12597. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12598. else
  12599. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12600. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12601. {
  12602. if (thisType->IsSplattable())
  12603. paramVar->mIsSplat = true;
  12604. else
  12605. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12606. }
  12607. auto thisTypeInst = thisType->ToTypeInstance();
  12608. paramVar->mIsStruct = isThisStruct;
  12609. paramVar->mAddr = BfIRValue();
  12610. paramVar->mIsThis = true;
  12611. paramVar->mParamIdx = -1;
  12612. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12613. {
  12614. paramVar->mIsAssigned = false;
  12615. }
  12616. else
  12617. {
  12618. paramVar->mIsAssigned = true;
  12619. }
  12620. paramVar->mReadFromId = -1;
  12621. paramVar->Init();
  12622. if (methodDeclaration == NULL)
  12623. UseDefaultSrcPos();
  12624. AddLocalVariableDef(paramVar);
  12625. if (!thisType->IsValuelessType())
  12626. {
  12627. if (wantsDIData)
  12628. {
  12629. BfType* thisPtrType = thisType;
  12630. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12631. if (!thisType->IsValueType())
  12632. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12633. diParams->push_back(diType);
  12634. }
  12635. if (paramVar->mIsSplat)
  12636. {
  12637. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12638. }
  12639. else
  12640. {
  12641. argIdx++;
  12642. }
  12643. }
  12644. }
  12645. bool hadParams = false;
  12646. bool hasDefault = false;
  12647. int compositeVariableIdx = -1;
  12648. int paramIdx = 0;
  12649. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12650. {
  12651. // We already issues a type error for this param if we had one in declaration processing
  12652. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12653. BfLocalVariable* paramVar = new BfLocalVariable();
  12654. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12655. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12656. if (unresolvedType == NULL)
  12657. {
  12658. AssertErrorState();
  12659. unresolvedType = mContext->mBfObjectType;
  12660. paramVar->mParamFailed = true;
  12661. }
  12662. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12663. prevIgnoreErrors.Restore();
  12664. PopulateType(resolvedType, BfPopulateType_Declaration);
  12665. paramVar->mResolvedType = resolvedType;
  12666. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12667. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12668. if (!isParamSkipped)
  12669. {
  12670. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12671. if (resolvedType->IsMethodRef())
  12672. {
  12673. paramVar->mIsSplat = true;
  12674. }
  12675. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12676. {
  12677. int splatCount = resolvedType->GetSplatCount();
  12678. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12679. paramVar->mIsSplat = true;
  12680. }
  12681. }
  12682. else
  12683. {
  12684. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12685. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12686. }
  12687. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12688. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12689. paramVar->mParamIdx = paramIdx;
  12690. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12691. paramVar->mReadFromId = 0;
  12692. if (resolvedType->IsRef())
  12693. {
  12694. auto refType = (BfRefType*)resolvedType;
  12695. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12696. }
  12697. else
  12698. {
  12699. paramVar->mIsAssigned = true;
  12700. if (methodDef->mMethodType != BfMethodType_Mixin)
  12701. paramVar->mIsReadOnly = true;
  12702. }
  12703. if (paramVar->mResolvedType->IsGenericParam())
  12704. {
  12705. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12706. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12707. {
  12708. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12709. paramVar->mResolvedType = typedVal.mType;
  12710. paramVar->mConstValue = typedVal.mValue;
  12711. }
  12712. }
  12713. if (paramVar->mResolvedType->IsConstExprValue())
  12714. {
  12715. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12716. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12717. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12718. BF_ASSERT(unspecParamType->IsGenericParam());
  12719. if (unspecParamType->IsGenericParam())
  12720. {
  12721. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12722. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12723. {
  12724. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12725. if (genericParamInst->mTypeConstraint != NULL)
  12726. {
  12727. BfExprEvaluator exprEvaluator(this);
  12728. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12729. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12730. auto checkType = genericParamInst->mTypeConstraint;
  12731. if (checkType->IsTypedPrimitive())
  12732. checkType = checkType->GetUnderlyingType();
  12733. if (exprEvaluator.mResult.mType == checkType)
  12734. {
  12735. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12736. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12737. BF_ASSERT(paramVar->mConstValue.IsConst());
  12738. }
  12739. else
  12740. {
  12741. AssertErrorState();
  12742. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12743. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12744. }
  12745. }
  12746. }
  12747. }
  12748. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12749. if (paramVar->mResolvedType->IsConstExprValue())
  12750. {
  12751. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12752. //AssertErrorState();
  12753. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12754. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12755. }
  12756. }
  12757. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12758. {
  12759. if (compositeVariableIdx == -1)
  12760. {
  12761. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12762. BfLocalVariable* localVar = new BfLocalVariable();
  12763. auto paramInst = &methodInstance->mParams[paramIdx];
  12764. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12765. localVar->mName = paramDef->mName;
  12766. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12767. localVar->mCompositeCount = 0;
  12768. DoAddLocalVariable(localVar);
  12769. }
  12770. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12771. }
  12772. CheckVariableDef(paramVar);
  12773. paramVar->Init();
  12774. AddLocalVariableDef(paramVar);
  12775. if (!isParamSkipped)
  12776. {
  12777. if (wantsDIData)
  12778. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12779. if (paramVar->mIsSplat)
  12780. {
  12781. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12782. }
  12783. else
  12784. {
  12785. argIdx++;
  12786. }
  12787. }
  12788. }
  12789. // Try to find an ending delegate params composite
  12790. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12791. {
  12792. auto paramDef = methodDef->mParams.back();
  12793. if (paramDef->mParamKind == BfParamKind_Params)
  12794. {
  12795. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12796. if (paramsType == NULL)
  12797. {
  12798. AssertErrorState();
  12799. }
  12800. else if (paramsType->IsGenericParam())
  12801. {
  12802. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12803. if (genericParamInstance->mTypeConstraint != NULL)
  12804. {
  12805. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12806. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12807. ((typeInstConstraint != NULL) &&
  12808. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12809. {
  12810. BfLocalVariable* localVar = new BfLocalVariable();
  12811. localVar->mName = paramDef->mName;
  12812. localVar->mResolvedType = paramsType;
  12813. localVar->mCompositeCount = 0;
  12814. DoAddLocalVariable(localVar);
  12815. }
  12816. }
  12817. }
  12818. else if (paramsType->IsDelegate())
  12819. {
  12820. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12821. if (invokeMethodInstance != NULL)
  12822. {
  12823. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12824. // and wasn't cleared by the preceding loop
  12825. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12826. BfLocalVariable* localVar = new BfLocalVariable();
  12827. localVar->mName = paramDef->mName;
  12828. localVar->mResolvedType = paramsType;
  12829. localVar->mCompositeCount = 0;
  12830. DoAddLocalVariable(localVar);
  12831. }
  12832. }
  12833. }
  12834. }
  12835. }
  12836. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12837. {
  12838. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12839. // return;
  12840. auto _ClearState = [&]()
  12841. {
  12842. mCurMethodState->mLocalMethods.Clear();
  12843. for (auto& local : mCurMethodState->mLocals)
  12844. delete local;
  12845. mCurMethodState->mLocals.Clear();
  12846. mCurMethodState->mLocalVarSet.Clear();
  12847. };
  12848. // 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
  12849. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12850. // however (compiler bug), so this is the safest way
  12851. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12852. {
  12853. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12854. {
  12855. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12856. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12857. if (!mHadBuildError)
  12858. {
  12859. // Process as a closure - that allows us to look back and see the const locals and stuff
  12860. BfClosureState closureState;
  12861. mCurMethodState->mClosureState = &closureState;
  12862. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12863. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12864. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12865. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12866. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12867. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12868. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12869. _ClearState();
  12870. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12871. {
  12872. auto localVar = new BfLocalVariable();
  12873. *localVar = constLocal;
  12874. DoAddLocalVariable(localVar);
  12875. }
  12876. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12877. bool doProcess = !mCompiler->mCanceling;
  12878. if (doProcess)
  12879. {
  12880. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12881. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12882. }
  12883. }
  12884. delete deferredLocalMethod;
  12885. mSystem->CheckLockYield();
  12886. }
  12887. }
  12888. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12889. {
  12890. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12891. }
  12892. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12893. {
  12894. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12895. {
  12896. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12897. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12898. BfClosureState closureState;
  12899. mCurMethodState->mClosureState = &closureState;
  12900. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12901. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12902. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  12903. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12904. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  12905. _ClearState();
  12906. for (auto& constLocal : lambdaInstance->mConstLocals)
  12907. {
  12908. //if (constLocal.mIsThis)
  12909. {
  12910. // Valueless 'this'
  12911. closureState.mConstLocals.Add(constLocal);
  12912. }
  12913. /*else
  12914. {
  12915. auto localVar = new BfLocalVariable();
  12916. *localVar = constLocal;
  12917. DoAddLocalVariable(localVar);
  12918. }*/
  12919. }
  12920. BfMethodInstanceGroup methodInstanceGroup;
  12921. methodInstanceGroup.mOwner = mCurTypeInstance;
  12922. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12923. bool doProcess = !mCompiler->mCanceling;
  12924. if (doProcess)
  12925. {
  12926. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  12927. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  12928. ProcessMethod(lambdaInstance->mMethodInstance);
  12929. if (lambdaInstance->mDtorMethodInstance != NULL)
  12930. {
  12931. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  12932. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  12933. }
  12934. }
  12935. }
  12936. mSystem->CheckLockYield();
  12937. }
  12938. }
  12939. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12940. {
  12941. if (checkType->IsComposite())
  12942. PopulateType(checkType, BfPopulateType_Data);
  12943. if (!checkType->WantsGCMarking())
  12944. return;
  12945. auto typeInstance = checkType->ToTypeInstance();
  12946. bool callMarkMethod = false;
  12947. // Call the actual marking method
  12948. if (memberDepth == 0)
  12949. {
  12950. // Don't call marking method on self
  12951. }
  12952. else if (checkType->IsObjectOrInterface())
  12953. {
  12954. if (!objectOffsets.Add(curOffset))
  12955. {
  12956. return;
  12957. }
  12958. callMarkMethod = true;
  12959. }
  12960. else if (checkType->IsSizedArray())
  12961. {
  12962. callMarkMethod = true;
  12963. }
  12964. else if (typeInstance != NULL)
  12965. {
  12966. typeInstance->mTypeDef->PopulateMemberSets();
  12967. BfMemberSetEntry* entry = NULL;
  12968. BfMethodDef* methodDef = NULL;
  12969. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  12970. {
  12971. methodDef = (BfMethodDef*)entry->mMemberDef;
  12972. if (methodDef->HasBody())
  12973. {
  12974. callMarkMethod = true;
  12975. }
  12976. }
  12977. }
  12978. if (callMarkMethod)
  12979. {
  12980. BfTypedValue markValue;
  12981. auto memberType = checkType;
  12982. if (memberType->IsObjectOrInterface())
  12983. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  12984. auto memberPtrType = CreatePointerType(memberType);
  12985. if (curOffset == 0)
  12986. {
  12987. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  12988. }
  12989. else
  12990. {
  12991. if (!thisValue.mType->IsPointer())
  12992. {
  12993. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  12994. auto int8PtrType = CreatePointerType(int8Type);
  12995. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  12996. }
  12997. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  12998. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  12999. }
  13000. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13001. return;
  13002. }
  13003. auto methodDef = mCurMethodInstance->mMethodDef;
  13004. if (checkType->IsPayloadEnum())
  13005. {
  13006. for (auto& fieldInst : typeInstance->mFieldInstances)
  13007. {
  13008. if (!fieldInst.mIsEnumPayloadCase)
  13009. continue;
  13010. auto fieldDef = fieldInst.GetFieldDef();
  13011. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13012. }
  13013. return;
  13014. }
  13015. if (typeInstance == NULL)
  13016. return;
  13017. for (auto& fieldInst : typeInstance->mFieldInstances)
  13018. {
  13019. auto fieldDef = fieldInst.GetFieldDef();
  13020. if (fieldDef == NULL)
  13021. continue;
  13022. if (fieldDef->mIsStatic)
  13023. continue;
  13024. if (typeInstance == mCurTypeInstance)
  13025. {
  13026. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13027. // we may be marking member values that can never contain a value anyway, but this is benign
  13028. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13029. continue;
  13030. }
  13031. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13032. }
  13033. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13034. {
  13035. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13036. }
  13037. }
  13038. void BfModule::EmitGCMarkMembers()
  13039. {
  13040. auto methodDef = mCurMethodInstance->mMethodDef;
  13041. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13042. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13043. if (gcType != NULL)
  13044. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13045. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13046. {
  13047. if (mCurTypeInstance->IsBoxed())
  13048. {
  13049. // This already gets filled in by the normal boxed forwarding
  13050. }
  13051. else
  13052. {
  13053. auto thisValue = GetThis();
  13054. if (thisValue.IsSplat())
  13055. {
  13056. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13057. int argIdx = 0;
  13058. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13059. {
  13060. if (checkType->IsStruct())
  13061. {
  13062. auto checkTypeInstance = checkType->ToTypeInstance();
  13063. if (checkTypeInstance->mBaseType != NULL)
  13064. checkTypeLambda(checkTypeInstance->mBaseType);
  13065. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13066. {
  13067. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13068. if (fieldInstance->mDataIdx >= 0)
  13069. checkTypeLambda(fieldInstance->GetResolvedType());
  13070. }
  13071. }
  13072. else if (checkType->IsMethodRef())
  13073. {
  13074. BF_FATAL("Not handled");
  13075. }
  13076. else if (checkType->WantsGCMarking())
  13077. {
  13078. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13079. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13080. argIdx++;
  13081. }
  13082. };
  13083. checkTypeLambda(thisValue.mType);
  13084. }
  13085. else if (!methodDef->mIsStatic)
  13086. {
  13087. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13088. {
  13089. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13090. if (moduleMethodInst)
  13091. {
  13092. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13093. if (methodBaseType != mContext->mBfObjectType)
  13094. {
  13095. auto thisValue = GetThis();
  13096. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13097. SizedArray<BfIRValue, 1> args;
  13098. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13099. {
  13100. BfExprEvaluator exprEvaluator(this);
  13101. exprEvaluator.SplatArgs(baseValue, args);
  13102. }
  13103. else
  13104. {
  13105. args.push_back(baseValue.mValue);
  13106. }
  13107. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13108. }
  13109. }
  13110. }
  13111. }
  13112. if (!methodDef->mIsStatic)
  13113. {
  13114. HashSet<int> objectOffsets;
  13115. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13116. }
  13117. else
  13118. {
  13119. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13120. {
  13121. if (thisValue.IsSplat())
  13122. break;
  13123. auto fieldDef = fieldInst.GetFieldDef();
  13124. if (fieldDef == NULL)
  13125. continue;
  13126. if (fieldInst.mIsThreadLocal)
  13127. continue;
  13128. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13129. {
  13130. // For extensions, only handle these fields in the appropriate extension
  13131. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13132. continue;
  13133. if (!fieldInst.mFieldIncluded)
  13134. continue;
  13135. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13136. if (fieldTypeInst != NULL)
  13137. {
  13138. auto fieldDef = fieldInst.GetFieldDef();
  13139. BfTypedValue markVal;
  13140. if (fieldDef->mIsConst)
  13141. continue;
  13142. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13143. continue;
  13144. mBfIRBuilder->PopulateType(fieldTypeInst);
  13145. if (fieldTypeInst->IsValuelessType())
  13146. continue;
  13147. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13148. {
  13149. markVal = ReferenceStaticField(&fieldInst);
  13150. }
  13151. else if (!fieldDef->mIsStatic)
  13152. {
  13153. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13154. }
  13155. if (markVal)
  13156. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13157. }
  13158. }
  13159. }
  13160. }
  13161. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13162. CallChainedMethods(mCurMethodInstance, false);
  13163. }
  13164. }
  13165. }
  13166. void BfModule::EmitGCFindTLSMembers()
  13167. {
  13168. auto methodDef = mCurMethodInstance->mMethodDef;
  13169. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13170. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13171. BF_ASSERT(reportTLSMark);
  13172. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13173. {
  13174. auto fieldDef = fieldInst.GetFieldDef();
  13175. if (fieldDef == NULL)
  13176. continue;
  13177. if (!fieldInst.mIsThreadLocal)
  13178. continue;
  13179. // For extensions, only handle these fields in the appropriate extension
  13180. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13181. continue;
  13182. if (!fieldInst.mFieldIncluded)
  13183. continue;
  13184. if (fieldDef->mIsConst)
  13185. continue;
  13186. auto fieldType = fieldInst.mResolvedType;
  13187. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13188. continue;
  13189. if (fieldType->IsValuelessType())
  13190. continue;
  13191. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13192. if (markVal)
  13193. {
  13194. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13195. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13196. SizedArray<BfIRValue, 2> llvmArgs;
  13197. llvmArgs.push_back(fieldRefPtr);
  13198. llvmArgs.push_back(markFuncPtr);
  13199. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13200. }
  13201. }
  13202. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13203. CallChainedMethods(mCurMethodInstance, false);
  13204. }
  13205. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13206. {
  13207. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13208. if (mAwaitingInitFinish)
  13209. FinishInit();
  13210. if (!methodInstance->mIsReified)
  13211. BF_ASSERT(!mIsReified);
  13212. if (methodInstance->mMethodInfoEx != NULL)
  13213. {
  13214. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13215. {
  13216. if (methodGenericArg->IsMethodRef())
  13217. {
  13218. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13219. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13220. }
  13221. }
  13222. }
  13223. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13224. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13225. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13226. {
  13227. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13228. }
  13229. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13230. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13231. (mCompiler->mResolvePassData != NULL))
  13232. {
  13233. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13234. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13235. }
  13236. if (methodInstance->mHasBeenProcessed)
  13237. {
  13238. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13239. return;
  13240. }
  13241. if (methodInstance->mFailedConstraints)
  13242. {
  13243. // The only way this should be able to happen is if we fail our generic param check
  13244. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13245. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13246. methodInstance->mHasBeenProcessed = true;
  13247. return;
  13248. }
  13249. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13250. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13251. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13252. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13253. {
  13254. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13255. auto owningModule = methodInstance->GetOwner()->mModule;
  13256. if (owningModule->mIsScratchModule)
  13257. {
  13258. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13259. }
  13260. else
  13261. {
  13262. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13263. if (owningModule->mOnDemandMethodCount > 0)
  13264. owningModule->mOnDemandMethodCount--;
  13265. }
  13266. }
  13267. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13268. // self-referencing append allocations in ctor@calcAppend
  13269. methodInstance->mHasBeenProcessed = true;
  13270. mIncompleteMethodCount--;
  13271. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13272. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13273. auto methodDef = methodInstance->mMethodDef;
  13274. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13275. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13276. {
  13277. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13278. // so we get the new vdata for it
  13279. methodInstance->GetOwner()->mDirty = true;
  13280. }
  13281. int dependentGenericStartIdx = 0;
  13282. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13283. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13284. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13285. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13286. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13287. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13288. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13289. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13290. if ((methodInstance->mIsReified) &&
  13291. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13292. {
  13293. mCurTypeInstance->mHasBeenInstantiated = true;
  13294. }
  13295. // Warnings are shown in the capture phase
  13296. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13297. mIgnoreWarnings = true;
  13298. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13299. UseDefaultSrcPos();
  13300. // We may not actually be populated in relatively rare autocompelte cases
  13301. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13302. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13303. BfAstNode* nameNode = NULL;
  13304. if (methodDeclaration != NULL)
  13305. {
  13306. nameNode = methodDeclaration->mNameNode;
  13307. if (nameNode == NULL)
  13308. {
  13309. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13310. nameNode = ctorDeclaration->mThisToken;
  13311. }
  13312. }
  13313. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13314. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13315. {
  13316. if (methodInstance->GetExplicitInterface() == NULL)
  13317. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13318. else
  13319. {
  13320. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13321. {
  13322. auto ifaceInst = ifaceEntry.mInterfaceType;
  13323. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13324. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13325. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13326. continue;
  13327. ifaceInst->mTypeDef->PopulateMemberSets();
  13328. BfMethodDef* nextMethod = NULL;
  13329. BfMemberSetEntry* entry = NULL;
  13330. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13331. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13332. while (nextMethod != NULL)
  13333. {
  13334. auto checkMethod = nextMethod;
  13335. nextMethod = nextMethod->mNextWithSameName;
  13336. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13337. if (implMethodInst == methodInstance)
  13338. {
  13339. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13340. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13341. }
  13342. }
  13343. }
  13344. }
  13345. if (methodDef->mIsOverride)
  13346. {
  13347. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13348. {
  13349. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13350. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13351. continue;
  13352. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13353. if (virtMethod != NULL)
  13354. {
  13355. if (virtMethod == methodInstance)
  13356. {
  13357. // Is matching method
  13358. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13359. {
  13360. auto baseType = mCurTypeInstance->mBaseType;
  13361. if (baseType != NULL)
  13362. {
  13363. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13364. baseType = baseType->mBaseType;
  13365. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13366. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13367. }
  13368. }
  13369. break;
  13370. }
  13371. }
  13372. }
  13373. }
  13374. }
  13375. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13376. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13377. {
  13378. if (mBfIRBuilder->mIgnoreWrites)
  13379. return;
  13380. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13381. if (!methodInstance->mIRFunction)
  13382. {
  13383. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13384. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13385. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13386. }
  13387. if (HasCompiledOutput())
  13388. {
  13389. BfDllImportEntry dllImportEntry;
  13390. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13391. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13392. mDllImportEntries.push_back(dllImportEntry);
  13393. }
  13394. return;
  13395. }
  13396. StringT<128> mangledName;
  13397. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13398. if (!methodInstance->mIRFunction)
  13399. {
  13400. bool isIntrinsic = false;
  13401. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13402. }
  13403. if (methodInstance->mIsIntrinsic)
  13404. return;
  13405. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13406. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13407. if (methodDef->mBody != NULL)
  13408. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13409. else if (methodDeclaration != NULL)
  13410. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13411. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13412. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13413. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13414. {
  13415. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13416. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13417. {
  13418. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13419. }
  13420. }
  13421. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13422. BfMethodState methodState;
  13423. if (mCurMethodState != NULL)
  13424. methodState.mClosureState = mCurMethodState->mClosureState;
  13425. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13426. {
  13427. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13428. if (methodInstance->mHotMethod == NULL)
  13429. CheckHotMethod(methodInstance, mangledName);
  13430. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13431. }
  13432. methodState.mPrevMethodState = mCurMethodState;
  13433. methodState.mMethodInstance = methodInstance;
  13434. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13435. if (methodInstance->GetCustomAttributes() != NULL)
  13436. {
  13437. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13438. if (typeOptionsIdx != -1)
  13439. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13440. }
  13441. BfTypeState typeState(mCurTypeInstance);
  13442. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13443. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13444. BfMethodInstance* unspecializedMethodInstance = NULL;
  13445. if ((prevMethodState.mPrevVal != NULL) &&
  13446. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13447. {
  13448. // This is 'inner' (probably a closure) - use binding from outer function
  13449. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13450. }
  13451. else if ((methodInstance->mIsUnspecialized) || (mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation))
  13452. {
  13453. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13454. }
  13455. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) || ((mCurTypeInstance->IsGenericTypeInstance())) && (!isGenericVariation)))
  13456. {
  13457. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13458. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13459. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13460. {
  13461. // Make sure the unspecialized method is processed so we can take its bindings
  13462. // Clear mCurMethodState so we don't think we're in a local method
  13463. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13464. mContext->ProcessMethod(unspecializedMethodInstance);
  13465. }
  13466. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13467. }
  13468. if (methodDef->mMethodType == BfMethodType_Operator)
  13469. {
  13470. auto operatorDef = (BfOperatorDef*) methodDef;
  13471. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13472. auto paramErrorRefNode = refNode;
  13473. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13474. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13475. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13476. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13477. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13478. {
  13479. if (methodDef->mParams.size() != 2)
  13480. {
  13481. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13482. }
  13483. else
  13484. {
  13485. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13486. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13487. {
  13488. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13489. }
  13490. }
  13491. BfType* wantType = NULL;
  13492. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13493. {
  13494. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13495. }
  13496. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13497. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13498. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13499. }
  13500. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13501. {
  13502. if (methodDef->mParams.size() != 1)
  13503. {
  13504. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13505. }
  13506. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13507. {
  13508. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13509. }
  13510. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13511. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13512. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13513. {
  13514. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13515. }
  13516. }
  13517. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13518. {
  13519. if (methodDef->mParams.size() != 1)
  13520. {
  13521. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13522. }
  13523. if (mCurMethodInstance->mReturnType->IsVoid())
  13524. {
  13525. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13526. }
  13527. }
  13528. else // Conversion
  13529. {
  13530. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13531. {
  13532. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13533. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13534. }
  13535. if (methodDef->mParams.size() != 1)
  13536. {
  13537. auto refNode = paramErrorRefNode;
  13538. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13539. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13540. Fail("Conversion operators must declare one parameter", refNode);
  13541. }
  13542. else
  13543. {
  13544. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13545. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13546. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13547. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13548. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13549. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13550. // happened here
  13551. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13552. {
  13553. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13554. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13555. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13556. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13557. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13558. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13559. }
  13560. }
  13561. }
  13562. }
  13563. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13564. if (methodDef->mMethodType == BfMethodType_Mixin)
  13565. wantsDIData = false;
  13566. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13567. wantsDIData = false;
  13568. bool wantsDIVariables = wantsDIData;
  13569. if (methodDef->mIsExtern)
  13570. wantsDIVariables = false;
  13571. SizedArray<BfIRMDNode, 8> diParams;
  13572. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13573. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13574. BfType* thisType = NULL;
  13575. if (!methodDef->mIsStatic)
  13576. {
  13577. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13578. thisType = methodState.mClosureState->mClosureType;
  13579. else
  13580. thisType = mCurTypeInstance;
  13581. }
  13582. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13583. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13584. //////////////////////////////////////////////////////////////////////////
  13585. //
  13586. {
  13587. if (methodDeclaration != NULL)
  13588. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13589. else if (methodDef->mBody != NULL)
  13590. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13591. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13592. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13593. }
  13594. BfIRMDNode diFunction;
  13595. if (wantsDIData)
  13596. {
  13597. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13598. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13599. int defLine = mCurFilePosition.mCurLine;
  13600. if (mDICompileUnit)
  13601. {
  13602. int flags = 0;
  13603. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13604. if (methodDef->mProtection == BfProtection_Public)
  13605. flags = llvm::DINode::FlagPublic;
  13606. else if (methodDef->mProtection == BfProtection_Protected)
  13607. flags = llvm::DINode::FlagProtected;
  13608. else
  13609. flags = llvm::DINode::FlagPrivate;
  13610. if (methodDef->mIsOverride)
  13611. {
  13612. //flags |= llvm::DINode::FlagVirtual;
  13613. }
  13614. else if (methodDef->mIsVirtual)
  13615. flags |= llvm::DINode::FlagIntroducedVirtual;
  13616. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13617. flags |= llvm::DINode::FlagStaticMember;
  13618. else
  13619. {
  13620. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13621. flags |= llvm::DINode::FlagStaticMember;
  13622. }
  13623. flags |= llvm::DINode::FlagPrototyped;
  13624. if (methodDef->mMethodType == BfMethodType_Ctor)
  13625. {
  13626. flags |= llvm::DINode::FlagArtificial;
  13627. }
  13628. auto llvmFunction = methodInstance->mIRFunction;
  13629. SizedArray<BfIRMDNode, 1> genericArgs;
  13630. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13631. String methodName;
  13632. if (methodInstance->GetForeignType() != NULL)
  13633. {
  13634. methodName += TypeToString(methodInstance->GetForeignType());
  13635. methodName += ".";
  13636. }
  13637. if (methodInstance->GetExplicitInterface() != NULL)
  13638. {
  13639. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13640. methodName += ".";
  13641. }
  13642. methodName += methodDef->mName;
  13643. if (methodInstance->GetNumGenericArguments() != 0)
  13644. {
  13645. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13646. {
  13647. if (genericArg->IsConstExprValue())
  13648. {
  13649. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13650. while (genericConstValueArgs.size() < genericArgs.size())
  13651. genericConstValueArgs.push_back(BfIRValue());
  13652. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13653. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13654. }
  13655. else
  13656. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13657. }
  13658. methodName += "<";
  13659. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13660. {
  13661. if (i > 0)
  13662. methodName += ", ";
  13663. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13664. methodName += TypeToString(type);
  13665. }
  13666. methodName += ">";
  13667. }
  13668. if ((methodName.empty()) && (methodDeclaration != NULL))
  13669. {
  13670. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13671. {
  13672. methodName += "operator";
  13673. if (operatorDecl->mIsConvOperator)
  13674. {
  13675. methodName += " ";
  13676. methodName += TypeToString(methodInstance->mReturnType);
  13677. }
  13678. else if (operatorDecl->mOpTypeToken != NULL)
  13679. methodName += operatorDecl->mOpTypeToken->ToString();
  13680. }
  13681. }
  13682. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13683. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13684. // defLine + 1, diFuncType, false, true,
  13685. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13686. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13687. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13688. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13689. defLine + 1, diFuncType, false, true,
  13690. llvm::dwarf::DW_VIRTUALITY_none,
  13691. 0,
  13692. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13693. }
  13694. }
  13695. //////////////////////////////////////////////////////////////////////////
  13696. // Head and Init get rolled into Entry afterwards.
  13697. methodState.mIRFunction = methodInstance->mIRFunction;
  13698. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13699. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13700. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13701. methodState.mCurScope->mDIScope = diFunction;
  13702. auto llvmEntryBlock = methodState.mIREntryBlock;
  13703. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13704. if (methodDef->mBody != NULL)
  13705. {
  13706. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13707. }
  13708. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13709. {
  13710. // We want to be able to step into delegate invokes -- we actually step over them
  13711. if (methodDef->mName != "Invoke")
  13712. {
  13713. UpdateSrcPos(typeDef->mTypeDeclaration);
  13714. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13715. }
  13716. }
  13717. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13718. mBfIRBuilder->ClearDebugLocation();
  13719. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13720. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13721. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13722. {
  13723. int localIdx = 0;
  13724. int argIdx = 0;
  13725. if (methodInstance->HasStructRet())
  13726. argIdx++;
  13727. //
  13728. bool doDbgAgg = false;
  13729. Array<BfIRValue> splatAddrValues;
  13730. for ( ; argIdx < irParamCount; localIdx++)
  13731. {
  13732. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13733. if ((isThis) && (thisType->IsValuelessType()))
  13734. isThis = false;
  13735. BfLocalVariable* paramVar = NULL;
  13736. while (true)
  13737. {
  13738. BF_ASSERT(localIdx < methodState.mLocals.size());
  13739. paramVar = methodState.mLocals[localIdx];
  13740. if ((paramVar->mCompositeCount == -1) &&
  13741. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13742. break;
  13743. localIdx++;
  13744. }
  13745. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13746. {
  13747. paramVar->mIsReadOnly = true;
  13748. }
  13749. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13750. if (paramVar->mResolvedType->IsMethodRef())
  13751. wantsAddr = false;
  13752. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13753. // {
  13754. // BF_ASSERT(paramVar->mName == "appendIdx");
  13755. // wantsAddr = true;
  13756. // }
  13757. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13758. {
  13759. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13760. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13761. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13762. {
  13763. BfIRType splatIRType;
  13764. if (checkType->IsComposite())
  13765. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13766. else
  13767. splatIRType = mBfIRBuilder->MapType(checkType);
  13768. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13769. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13770. if (!paramVar->mAddr)
  13771. paramVar->mAddr = allocaInst;
  13772. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13773. splatAddrValues.push_back(allocaInst);
  13774. }, paramVar->mResolvedType);
  13775. mBfIRBuilder->SetInsertPoint(prevInsert);
  13776. }
  13777. else if (isThis)
  13778. {
  13779. if (wantsAddr)
  13780. {
  13781. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13782. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13783. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13784. if (paramVar->mIsSplat)
  13785. {
  13786. if (doDbgAgg)
  13787. {
  13788. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13789. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13790. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13791. paramVar->mAddr = allocaInst;
  13792. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13793. }
  13794. }
  13795. else
  13796. {
  13797. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13798. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13799. wantPtr = true;
  13800. if (wantPtr)
  13801. {
  13802. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13803. }
  13804. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13805. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13806. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13807. paramVar->mAddr = allocaInst;
  13808. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13809. }
  13810. mBfIRBuilder->SetInsertPoint(prevInsert);
  13811. }
  13812. }
  13813. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13814. {
  13815. // Address doesn't change so we don't have to alloca it
  13816. BfIRType allocType;
  13817. int alignSize = mSystem->mPtrSize;
  13818. if (paramVar->mResolvedType->IsRef())
  13819. {
  13820. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13821. }
  13822. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13823. {
  13824. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13825. alignSize = paramVar->mResolvedType->mAlign;
  13826. }
  13827. else
  13828. {
  13829. paramVar->mHasLocalStructBacking = true;
  13830. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13831. if (typeInst != NULL)
  13832. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13833. else
  13834. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13835. }
  13836. if (wantsAddr)
  13837. {
  13838. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13839. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13840. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13841. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13842. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13843. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13844. paramVar->mAddr = allocaInst;
  13845. mBfIRBuilder->SetInsertPoint(prevInsert);
  13846. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13847. }
  13848. }
  13849. else if (wantsAddr)
  13850. {
  13851. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13852. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13853. paramVar->mAddr = allocaInst;
  13854. }
  13855. if (paramVar->mIsSplat)
  13856. {
  13857. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13858. }
  13859. else
  13860. {
  13861. argIdx++;
  13862. }
  13863. }
  13864. if (methodDef->mBody != NULL)
  13865. UpdateSrcPos(methodDef->mBody);
  13866. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13867. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13868. int declArgIdx = 0;
  13869. localIdx = 0;
  13870. argIdx = 0;
  13871. if (methodInstance->HasStructRet())
  13872. argIdx++;
  13873. int splatAddrIdx = 0;
  13874. while (localIdx < (int)methodState.mLocals.size())
  13875. {
  13876. int curLocalIdx = localIdx++;
  13877. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13878. if (!paramVar->IsParam())
  13879. continue;
  13880. if (paramVar->mCompositeCount != -1)
  13881. continue;
  13882. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13883. if ((isThis) && (thisType->IsValuelessType()))
  13884. isThis = false;
  13885. BfIRMDNode diVariable;
  13886. if (wantsDIData)
  13887. {
  13888. String paramName = paramVar->mName;
  13889. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13890. if (isThis)
  13891. {
  13892. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13893. paramName = "__closure";
  13894. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13895. {
  13896. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13897. bool wantRef = paramVar->mResolvedType->IsComposite();
  13898. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13899. wantRef = true;
  13900. if (wantRef)
  13901. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13902. }
  13903. else if (!paramVar->mResolvedType->IsValueType())
  13904. {
  13905. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  13906. }
  13907. }
  13908. else
  13909. {
  13910. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13911. {
  13912. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13913. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13914. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13915. }
  13916. }
  13917. if ((!paramVar->mIsSplat) || (doDbgAgg))
  13918. {
  13919. if (paramVar->mResolvedType->IsValuelessType())
  13920. {
  13921. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  13922. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  13923. }
  13924. else if (paramVar->mIsImplicitParam)
  13925. {
  13926. // Annotate this specially?
  13927. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  13928. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  13929. }
  13930. else
  13931. {
  13932. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  13933. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  13934. }
  13935. paramVar->mDbgVarInst = diVariable;
  13936. }
  13937. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  13938. {
  13939. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  13940. // {
  13941. // // Only add this placeholder if we don't have any values
  13942. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13943. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  13944. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  13945. // }
  13946. }
  13947. }
  13948. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  13949. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  13950. {
  13951. // Write our argument value into the .addr
  13952. mBfIRBuilder->ClearDebugLocation();
  13953. if (paramVar->mIsSplat)
  13954. {
  13955. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13956. if (doDbgAgg)
  13957. {
  13958. auto curArgIdx = argIdx;
  13959. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  13960. {
  13961. if (checkType->IsStruct())
  13962. {
  13963. auto checkTypeInstance = checkType->ToTypeInstance();
  13964. if (checkTypeInstance->mBaseType != NULL)
  13965. {
  13966. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  13967. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  13968. }
  13969. if (checkTypeInstance->mIsUnion)
  13970. {
  13971. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  13972. if (!unionInnerType->IsValuelessType())
  13973. {
  13974. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  13975. checkTypeLambda(unionInnerType, newDestAddr);
  13976. }
  13977. if (checkTypeInstance->IsEnum())
  13978. {
  13979. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  13980. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  13981. checkTypeLambda(dscrType, newDestAddr);
  13982. }
  13983. }
  13984. else
  13985. {
  13986. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13987. {
  13988. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13989. if (fieldInstance->mDataIdx >= 0)
  13990. {
  13991. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  13992. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  13993. }
  13994. }
  13995. }
  13996. }
  13997. else if (checkType->IsMethodRef())
  13998. {
  13999. BF_FATAL("Unimplemented");
  14000. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14001. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14002. // {
  14003. // checkTypeLambda->
  14004. // }
  14005. }
  14006. else if (!checkType->IsValuelessType())
  14007. {
  14008. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14009. curArgIdx++;
  14010. }
  14011. };
  14012. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14013. }
  14014. }
  14015. else
  14016. {
  14017. bool handled = false;
  14018. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14019. if (paramVar->mIsLowered)
  14020. {
  14021. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14022. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14023. if (loweredTypeCode != BfTypeCode_None)
  14024. {
  14025. // We have a lowered type coming in, so we have to cast the .addr before storing
  14026. auto primType = GetPrimitiveType(loweredTypeCode);
  14027. auto primPtrType = CreatePointerType(primType);
  14028. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14029. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14030. // We don't want to allow directly using value
  14031. paramVar->mValue = BfIRValue();
  14032. handled = true;
  14033. }
  14034. }
  14035. if (!handled)
  14036. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14037. }
  14038. }
  14039. if (!isThis)
  14040. declArgIdx++;
  14041. if (methodDef->mBody != NULL)
  14042. UpdateSrcPos(methodDef->mBody);
  14043. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14044. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14045. else if (methodDeclaration == NULL)
  14046. UseDefaultSrcPos();
  14047. // Write our argument value into the .addr
  14048. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14049. {
  14050. int splatComponentIdx = 0;
  14051. auto curArgIdx = argIdx;
  14052. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14053. {
  14054. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14055. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14056. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14057. mBfIRBuilder->ClearDebugLocation(storeInst);
  14058. if (wantsDIData)
  14059. {
  14060. BfIRMDNode diType;
  14061. if (checkType->IsComposite())
  14062. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14063. else
  14064. diType = mBfIRBuilder->DbgGetType(checkType);
  14065. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14066. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14067. if (wantsDIVariables)
  14068. {
  14069. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14070. }
  14071. }
  14072. curArgIdx++;
  14073. splatComponentIdx++;
  14074. };
  14075. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14076. {
  14077. if (checkType->IsStruct())
  14078. {
  14079. auto checkTypeInstance = checkType->ToTypeInstance();
  14080. if (checkTypeInstance->mBaseType != NULL)
  14081. {
  14082. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14083. }
  14084. if (checkTypeInstance->mIsUnion)
  14085. {
  14086. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14087. if (!unionInnerType->IsValuelessType())
  14088. {
  14089. _FinishSplatsIterate(unionInnerType, name + "$u");
  14090. }
  14091. if (checkTypeInstance->IsEnum())
  14092. {
  14093. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14094. _FinishSplatsIterate(dscrType, name + "$d");
  14095. }
  14096. }
  14097. else
  14098. {
  14099. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14100. {
  14101. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14102. auto fieldDef = fieldInstance->GetFieldDef();
  14103. if (fieldInstance->mDataIdx >= 0)
  14104. {
  14105. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14106. }
  14107. }
  14108. }
  14109. }
  14110. else if (checkType->IsMethodRef())
  14111. {
  14112. auto methodRefType = (BfMethodRefType*)checkType;
  14113. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14114. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14115. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14116. // {
  14117. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14118. // if (!paramType->IsValuelessType())
  14119. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14120. // }
  14121. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14122. {
  14123. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14124. String paramName = methodInstance->GetParamName(paramIdx);
  14125. if (paramName == "this")
  14126. paramName = "__this";
  14127. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14128. {
  14129. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14130. }
  14131. else
  14132. {
  14133. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14134. }
  14135. }
  14136. }
  14137. else if (!checkType->IsValuelessType())
  14138. {
  14139. _FinishSplats(checkType, name);
  14140. }
  14141. };
  14142. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14143. if (!paramVar->mConstValue)
  14144. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14145. }
  14146. BfIRValue declareCall;
  14147. if (diVariable)
  14148. {
  14149. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14150. {
  14151. if (!paramVar->mAddr)
  14152. {
  14153. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14154. {
  14155. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14156. {
  14157. // We don't need to set the location for this
  14158. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14159. }
  14160. }
  14161. else
  14162. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14163. }
  14164. else
  14165. {
  14166. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14167. }
  14168. }
  14169. }
  14170. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14171. {
  14172. // We don't allow actually assignment to "this", so we just do a single load
  14173. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14174. // we need to store it in the stack frame for debugging purposes
  14175. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14176. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14177. paramVar->mValue = loadedThis;
  14178. }
  14179. if ((wantsDIData) && (declareCall))
  14180. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14181. if (paramVar->mIsSplat)
  14182. {
  14183. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14184. }
  14185. else if (!paramVar->mResolvedType->IsValuelessType())
  14186. {
  14187. argIdx++;
  14188. }
  14189. }
  14190. if (wantsDIData)
  14191. {
  14192. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14193. }
  14194. }
  14195. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14196. {
  14197. auto paramVar = mCurMethodState->mLocals[varIdx];
  14198. // 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
  14199. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14200. // if (paramVar->mIsSplat)
  14201. // {
  14202. // if (wantsDIVariables)
  14203. // {
  14204. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14205. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14206. // }
  14207. // }
  14208. if (paramVar->mResolvedType->IsValuelessType())
  14209. {
  14210. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14211. {
  14212. // Only add this placeholder if we don't have any values
  14213. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14214. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14215. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14216. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14217. }
  14218. }
  14219. }
  14220. if (IsTargetingBeefBackend())
  14221. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14222. if (methodState.mClosureState != NULL)
  14223. {
  14224. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14225. {
  14226. BfLocalVariable* localVar = new BfLocalVariable();
  14227. *localVar = constLocal;
  14228. AddLocalVariableDef(localVar, true);
  14229. }
  14230. }
  14231. bool wantsRemoveBody = false;
  14232. bool skipBody = false;
  14233. bool skipUpdateSrcPos = false;
  14234. bool skipEndChecks = false;
  14235. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14236. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14237. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14238. hasExternSpecifier = true;
  14239. // Allocate, clear, set classVData
  14240. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14241. {
  14242. CreateStaticCtor();
  14243. }
  14244. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14245. {
  14246. skipBody = true;
  14247. skipEndChecks = true;
  14248. if (HasCompiledOutput())
  14249. {
  14250. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14251. mBfIRBuilder->ClearDebugLocation();
  14252. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14253. BfTypeInstance* innerType = boxedType->mElementType;
  14254. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14255. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14256. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14257. if (methodInstance->mIsForeignMethodDef)
  14258. {
  14259. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14260. }
  14261. BfTypeVector methodGenericArguments;
  14262. if (methodInstance->mMethodInfoEx != NULL)
  14263. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14264. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14265. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14266. {
  14267. if (!methodInstance->mReturnType->IsValuelessType())
  14268. {
  14269. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14270. CreateReturn(retVal);
  14271. }
  14272. }
  14273. else
  14274. {
  14275. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14276. SizedArray<BfIRValue, 8> innerParams;
  14277. BfExprEvaluator exprEvaluator(this);
  14278. if (!innerType->IsValuelessType())
  14279. {
  14280. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14281. BfTypedValue innerVal(thisValue, innerType, true);
  14282. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14283. }
  14284. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14285. {
  14286. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14287. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14288. exprEvaluator.PushArg(localVal, innerParams);
  14289. }
  14290. if (!innerMethodInstance.mFunc)
  14291. {
  14292. BF_ASSERT(innerType->IsUnspecializedType());
  14293. }
  14294. else if (methodInstance->HasStructRet())
  14295. {
  14296. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14297. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14298. exprEvaluator.mReceivingValue = &returnType;
  14299. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14300. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14301. mBfIRBuilder->CreateRetVoid();
  14302. }
  14303. else
  14304. {
  14305. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14306. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14307. if (mCurMethodInstance->mReturnType->IsValueType())
  14308. retVal = LoadValue(retVal);
  14309. CreateReturn(retVal.mValue);
  14310. }
  14311. }
  14312. }
  14313. mCurMethodState->SetHadReturn(true);
  14314. mCurMethodState->mLeftBlockUncond = true;
  14315. }
  14316. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14317. {
  14318. mBfIRBuilder->ClearDebugLocation();
  14319. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14320. auto thisVal = GetThis();
  14321. int prevSize = mContext->mBfObjectType->mInstSize;
  14322. int curSize = mCurTypeInstance->mInstSize;
  14323. if (curSize > prevSize)
  14324. {
  14325. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14326. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14327. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14328. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14329. }
  14330. skipUpdateSrcPos = true;
  14331. }
  14332. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14333. {
  14334. EmitCtorBody(skipBody);
  14335. }
  14336. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14337. {
  14338. EmitDtorBody();
  14339. skipBody = true;
  14340. }
  14341. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14342. {
  14343. EmitIteratorBlock(skipBody);
  14344. }
  14345. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14346. {
  14347. // We need to be able to mark deleted objects
  14348. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14349. }
  14350. auto customAttributes = methodInstance->GetCustomAttributes();
  14351. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14352. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14353. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14354. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14355. {
  14356. // We chain even non-default ctors to the default ctors
  14357. auto defaultCtor = methodInstance;
  14358. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14359. CallChainedMethods(defaultCtor, false);
  14360. }
  14361. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14362. if (methodDef->mBody == NULL)
  14363. {
  14364. if (methodDeclaration != NULL)
  14365. {
  14366. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14367. {
  14368. if (operatorDeclaration->mIsConvOperator)
  14369. wantsRemoveBody = true;
  14370. }
  14371. }
  14372. bool isDllImport = false;
  14373. if (methodDef->mImportKind == BfImportKind_Static)
  14374. {
  14375. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14376. {
  14377. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14378. {
  14379. if (customAttr.mCtorArgs.size() == 1)
  14380. {
  14381. auto fileNameArg = customAttr.mCtorArgs[0];
  14382. int strNum = 0;
  14383. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14384. if (constant != NULL)
  14385. {
  14386. if (constant->IsNull())
  14387. continue; // Invalid
  14388. strNum = constant->mInt32;
  14389. }
  14390. else
  14391. {
  14392. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14393. }
  14394. if (!mImportFileNames.Contains(strNum))
  14395. mImportFileNames.Add(strNum);
  14396. }
  14397. }
  14398. }
  14399. //mImportFileNames
  14400. }
  14401. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14402. {
  14403. CreateDllImportMethod();
  14404. }
  14405. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14406. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14407. {
  14408. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14409. {
  14410. // Emit nothing
  14411. }
  14412. else
  14413. {
  14414. CreateDelegateInvokeMethod();
  14415. mCurMethodState->SetHadReturn(true);
  14416. mCurMethodState->mLeftBlockUncond = true;
  14417. }
  14418. }
  14419. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14420. {
  14421. if (mCurTypeInstance->IsObject())
  14422. {
  14423. CreateDynamicCastMethod();
  14424. }
  14425. else
  14426. {
  14427. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14428. mCurMethodState->mHadReturn = true;
  14429. }
  14430. }
  14431. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14432. {
  14433. BfIRValue ret;
  14434. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14435. {
  14436. // This can happen if we provide an invalid name
  14437. AssertErrorState();
  14438. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14439. }
  14440. else
  14441. {
  14442. // Unfortunate DebugLoc shenanigans-
  14443. // 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,
  14444. // so we only set the loc on the CreateRet which gets inlined out
  14445. mBfIRBuilder->SaveDebugLocation();
  14446. mBfIRBuilder->ClearDebugLocation();
  14447. BfIRValue fromBool;
  14448. if (!mCurTypeInstance->IsTypedPrimitive())
  14449. {
  14450. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14451. }
  14452. else
  14453. {
  14454. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14455. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14456. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14457. }
  14458. mBfIRBuilder->RestoreDebugLocation();
  14459. ret = mBfIRBuilder->CreateRet(fromBool);
  14460. //ExtendLocalLifetimes(0);
  14461. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14462. }
  14463. mCurMethodState->SetHadReturn(true);
  14464. mCurMethodState->mLeftBlockUncond = true;
  14465. }
  14466. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14467. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14468. {
  14469. BfIRValue ret;
  14470. // Unfortunate DebugLoc shenanigans-
  14471. // 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,
  14472. // so we only set the loc on the CreateRet which gets inlined out
  14473. mBfIRBuilder->SaveDebugLocation();
  14474. mBfIRBuilder->ClearDebugLocation();
  14475. BfIRValue fromBool;
  14476. mBfIRBuilder->RestoreDebugLocation();
  14477. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14478. //ExtendLocalLifetimes(0);
  14479. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14480. mCurMethodState->SetHadReturn(true);
  14481. mCurMethodState->mLeftBlockUncond = true;
  14482. }
  14483. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14484. {
  14485. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14486. if (HasCompiledOutput())
  14487. {
  14488. EmitEnumToStringBody();
  14489. }
  14490. mBfIRBuilder->CreateRetVoid();
  14491. mCurMethodState->SetHadReturn(true);
  14492. mCurMethodState->mLeftBlockUncond = true;
  14493. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14494. }
  14495. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14496. {
  14497. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14498. if (HasCompiledOutput())
  14499. {
  14500. EmitTupleToStringBody();
  14501. }
  14502. mBfIRBuilder->CreateRetVoid();
  14503. mCurMethodState->SetHadReturn(true);
  14504. mCurMethodState->mLeftBlockUncond = true;
  14505. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14506. }
  14507. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14508. {
  14509. CreateValueTypeEqualsMethod();
  14510. skipBody = true;
  14511. skipEndChecks = true;
  14512. }
  14513. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14514. {
  14515. CreateValueTypeEqualsMethod();
  14516. skipBody = true;
  14517. skipEndChecks = true;
  14518. }
  14519. else if (HasCompiledOutput())
  14520. {
  14521. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14522. {
  14523. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14524. {
  14525. EmitGCMarkMembers();
  14526. }
  14527. else if (!mCurTypeInstance->IsObject())
  14528. {
  14529. }
  14530. }
  14531. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14532. {
  14533. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14534. {
  14535. EmitGCFindTLSMembers();
  14536. }
  14537. }
  14538. }
  14539. }
  14540. else if (!skipBody)
  14541. {
  14542. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14543. if (isEmptyBodied) // Generate autoProperty things
  14544. {
  14545. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14546. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14547. {
  14548. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14549. Fail("Body expected", methodDef->mBody);
  14550. }
  14551. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14552. {
  14553. if (methodInstance->mReturnType->IsValuelessType())
  14554. {
  14555. mBfIRBuilder->CreateRetVoid();
  14556. }
  14557. else if (HasCompiledOutput())
  14558. {
  14559. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14560. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14561. BfFieldDef* fieldDef = NULL;
  14562. if (fieldInstance != NULL)
  14563. fieldDef = fieldInstance->GetFieldDef();
  14564. BfType* retType = methodInstance->mReturnType;
  14565. if (retType->IsRef())
  14566. retType = retType->GetUnderlyingType();
  14567. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14568. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14569. {
  14570. BfTypedValue lookupValue;
  14571. if (fieldDef->IsNonConstStatic())
  14572. lookupValue = ReferenceStaticField(fieldInstance);
  14573. else if (mCurTypeInstance->IsObject())
  14574. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14575. else
  14576. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14577. if (!methodInstance->mReturnType->IsRef())
  14578. lookupValue = LoadValue(lookupValue);
  14579. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14580. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14581. }
  14582. else
  14583. {
  14584. // This can happen if we have two properties with the same name but different types
  14585. AssertErrorState();
  14586. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14587. }
  14588. }
  14589. else
  14590. {
  14591. // During autocomplete, the actual type may not have the proper field instance
  14592. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14593. }
  14594. mCurMethodState->SetHadReturn(true);
  14595. }
  14596. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14597. {
  14598. if (!mCompiler->IsAutocomplete())
  14599. {
  14600. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14601. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14602. auto fieldDef = fieldInstance->GetFieldDef();
  14603. auto& lastParam = mCurMethodState->mLocals.back();
  14604. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14605. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14606. {
  14607. BfIRValue lookupAddr;
  14608. if (fieldDef->IsNonConstStatic())
  14609. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14610. else
  14611. {
  14612. auto thisValue = GetThis();
  14613. if (thisValue.IsSplat())
  14614. {
  14615. BF_FATAL("Should not happen");
  14616. }
  14617. if (mCurTypeInstance->IsObject())
  14618. thisValue = LoadValue(thisValue);
  14619. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14620. }
  14621. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14622. }
  14623. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14624. {
  14625. // This can happen if we have two properties with the same name but different types
  14626. AssertErrorState();
  14627. }
  14628. }
  14629. }
  14630. }
  14631. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14632. {
  14633. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14634. if (mCurMethodInstance->HasStructRet())
  14635. {
  14636. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14637. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14638. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14639. mBfIRBuilder->ClearDebugLocation(storeInst);
  14640. mCurMethodState->mRetValAddr = allocaInst;
  14641. }
  14642. else
  14643. {
  14644. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14645. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14646. }
  14647. }
  14648. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14649. {
  14650. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14651. BfGetSymbolReferenceKind prevSymbolKind;
  14652. BfAutoComplete* prevAutoComplete;
  14653. if (mCompiler->mResolvePassData != NULL)
  14654. {
  14655. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14656. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14657. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14658. }
  14659. EmitCtorCalcAppend();
  14660. if (mCompiler->mResolvePassData != NULL)
  14661. {
  14662. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14663. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14664. }
  14665. }
  14666. else if (!isEmptyBodied)
  14667. {
  14668. if (!mCurMethodState->mIRExitBlock)
  14669. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14670. bool isExpressionBody = false;
  14671. if (methodDeclaration != NULL)
  14672. {
  14673. if (methodDeclaration->mFatArrowToken != NULL)
  14674. isExpressionBody = true;
  14675. }
  14676. else if (methodDef->GetPropertyDeclaration() != NULL)
  14677. {
  14678. //
  14679. }
  14680. else
  14681. {
  14682. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14683. {
  14684. if (!block->mChildArr.IsEmpty())
  14685. {
  14686. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14687. {
  14688. if (exprStmt->mTrailingSemicolon == NULL)
  14689. isExpressionBody = true;
  14690. }
  14691. }
  14692. }
  14693. else
  14694. isExpressionBody = true;
  14695. }
  14696. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14697. {
  14698. while (fieldDtorBody != NULL)
  14699. {
  14700. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14701. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14702. }
  14703. }
  14704. else if (!isExpressionBody)
  14705. {
  14706. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14707. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14708. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14709. VisitCodeBlock(bodyBlock);
  14710. }
  14711. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14712. {
  14713. if (methodDef->mMethodType != BfMethodType_Normal)
  14714. {
  14715. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14716. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14717. }
  14718. auto expectingType = mCurMethodInstance->mReturnType;
  14719. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14720. // {
  14721. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14722. // }
  14723. //TODO: Why did we have all this stuff for handling void?
  14724. // if (expectingType->IsVoid())
  14725. // {
  14726. // bool wasReturnGenericParam = false;
  14727. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14728. // {
  14729. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14730. // }
  14731. // else
  14732. // {
  14733. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14734. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14735. // wasReturnGenericParam = true;
  14736. // }
  14737. //
  14738. // // If we the void return was from a generic specialization, allow us to return a void result,
  14739. // // otherwise treat expression as though it must be a statement
  14740. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14741. // if (isStatement)
  14742. // expectingType = NULL;
  14743. // }
  14744. UpdateSrcPos(expressionBody);
  14745. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14746. if ((retVal) && (expectingType != NULL))
  14747. {
  14748. mCurMethodState->mHadReturn = true;
  14749. retVal = LoadValue(retVal);
  14750. EmitReturn(retVal.mValue);
  14751. }
  14752. }
  14753. }
  14754. }
  14755. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14756. if (skipUpdateSrcPos)
  14757. {
  14758. // Skip
  14759. }
  14760. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14761. UpdateSrcPos(bodyBlock->mCloseBrace);
  14762. else if (methodDef->mBody != NULL)
  14763. UpdateSrcPos(methodDef->mBody);
  14764. else if (methodDeclaration != NULL)
  14765. UpdateSrcPos(methodDeclaration);
  14766. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14767. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14768. else
  14769. UseDefaultSrcPos();
  14770. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14771. {
  14772. if (mCurMethodState->mRetVal)
  14773. {
  14774. mCurMethodState->SetHadReturn(true);
  14775. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14776. mBfIRBuilder->CreateRet(retVal);
  14777. }
  14778. else
  14779. AssertErrorState();
  14780. }
  14781. if (!mCurMethodState->mHadReturn)
  14782. {
  14783. // Clear off the stackallocs that have occurred after a scopeData break
  14784. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14785. }
  14786. if (mCurMethodState->mIRExitBlock)
  14787. {
  14788. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14789. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14790. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14791. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14792. if (!mCurMethodState->mDIRetVal)
  14793. CreateDIRetVal();
  14794. }
  14795. for (auto localVar : mCurMethodState->mLocals)
  14796. {
  14797. if ((skipEndChecks) || (bodyBlock == NULL))
  14798. break;
  14799. LocalVariableDone(localVar, true);
  14800. }
  14801. if (mCurMethodState->mIRExitBlock)
  14802. {
  14803. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14804. {
  14805. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14806. CreateReturn(loadedVal);
  14807. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14808. if (mCurMethodState->mDIRetVal)
  14809. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14810. }
  14811. else
  14812. {
  14813. // Have something on the last line to step onto
  14814. if (mHasFullDebugInfo)
  14815. {
  14816. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14817. UpdateSrcPos(bodyBlock->mCloseBrace);
  14818. EmitEnsureInstructionAt();
  14819. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14820. {
  14821. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14822. mBfIRBuilder->EnsureFunctionPatchable();
  14823. }
  14824. }
  14825. mBfIRBuilder->CreateRetVoid();
  14826. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14827. if (mCurMethodState->mDIRetVal)
  14828. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14829. }
  14830. }
  14831. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14832. {
  14833. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14834. {
  14835. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14836. {
  14837. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14838. mBfIRBuilder->EnsureFunctionPatchable();
  14839. }
  14840. mBfIRBuilder->CreateRetVoid();
  14841. }
  14842. }
  14843. else
  14844. {
  14845. if (!mCurMethodState->mHadReturn)
  14846. {
  14847. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14848. if (bodyBlock != NULL)
  14849. {
  14850. if (bodyBlock->mCloseBrace != NULL)
  14851. {
  14852. BfAstNode* target = bodyBlock->mCloseBrace;
  14853. Fail("Method must return value", target);
  14854. }
  14855. else
  14856. {
  14857. // It's possible to not have a closing brace if the method ends in an EOF
  14858. AssertErrorState();
  14859. }
  14860. }
  14861. }
  14862. }
  14863. // Move 'init' into 'entry'
  14864. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14865. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14866. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14867. {
  14868. // Don't keep instructions for unspecialized types
  14869. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14870. }
  14871. if ((hasExternSpecifier) && (!skipBody))
  14872. {
  14873. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14874. // incase it gets called later by some hot-loaded coded
  14875. if (mCompiler->mOptions.mAllowHotSwapping)
  14876. CreateFakeCallerMethod(mangledName);
  14877. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14878. }
  14879. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14880. {
  14881. // We only need the DLL stub when we may be hot swapping
  14882. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14883. }
  14884. else if (wantsRemoveBody)
  14885. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14886. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  14887. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  14888. // unspecialized types
  14889. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  14890. {
  14891. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  14892. methodInstance->mIRFunction = BfIRFunction();
  14893. }
  14894. CheckAddFailType();
  14895. if (mHadBuildError)
  14896. prevHadBuildError.CancelRestore();
  14897. if (mHadBuildWarning)
  14898. prevHadWarning.CancelRestore();
  14899. if (!methodDef->mIsLocalMethod)
  14900. ProcessMethod_ProcessDeferredLocals();
  14901. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  14902. if (methodState.mHotDataReferenceBuilder != NULL)
  14903. {
  14904. AddHotDataReferences(&hotDataReferenceBuilder);
  14905. }
  14906. else
  14907. {
  14908. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  14909. {
  14910. // Remove the hot method data
  14911. auto hotMethod = methodInstance->mHotMethod;
  14912. auto prevMethod = hotMethod->mPrevVersion;
  14913. if (prevMethod != NULL)
  14914. {
  14915. // If there's a prev method then pull its data into the main HotMethod.
  14916. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  14917. // over to the main HotMethod definition to keep the HotMethod address
  14918. // invariant
  14919. for (auto ref : hotMethod->mReferences)
  14920. ref->Deref();
  14921. hotMethod->mReferences.Clear();
  14922. BF_ASSERT(prevMethod->mRefCount == 1);
  14923. hotMethod->mReferences = prevMethod->mReferences;
  14924. if (hotMethod->mSrcTypeVersion != NULL)
  14925. hotMethod->mSrcTypeVersion->Deref();
  14926. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  14927. prevMethod->mSrcTypeVersion = NULL;
  14928. prevMethod->mReferences.Clear();
  14929. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  14930. prevMethod->mPrevVersion = NULL;
  14931. prevMethod->Deref();
  14932. }
  14933. hotMethod->Deref();
  14934. methodInstance->mHotMethod = NULL;
  14935. }
  14936. }
  14937. }
  14938. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  14939. {
  14940. String name;
  14941. bool found = false;
  14942. auto checkMethodState = mCurMethodState;
  14943. while (checkMethodState != NULL)
  14944. {
  14945. if (checkMethodState->mClosureState == NULL)
  14946. break;
  14947. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  14948. {
  14949. found = true;
  14950. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  14951. break;
  14952. }
  14953. checkMethodState = checkMethodState->mPrevMethodState;
  14954. }
  14955. if (!found)
  14956. name += mCurMethodInstance->mMethodDef->mName;
  14957. int prevSepPos = (int)name.LastIndexOf('$');
  14958. if (prevSepPos != -1)
  14959. {
  14960. name.RemoveToEnd(prevSepPos);
  14961. }
  14962. name += "@";
  14963. name += baseName;
  14964. HashContext hashCtx;
  14965. if (anchorNode != NULL)
  14966. {
  14967. hashCtx.Mixin(anchorNode->GetStartCharId());
  14968. }
  14969. //
  14970. {
  14971. auto checkMethodState = declMethodState;
  14972. auto checkMixinState = declMixinState;
  14973. while (checkMethodState != NULL)
  14974. {
  14975. if (checkMixinState != NULL)
  14976. {
  14977. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  14978. }
  14979. checkMethodState = checkMethodState->mPrevMethodState;
  14980. if (checkMethodState != NULL)
  14981. checkMixinState = checkMethodState->mMixinState;
  14982. }
  14983. }
  14984. auto rootMethodState = mCurMethodState->GetRootMethodState();
  14985. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  14986. {
  14987. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  14988. {
  14989. StringT<128> genericTypeName;
  14990. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  14991. hashCtx.MixinStr(genericTypeName);
  14992. }
  14993. }
  14994. uint64 hashVal = hashCtx.Finish64();
  14995. name += "$";
  14996. name += BfTypeUtils::HashEncode64(hashVal);
  14997. return name;
  14998. }
  14999. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15000. {
  15001. if (localMethod->mMethodDef != NULL)
  15002. return localMethod->mMethodDef;
  15003. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15004. auto declMethodState = localMethod->mDeclMethodState;
  15005. auto declMixinState = localMethod->mDeclMixinState;
  15006. auto typeInst = mCurTypeInstance;
  15007. BfAstNode* body = NULL;
  15008. BfAstNode* anchorNode = NULL;
  15009. auto _AllocDirectTypeRef = [&](BfType* type)
  15010. {
  15011. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15012. directTypeRef->Init(type);
  15013. return directTypeRef;
  15014. };
  15015. auto methodDeclaration = localMethod->mMethodDeclaration;
  15016. if (methodDeclaration != NULL)
  15017. {
  15018. body = methodDeclaration->mBody;
  15019. anchorNode = methodDeclaration->mOpenParen;
  15020. }
  15021. else
  15022. {
  15023. body = localMethod->mLambdaBindExpr->mBody;
  15024. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15025. }
  15026. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15027. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15028. BfMethodDef* methodDef;
  15029. if (methodDeclaration != NULL)
  15030. {
  15031. BfDefBuilder defBuilder(mCompiler->mSystem);
  15032. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15033. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15034. BfMethodDef* outerMethodDef = NULL;
  15035. if (localMethod->mOuterLocalMethod != NULL)
  15036. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15037. else
  15038. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15039. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15040. }
  15041. else
  15042. {
  15043. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15044. methodDef = new BfMethodDef();
  15045. methodDef->mName = localMethod->mMethodName;
  15046. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15047. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15048. methodDef->mBody = body;
  15049. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15050. {
  15051. auto paramType = invokeMethod->GetParamType(paramIdx);
  15052. String paramName;
  15053. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15054. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15055. else
  15056. paramName = invokeMethod->GetParamName(paramIdx);
  15057. auto paramDef = new BfParameterDef();
  15058. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15059. paramDef->mName = paramName;
  15060. methodDef->mParams.Add(paramDef);
  15061. }
  15062. }
  15063. methodDef->mIdx = ~methodLocalIdx;
  15064. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15065. methodDef->mName = localMethod->mExpectedFullName;
  15066. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15067. //
  15068. // if (!localMethod->mExpectedFullName.IsEmpty())
  15069. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15070. methodDef->mIsStatic = true;
  15071. methodDef->mIsLocalMethod = true;
  15072. methodDef->mIsVirtual = false;
  15073. localMethod->mMethodDef = methodDef;
  15074. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15075. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15076. methodInstanceGroup->mMethodIdx = -1;
  15077. methodInstanceGroup->mOwner = mCurTypeInstance;
  15078. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15079. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15080. {
  15081. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15082. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15083. }
  15084. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15085. {
  15086. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15087. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15088. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15089. {
  15090. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15091. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15092. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15093. autoComplete->mDefType = typeInst->mTypeDef;
  15094. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15095. autoComplete->mReplaceLocalId = methodLocalIdx;
  15096. }
  15097. }
  15098. return localMethod->mMethodDef;
  15099. }
  15100. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15101. {
  15102. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15103. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15104. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15105. auto declMethodState = localMethod->mDeclMethodState;
  15106. auto declMixinState = localMethod->mDeclMixinState;
  15107. auto callerMethodState = mCurMethodState;
  15108. auto typeInst = mCurTypeInstance;
  15109. auto methodDef = GetLocalMethodDef(localMethod);
  15110. BfAstNode* body = NULL;
  15111. auto methodDeclaration = localMethod->mMethodDeclaration;
  15112. if (methodDeclaration != NULL)
  15113. {
  15114. body = methodDeclaration->mBody;
  15115. }
  15116. else
  15117. {
  15118. body = localMethod->mLambdaBindExpr->mBody;
  15119. }
  15120. bool hadConcreteInterfaceGenericArgument = false;
  15121. BfTypeVector sanitizedMethodGenericArguments;
  15122. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15123. // version of this method for this pass through the outermost method
  15124. int dependentGenericStartIdx = 0;
  15125. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15126. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15127. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15128. if (methodGenericArguments.size() == 0)
  15129. {
  15130. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15131. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15132. }
  15133. else
  15134. {
  15135. int genericArgIdx = 0;
  15136. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15137. // {
  15138. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15139. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15140. // }
  15141. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15142. {
  15143. auto genericArgType = methodGenericArguments[genericArgIdx];
  15144. BF_ASSERT(!genericArgType->IsRef());
  15145. if (genericArgType->IsConcreteInterfaceType())
  15146. {
  15147. hadConcreteInterfaceGenericArgument = true;
  15148. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15149. genericArgType = concreteInterfaceType->mInterface;
  15150. }
  15151. sanitizedMethodGenericArguments.push_back(genericArgType);
  15152. }
  15153. }
  15154. bool wantPrematureMethodInstance = false;
  15155. if (!force)
  15156. {
  15157. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15158. }
  15159. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15160. bool isDefaultPass = true;
  15161. BfTypeVector lookupMethodGenericArguments;
  15162. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15163. {
  15164. auto genericArgType = methodGenericArguments[genericArgIdx];
  15165. BF_ASSERT(!genericArgType->IsRef());
  15166. lookupMethodGenericArguments.Add(genericArgType);
  15167. if (genericArgType->IsGenericParam())
  15168. {
  15169. auto genericParam = (BfGenericParamType*)genericArgType;
  15170. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15171. isDefaultPass = false;
  15172. }
  15173. else
  15174. {
  15175. isDefaultPass = false;
  15176. }
  15177. }
  15178. bool hadExistingMethodInstance = false;
  15179. if (methodInstance != NULL)
  15180. {
  15181. hadExistingMethodInstance = true;
  15182. }
  15183. else
  15184. {
  15185. if (isDefaultPass)
  15186. {
  15187. methodInstance = methodInstGroup->mDefault;
  15188. if (methodInstance != NULL)
  15189. {
  15190. hadExistingMethodInstance = true;
  15191. }
  15192. else
  15193. {
  15194. methodInstance = new BfMethodInstance();
  15195. methodInstGroup->mDefault = methodInstance;
  15196. }
  15197. }
  15198. else
  15199. {
  15200. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15201. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15202. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15203. BfMethodInstance** methodInstancePtr = NULL;
  15204. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15205. {
  15206. methodInstance = *methodInstancePtr;
  15207. hadExistingMethodInstance = true;
  15208. }
  15209. else
  15210. {
  15211. methodInstance = new BfMethodInstance();
  15212. *methodInstancePtr = methodInstance;
  15213. }
  15214. }
  15215. }
  15216. if (hadExistingMethodInstance)
  15217. {
  15218. if ((!methodInstance->mDisallowCalling) ||
  15219. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15220. return BfModuleMethodInstance(methodInstance);
  15221. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15222. }
  15223. else
  15224. {
  15225. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15226. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15227. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15228. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15229. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15230. methodInstance->mMethodDef = methodDef;
  15231. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15232. if (hadConcreteInterfaceGenericArgument)
  15233. methodInstance->mIgnoreBody = true;
  15234. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15235. for (auto genericArg : sanitizedMethodGenericArguments)
  15236. {
  15237. if (genericArg->IsPrimitiveType())
  15238. genericArg = GetWrappedStructType(genericArg);
  15239. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15240. }
  15241. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15242. {
  15243. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15244. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15245. }
  15246. SetupMethodIdHash(methodInstance);
  15247. }
  15248. auto _SetupMethodInstance = [&]()
  15249. {
  15250. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15251. // Generic constraints
  15252. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15253. {
  15254. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15255. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15256. }
  15257. };
  15258. //////////////////////////////////////////////////////////////////////////
  15259. auto _VisitLambdaBody = [&]()
  15260. {
  15261. if (localMethod->mDeclOnly)
  15262. return;
  15263. if (mCompiler->mCanceling)
  15264. return;
  15265. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15266. {
  15267. VisitCodeBlock(blockBody);
  15268. }
  15269. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15270. CreateValueFromExpression(bodyExpr);
  15271. };
  15272. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15273. {
  15274. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15275. auto result = ResolveTypeRef(typeRef);
  15276. if (result == NULL)
  15277. result = mContext->mBfObjectType;
  15278. return result;
  15279. };
  15280. BfTypeInstance* outerClosure = NULL;
  15281. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15282. outerClosure = declMethodState->mClosureState->mClosureType;
  15283. BfMethodState methodState;
  15284. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15285. BfIRFunctionType funcType;
  15286. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15287. SizedArray<BfIRType, 0> paramTypes;
  15288. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15289. mBfIRBuilder->SaveDebugLocation();
  15290. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15291. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15292. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15293. BfDeferredLocalAssignData deferredLocalAssignData;
  15294. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15295. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15296. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15297. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15298. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15299. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15300. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15301. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15302. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15303. methodState.mIRFunction = declMethodState->mIRFunction;
  15304. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15305. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15306. BfClosureState closureState;
  15307. if (methodDef->mMethodType == BfMethodType_Mixin)
  15308. {
  15309. if (declMethodState != NULL)
  15310. {
  15311. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15312. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15313. else if (declMethodState->mMethodInstance != NULL)
  15314. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15315. }
  15316. }
  15317. if (closureState.mReturnType == NULL)
  15318. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15319. closureState.mCapturing = true;
  15320. closureState.mLocalMethod = localMethod;
  15321. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15322. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15323. methodState.mClosureState = &closureState;
  15324. closureState.mClosureType = outerClosure;
  15325. int outerLocalsCount = (int)methodState.mLocals.size();
  15326. if (!hadExistingMethodInstance)
  15327. {
  15328. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15329. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15330. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15331. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15332. auto declareModule = this;
  15333. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15334. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15335. BF_ASSERT(declareModule != NULL);
  15336. methodInstance->mDeclModule = declareModule;
  15337. _SetupMethodInstance();
  15338. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15339. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15340. }
  15341. if (wantPrematureMethodInstance)
  15342. {
  15343. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15344. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15345. // its true method instance
  15346. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15347. //BF_ASSERT(moduleMethodInstance);
  15348. return BfModuleMethodInstance(methodInstance);
  15349. }
  15350. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15351. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15352. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15353. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15354. closureState.mClosureMethodDef = methodDef;
  15355. bool wantsVisitBody = true;
  15356. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15357. wantsVisitBody = false;
  15358. if (methodInstance->mIsUnspecializedVariation)
  15359. wantsVisitBody = false;
  15360. if (wantsVisitBody)
  15361. {
  15362. BP_ZONE("VisitLambdaBody");
  15363. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15364. // this capture stage for each of those times
  15365. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15366. /*
  15367. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15368. // that will not occur during the actual lambda method generation, for example: returning a value
  15369. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15370. // our AST nodes will still be visited
  15371. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15372. */
  15373. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15374. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15375. mBfIRBuilder->SaveDebugLocation();
  15376. closureState.mCaptureVisitingBody = true;
  15377. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15378. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15379. NewScopeState();
  15380. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15381. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15382. {
  15383. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15384. for (auto localDef : methodState.mLocals)
  15385. {
  15386. if (localDef->mResolvedType->IsVar())
  15387. continue;
  15388. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15389. }
  15390. }
  15391. _VisitLambdaBody();
  15392. RestoreScopeState();
  15393. //ProcessMethod(methodInstance);
  15394. closureState.mCaptureVisitingBody = false;
  15395. mBfIRBuilder->RestoreDebugLocation();
  15396. }
  15397. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15398. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15399. {
  15400. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15401. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15402. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15403. }
  15404. //RestoreScopeState();
  15405. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15406. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15407. closureState.mClosureMethodDef = NULL;
  15408. for (auto methodInstance : closureState.mLocalMethodRefs)
  15409. {
  15410. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15411. }
  15412. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15413. prevIgnoreWrites.Restore();
  15414. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15415. //
  15416. {
  15417. auto varMethodState = declMethodState;
  15418. while (varMethodState != NULL)
  15419. {
  15420. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15421. {
  15422. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15423. methodDef->mIsStatic = false;
  15424. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15425. methodDef->mIsMutating = true;
  15426. }
  15427. bool copyOuterCaptures = false;
  15428. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15429. {
  15430. auto localVar = varMethodState->mLocals[localIdx];
  15431. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15432. {
  15433. if (localVar->mIsThis)
  15434. {
  15435. // We can only set mutating if our owning type is mutating
  15436. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15437. {
  15438. if (mCurTypeInstance->IsValueType())
  15439. {
  15440. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15441. methodDef->mIsMutating = true;
  15442. }
  15443. }
  15444. methodDef->mIsStatic = false;
  15445. continue;
  15446. }
  15447. if ((localVar->mIsThis) && (outerClosure != NULL))
  15448. {
  15449. continue;
  15450. }
  15451. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15452. {
  15453. closureState.mConstLocals.push_back(*localVar);
  15454. continue;
  15455. }
  15456. BfClosureCapturedEntry capturedEntry;
  15457. auto capturedType = localVar->mResolvedType;
  15458. bool captureByRef = false;
  15459. if (!capturedType->IsRef())
  15460. {
  15461. if (localVar->mIsThis)
  15462. {
  15463. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15464. captureByRef = true;
  15465. }
  15466. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15467. captureByRef = true;
  15468. }
  15469. else
  15470. {
  15471. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15472. {
  15473. capturedType = ((BfRefType*)capturedType)->mElementType;
  15474. }
  15475. }
  15476. if (captureByRef)
  15477. {
  15478. //capturedEntry.mIsByReference = true;
  15479. capturedType = CreateRefType(capturedType);
  15480. }
  15481. else
  15482. {
  15483. //capturedEntry.mIsByReference = false;
  15484. }
  15485. capturedEntry.mNameNode = localVar->mNameNode;
  15486. capturedEntry.mType = capturedType;
  15487. capturedEntry.mName = localVar->mName;
  15488. //capturedEntry.mLocalVarDef = localVar;
  15489. capturedEntries.insert(capturedEntry);
  15490. }
  15491. }
  15492. varMethodState = varMethodState->mPrevMethodState;
  15493. if ((varMethodState == NULL) ||
  15494. (varMethodState->mMixinState != NULL) ||
  15495. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15496. break;
  15497. }
  15498. }
  15499. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15500. {
  15501. auto fieldDef = copyField->GetFieldDef();
  15502. BfClosureCapturedEntry capturedEntry;
  15503. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15504. capturedEntry.mType = copyField->mResolvedType;
  15505. if (capturedEntry.mType->IsRef())
  15506. {
  15507. // Keep by ref
  15508. }
  15509. else if (!fieldDef->mIsReadOnly)
  15510. {
  15511. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15512. }
  15513. capturedEntries.insert(capturedEntry);
  15514. }
  15515. int captureIdx = 0;
  15516. for (auto& capturedEntry : capturedEntries)
  15517. {
  15518. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15519. }
  15520. /*if (isDefaultPass)
  15521. {
  15522. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15523. int captureIdx = 0;
  15524. for (auto& capturedEntry : capturedEntries)
  15525. {
  15526. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15527. BfParameterDef* paramDef = new BfParameterDef();
  15528. paramDef->mName = capturedEntry.mName;
  15529. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15530. directTypeRef->mType = capturedEntry.mType;
  15531. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15532. paramDef->mTypeRef = directTypeRef;
  15533. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15534. methodDef->mParams.Insert(captureIdx, paramDef);
  15535. captureIdx++;
  15536. }
  15537. }
  15538. else
  15539. {
  15540. auto defaultMethodInstance = methodInstGroup->mDefault;
  15541. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15542. }*/
  15543. methodState.Reset();
  15544. closureState.mCapturing = false;
  15545. //////////////////////////////////////////////////////////////////////////
  15546. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15547. if (methodInstance->mReturnType != NULL)
  15548. {
  15549. BF_ASSERT(methodInstance->mDisallowCalling);
  15550. // We did a premature declaration (without captures)
  15551. methodInstance->UndoDeclaration();
  15552. methodInstance->mDisallowCalling = false;
  15553. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15554. }
  15555. auto declareModule = this;
  15556. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15557. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15558. BF_ASSERT(declareModule != NULL);
  15559. methodInstance->mDeclModule = declareModule;
  15560. _SetupMethodInstance();
  15561. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15562. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15563. closureState.mReturnType = methodInstance->mReturnType;
  15564. mCompiler->mStats.mMethodsQueued++;
  15565. mCompiler->UpdateCompletion();
  15566. declareModule->mIncompleteMethodCount++;
  15567. mCompiler->mStats.mMethodsProcessed++;
  15568. if (!methodInstance->mIsReified)
  15569. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15570. auto deferMethodState = rootMethodState;
  15571. // 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)
  15572. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15573. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15574. {
  15575. BP_ZONE("BfDeferredLocalMethod:create");
  15576. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15577. deferredLocalMethod->mLocalMethod = localMethod;
  15578. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15579. deferredLocalMethod->mMethodInstance = methodInstance;
  15580. auto checkMethodState = declMethodState;
  15581. while (checkMethodState != NULL)
  15582. {
  15583. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15584. {
  15585. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15586. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15587. }
  15588. if (checkMethodState->mMixinState != NULL)
  15589. {
  15590. BfMixinRecord mixinRecord;
  15591. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15592. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15593. }
  15594. checkMethodState = checkMethodState->mPrevMethodState;
  15595. }
  15596. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15597. }
  15598. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15599. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15600. mBfIRBuilder->RestoreDebugLocation();
  15601. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15602. {
  15603. auto checkMethodState = mCurMethodState;
  15604. while (checkMethodState != NULL)
  15605. {
  15606. BfLocalMethod* nextLocalMethod = NULL;
  15607. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15608. {
  15609. while (nextLocalMethod != NULL)
  15610. {
  15611. auto checkLocalMethod = nextLocalMethod;
  15612. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15613. if (checkLocalMethod == localMethod)
  15614. continue;
  15615. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15616. continue;
  15617. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15618. if (checkMethodInstance == NULL)
  15619. continue; // Not generated yet
  15620. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15621. {
  15622. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15623. if (bfError != NULL)
  15624. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15625. }
  15626. }
  15627. }
  15628. checkMethodState = checkMethodState->mPrevMethodState;
  15629. }
  15630. }
  15631. return BfModuleMethodInstance(methodInstance);
  15632. }
  15633. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15634. {
  15635. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15636. return 0;
  15637. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15638. int rootMethodGenericParamCount = 0;
  15639. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15640. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15641. if (mCurMethodInstance == NULL)
  15642. return rootMethodGenericParamCount;
  15643. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15644. return rootMethodGenericParamCount;
  15645. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15646. if (callerLocalMethod == NULL)
  15647. return rootMethodGenericParamCount;
  15648. BfLocalMethod* calledLocalMethod = NULL;
  15649. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15650. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15651. {
  15652. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15653. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15654. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15655. }
  15656. return rootMethodGenericParamCount;
  15657. }
  15658. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15659. {
  15660. auto methodDef = methodInstance->mMethodDef;
  15661. if (methodInstance->GetCustomAttributes() != NULL)
  15662. return;
  15663. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15664. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15665. auto typeInstance = methodInstance->GetOwner();
  15666. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15667. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15668. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15669. {
  15670. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15671. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15672. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15673. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15674. }
  15675. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15676. {
  15677. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15678. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15679. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15680. }
  15681. }
  15682. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15683. {
  15684. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15685. {
  15686. // Don't create a func
  15687. return;
  15688. }
  15689. auto typeInstance = methodInstance->GetOwner();
  15690. auto methodDef = methodInstance->mMethodDef;
  15691. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15692. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15693. if (mCompiler->mResolvePassData == NULL)
  15694. {
  15695. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15696. {
  15697. typeInstance->mHasStaticInitMethod = true;
  15698. }
  15699. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15700. {
  15701. typeInstance->mHasStaticDtorMethod = true;
  15702. }
  15703. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15704. {
  15705. typeInstance->mHasStaticMarkMethod = true;
  15706. }
  15707. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15708. {
  15709. typeInstance->mHasTLSFindMethod = true;
  15710. }
  15711. }
  15712. if (isTemporaryFunc)
  15713. {
  15714. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15715. mangledName = "autocomplete_tmp";
  15716. }
  15717. if (!mBfIRBuilder->mIgnoreWrites)
  15718. {
  15719. BfIRFunction prevFunc;
  15720. // Remove old version (if we have one)
  15721. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15722. if (prevFunc)
  15723. {
  15724. if (methodDef->mIsExtern)
  15725. {
  15726. // Allow this
  15727. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15728. }
  15729. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15730. {
  15731. // We can have a collision of names when we have generic methods that differ only in
  15732. // their constraints, but they should only collide in their unspecialized form
  15733. // since only one will be chosen for a given concrete type
  15734. mCurMethodInstance->mMangleWithIdx = true;
  15735. mangledName.Clear();
  15736. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15737. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15738. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15739. }
  15740. else
  15741. {
  15742. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15743. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15744. }
  15745. }
  15746. }
  15747. if (typeInstance != mContext->mBfObjectType)
  15748. {
  15749. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15750. GetMethodCustomAttributes(methodInstance);
  15751. }
  15752. // if (prevFunc)
  15753. // {
  15754. // if (methodDef->mIsExtern)
  15755. // {
  15756. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15757. // methodInstance->mIRFunction = prevFunc;
  15758. // }
  15759. // else
  15760. // {
  15761. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15762. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15763. // {
  15764. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15765. // BfLogSysM("Ignoring function name collision\n");
  15766. // }
  15767. // else
  15768. // {
  15769. // if (methodDef->mMethodDeclaration == NULL)
  15770. // {
  15771. // AssertErrorState();
  15772. // }
  15773. // else
  15774. // {
  15775. // BF_ASSERT(mIsSpecialModule);
  15776. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15777. // {
  15778. // // We shouldn't have name collisions on the first run!
  15779. // AssertErrorState();
  15780. // }
  15781. // }
  15782. // }
  15783. // BfLogSysM("Before erase\n");
  15784. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15785. // }
  15786. // }
  15787. bool isIntrinsic = false;
  15788. if (!methodInstance->mIRFunction)
  15789. {
  15790. BfIRFunction func;
  15791. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15792. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15793. {
  15794. if (!mIsReified)
  15795. wantsLLVMFunc = false;
  15796. }*/
  15797. if (wantsLLVMFunc)
  15798. {
  15799. func = GetIntrinsic(methodInstance, true);
  15800. if (func)
  15801. {
  15802. isIntrinsic = true;
  15803. }
  15804. else
  15805. {
  15806. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15807. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15808. if (methodInstance->mAlwaysInline)
  15809. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15810. // if (prevFunc)
  15811. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15812. }
  15813. methodInstance->mIRFunction = func;
  15814. //if (!ignoreWrites)
  15815. //BF_ASSERT(!func.IsFake());
  15816. }
  15817. }
  15818. if (outIsIntrinsic != NULL)
  15819. *outIsIntrinsic = isIntrinsic;
  15820. if (!isIntrinsic)
  15821. SetupLLVMMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15822. }
  15823. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15824. {
  15825. if (methodInstance->mHotMethod != NULL)
  15826. return;
  15827. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15828. {
  15829. auto srcTypeInst = methodInstance->GetOwner();
  15830. StringT<128> mangledName = inMangledName;
  15831. if (mangledName.IsEmpty())
  15832. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15833. // We always keep the current primary method at the same address
  15834. BfHotMethod* hotMethod;
  15835. BfHotMethod** hotMethodPtr;
  15836. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15837. {
  15838. hotMethod = new BfHotMethod();
  15839. *hotMethodPtr = hotMethod;
  15840. hotMethod->mRefCount = 1;
  15841. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15842. #ifdef BF_DBG_HOTMETHOD_IDX
  15843. static int sMethodIdx = 0;
  15844. hotMethod->mMethodIdx = sMethodIdx++;
  15845. #endif
  15846. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15847. }
  15848. else
  15849. {
  15850. hotMethod = *hotMethodPtr;
  15851. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15852. {
  15853. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15854. auto prevHotMethod = *hotMethodPtr;
  15855. hotMethod = new BfHotMethod();
  15856. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15857. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15858. hotDupMethod->mRefCount++;
  15859. prevHotMethod->mReferences.Add(hotDupMethod);
  15860. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15861. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15862. }
  15863. else if (mCompiler->IsHotCompile())
  15864. {
  15865. // Link the previous version into the mPrevVersion
  15866. BfHotMethod* prevMethod = new BfHotMethod();
  15867. prevMethod->mRefCount = 1;
  15868. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15869. hotMethod->mPrevVersion = prevMethod;
  15870. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15871. hotMethod->mSrcTypeVersion = NULL;
  15872. prevMethod->mFlags = hotMethod->mFlags;
  15873. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15874. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15875. #ifdef BF_DBG_HOTMETHOD_NAME
  15876. prevMethod->mMangledName = hotMethod->mMangledName;
  15877. #endif
  15878. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15879. }
  15880. else
  15881. {
  15882. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15883. hotMethod->Clear(true);
  15884. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15885. }
  15886. }
  15887. if (methodInstance->mIsClosure)
  15888. {
  15889. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  15890. }
  15891. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  15892. hotMethod->mSrcTypeVersion->mRefCount++;
  15893. hotMethod->mRefCount++;
  15894. #ifdef BF_DBG_HOTMETHOD_NAME
  15895. hotMethod->mMangledName = mangledName;
  15896. #endif
  15897. methodInstance->mHotMethod = hotMethod;
  15898. }
  15899. }
  15900. // methodDeclaration is NULL for default constructors
  15901. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  15902. {
  15903. BP_ZONE("BfModule::BfMethodDeclaration");
  15904. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  15905. // to effectively make mIgnoreWrites method-scoped
  15906. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  15907. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  15908. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  15909. if (mCompiler->IsAutocomplete())
  15910. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  15911. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  15912. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  15913. if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15914. {
  15915. NOP;
  15916. }
  15917. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  15918. if (mAwaitingInitFinish)
  15919. FinishInit();
  15920. auto typeInstance = mCurTypeInstance;
  15921. auto typeDef = typeInstance->mTypeDef;
  15922. auto methodDef = mCurMethodInstance->mMethodDef;
  15923. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  15924. if (typeInstance->IsClosure())
  15925. {
  15926. if (methodDef->mName == "Invoke")
  15927. return;
  15928. }
  15929. auto methodInstance = mCurMethodInstance;
  15930. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  15931. addToWorkList = false;
  15932. bool hasNonGenericParams = false;
  15933. bool hasGenericParams = false;
  15934. int dependentGenericStartIdx = 0;
  15935. if (methodDef->mIsLocalMethod)
  15936. {
  15937. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  15938. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  15939. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  15940. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  15941. // over the local method each time
  15942. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  15943. dependentGenericStartIdx = 0;
  15944. if (rootMethodInstance->mMethodInfoEx != NULL)
  15945. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15946. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  15947. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  15948. }
  15949. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  15950. {
  15951. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  15952. if (genericArgType->IsGenericParam())
  15953. {
  15954. hasGenericParams = true;
  15955. auto genericParam = (BfGenericParamType*)genericArgType;
  15956. methodInstance->mIsUnspecialized = true;
  15957. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15958. methodInstance->mIsUnspecializedVariation = true;
  15959. }
  15960. else
  15961. {
  15962. hasNonGenericParams = true;
  15963. if (genericArgType->IsUnspecializedType())
  15964. {
  15965. methodInstance->mIsUnspecialized = true;
  15966. methodInstance->mIsUnspecializedVariation = true;
  15967. }
  15968. }
  15969. }
  15970. if ((hasGenericParams) && (hasNonGenericParams))
  15971. {
  15972. methodInstance->mIsUnspecializedVariation = true;
  15973. }
  15974. if (typeInstance->IsUnspecializedType())
  15975. {
  15976. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  15977. // actually want to do method processing on it
  15978. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  15979. methodInstance->mIsUnspecializedVariation = true;
  15980. methodInstance->mIsUnspecialized = true;
  15981. }
  15982. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  15983. for (auto genericParamDef : methodDef->mGenericParams)
  15984. {
  15985. if (mCompiler->IsAutocomplete())
  15986. {
  15987. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15988. //autoComplete->CheckTypeRef()
  15989. }
  15990. }
  15991. if (methodInstance->mIsUnspecializedVariation)
  15992. {
  15993. }
  15994. if (methodInstance->mIsUnspecializedVariation)
  15995. BF_ASSERT(methodInstance->mIsUnspecialized);
  15996. if (methodDef->mMethodType == BfMethodType_Mixin)
  15997. methodInstance->mIsUnspecialized = true;
  15998. BfAutoComplete* bfAutocomplete = NULL;
  15999. if (mCompiler->mResolvePassData != NULL)
  16000. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16001. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16002. {
  16003. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16004. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16005. if (bfAutocomplete != NULL)
  16006. {
  16007. for (auto nameNode : genericParamDef->mNameNodes)
  16008. {
  16009. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16010. }
  16011. }
  16012. }
  16013. if (methodInstance->mMethodInfoEx != NULL)
  16014. {
  16015. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16016. {
  16017. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16018. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16019. if (genericParam->mTypeConstraint != NULL)
  16020. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16021. }
  16022. }
  16023. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16024. {
  16025. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16026. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16027. if (nameNode == NULL)
  16028. {
  16029. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16030. nameNode = ctorDeclaration->mThisToken;
  16031. }
  16032. if (autoComplete->IsAutocompleteNode(nameNode))
  16033. {
  16034. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16035. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16036. autoComplete->mDefType = typeDef;
  16037. autoComplete->mDefMethod = methodDef;
  16038. autoComplete->SetDefinitionLocation(nameNode);
  16039. if (methodDef->mIsOverride)
  16040. {
  16041. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16042. {
  16043. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16044. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16045. continue;
  16046. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16047. if (virtMethod != NULL)
  16048. {
  16049. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16050. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16051. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16052. {
  16053. // Is matching method
  16054. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16055. {
  16056. auto baseType = typeInstance->mBaseType;
  16057. if (baseType != NULL)
  16058. {
  16059. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16060. baseType = baseType->mBaseType;
  16061. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16062. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16063. autoComplete->mDefType = baseType->mTypeDef;
  16064. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16065. }
  16066. }
  16067. break;
  16068. }
  16069. }
  16070. }
  16071. }
  16072. }
  16073. }
  16074. bool reportErrors = true;
  16075. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16076. reportErrors = true;
  16077. // Only the defining contexts needs to report errors here
  16078. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16079. if (methodDef->mMethodType == BfMethodType_Dtor)
  16080. {
  16081. if (methodDef->mIsStatic)
  16082. {
  16083. }
  16084. else
  16085. {
  16086. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16087. {
  16088. BfAstNode* refNode = methodDeclaration;
  16089. if (refNode == NULL)
  16090. {
  16091. // Whatever caused this ctor to be generated should have caused another failure
  16092. // But that failure might not be generated until the ctor is generated
  16093. }
  16094. else
  16095. {
  16096. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16097. if (dtorDecl != NULL)
  16098. refNode = dtorDecl->mThisToken;
  16099. Fail("Structs cannot have destructors", refNode);
  16100. }
  16101. }
  16102. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16103. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16104. (mCurTypeInstance != mContext->mBfObjectType))
  16105. {
  16106. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16107. }
  16108. }
  16109. }
  16110. BfType* resolvedReturnType = NULL;
  16111. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16112. (methodDef->mReturnTypeRef != NULL))
  16113. {
  16114. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16115. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16116. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16117. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16118. {
  16119. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16120. resolvedReturnType = mContext->mBfObjectType;
  16121. }
  16122. if (resolvedReturnType == NULL)
  16123. resolvedReturnType = mContext->mBfObjectType; // Fake an object
  16124. }
  16125. else
  16126. {
  16127. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16128. }
  16129. BF_ASSERT(resolvedReturnType != NULL);
  16130. mCurMethodInstance->mReturnType = resolvedReturnType;
  16131. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16132. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16133. //if (!methodInstance->IsSpecializedGenericMethod())
  16134. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16135. if (methodDef->mExplicitInterface != NULL)
  16136. {
  16137. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16138. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16139. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16140. if (explicitInterface != NULL)
  16141. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16142. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16143. {
  16144. bool interfaceFound = false;
  16145. for (auto ifaceInst : typeInstance->mInterfaces)
  16146. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16147. if (!interfaceFound)
  16148. {
  16149. if (methodDef->mMethodDeclaration != NULL)
  16150. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16151. else
  16152. {
  16153. // For property decls, we should have already given the error during type population
  16154. if (mCompiler->mRevision == 1)
  16155. AssertErrorState();
  16156. }
  16157. }
  16158. }
  16159. }
  16160. bool isThisStruct = mCurTypeInstance->IsStruct();
  16161. BfType* thisType = NULL;
  16162. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16163. {
  16164. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16165. {
  16166. thisType = mCurTypeInstance;
  16167. if (thisType == NULL)
  16168. return;
  16169. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16170. {
  16171. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16172. {
  16173. PopulateType(checkType, BfPopulateType_Data);
  16174. }, thisType);
  16175. }
  16176. }
  16177. else
  16178. {
  16179. thisType = mCurTypeInstance;
  16180. PopulateType(thisType, BfPopulateType_Declaration);
  16181. }
  16182. }
  16183. int implicitParamCount = 0;
  16184. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16185. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16186. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16187. bool hadDelegateParams = false;
  16188. bool hadParams = false;
  16189. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16190. {
  16191. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16192. BfParameterDef* paramDef = NULL;
  16193. int paramDefIdx = -1;
  16194. if (paramIdx < implicitParamCount)
  16195. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16196. else
  16197. {
  16198. paramDefIdx = paramIdx - implicitParamCount;
  16199. paramDef = methodDef->mParams[paramDefIdx];
  16200. }
  16201. if (hadParams)
  16202. break;
  16203. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16204. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16205. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16206. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16207. {
  16208. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16209. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16210. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16211. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16212. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16213. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16214. }
  16215. BfType* resolvedParamType = NULL;
  16216. if (closureCaptureEntry != NULL)
  16217. resolvedParamType = closureCaptureEntry->mType;
  16218. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16219. {
  16220. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16221. resolvedParamType = mContext->mBfObjectType;
  16222. }
  16223. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16224. {
  16225. if (methodDef->mMethodType != BfMethodType_Mixin)
  16226. {
  16227. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16228. resolvedParamType = mContext->mBfObjectType;
  16229. }
  16230. else
  16231. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16232. }
  16233. BfType* unresolvedParamType = resolvedParamType;
  16234. bool wasGenericParam = false;
  16235. if (resolvedParamType == NULL)
  16236. {
  16237. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16238. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16239. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16240. }
  16241. if (resolvedParamType == NULL)
  16242. {
  16243. resolvedParamType = mContext->mBfObjectType; // Fake an object
  16244. unresolvedParamType = resolvedParamType;
  16245. if (mCurTypeInstance->IsBoxed())
  16246. {
  16247. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16248. // If we failed a lookup here then we better have also failed it in the original type
  16249. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16250. }
  16251. }
  16252. if (!methodInstance->IsSpecializedGenericMethod())
  16253. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16254. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16255. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16256. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16257. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16258. {
  16259. BfMethodState methodState;
  16260. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16261. methodState.mTempKind = BfMethodState::TempKind_Static;
  16262. BfTypedValue defaultValue;
  16263. if (resolvedParamType->IsConstExprValue())
  16264. {
  16265. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16266. BfExprEvaluator exprEvaluator(this);
  16267. exprEvaluator.mExpectingType = constExprType->mType;
  16268. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16269. defaultValue = exprEvaluator.GetResult();
  16270. }
  16271. else
  16272. {
  16273. BfConstResolver constResolver(this);
  16274. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16275. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16276. {
  16277. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16278. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16279. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16280. {
  16281. defaultValue = castedDefaultValue; // Good!
  16282. }
  16283. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16284. {
  16285. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16286. // a conversion operator.
  16287. // This should throw an error
  16288. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16289. AssertErrorState();
  16290. if (!defaultValue.mValue.IsConst())
  16291. defaultValue = BfTypedValue();
  16292. }
  16293. }
  16294. }
  16295. if (!defaultValue)
  16296. {
  16297. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16298. if (!defaultValue.mValue.IsConst())
  16299. defaultValue = BfTypedValue();
  16300. }
  16301. if (defaultValue)
  16302. {
  16303. BF_ASSERT(defaultValue.mValue.IsConst());
  16304. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16305. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16306. CurrentAddToConstHolder(defaultValue.mValue);
  16307. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16308. }
  16309. }
  16310. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16311. {
  16312. bool addParams = true;
  16313. bool isValid = false;
  16314. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16315. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16316. {
  16317. // Span<T>
  16318. isValid = true;
  16319. }
  16320. else if (resolvedParamType->IsArray())
  16321. {
  16322. // Array is the 'normal' params type
  16323. isValid = true;
  16324. }
  16325. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16326. {
  16327. hadDelegateParams = true;
  16328. // This means we copy the params from a delegate
  16329. BfMethodParam methodParam;
  16330. methodParam.mResolvedType = resolvedParamType;
  16331. methodParam.mParamDefIdx = paramDefIdx;
  16332. methodParam.mDelegateParamIdx = 0;
  16333. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16334. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16335. {
  16336. methodParam.mDelegateParamIdx = delegateParamIdx;
  16337. mCurMethodInstance->mParams.Add(methodParam);
  16338. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16339. if (!methodInstance->IsSpecializedGenericMethod())
  16340. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16341. }
  16342. isValid = true;
  16343. addParams = false;
  16344. }
  16345. else if (resolvedParamType->IsGenericParam())
  16346. {
  16347. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16348. if (genericParamInstance->mTypeConstraint != NULL)
  16349. {
  16350. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16351. if (genericParamInstance->mTypeConstraint->IsArray())
  16352. {
  16353. BfMethodParam methodParam;
  16354. methodParam.mResolvedType = resolvedParamType;
  16355. methodParam.mParamDefIdx = paramDefIdx;
  16356. mCurMethodInstance->mParams.Add(methodParam);
  16357. isValid = true;
  16358. }
  16359. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16360. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16361. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16362. {
  16363. mCurMethodInstance->mHadGenericDelegateParams = true;
  16364. isValid = true;
  16365. addParams = false;
  16366. }
  16367. }
  16368. }
  16369. else
  16370. {
  16371. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16372. if ((paramTypeInst != NULL) &&
  16373. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16374. {
  16375. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16376. isValid = true;
  16377. addParams = false;
  16378. }
  16379. }
  16380. if (!isValid)
  16381. {
  16382. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16383. // Failure case, make it an Object[]
  16384. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16385. }
  16386. if (addParams)
  16387. {
  16388. BfMethodParam methodParam;
  16389. methodParam.mResolvedType = resolvedParamType;
  16390. methodParam.mParamDefIdx = paramDefIdx;
  16391. mCurMethodInstance->mParams.push_back(methodParam);
  16392. }
  16393. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16394. {
  16395. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16396. }
  16397. }
  16398. else
  16399. {
  16400. BfMethodParam methodParam;
  16401. methodParam.mResolvedType = resolvedParamType;
  16402. methodParam.mParamDefIdx = paramDefIdx;
  16403. mCurMethodInstance->mParams.Add(methodParam);
  16404. }
  16405. }
  16406. if (hadDelegateParams)
  16407. {
  16408. HashSet<String> usedNames;
  16409. Dictionary<int, int> usedParamDefIdx;
  16410. for (auto methodParam : methodDef->mParams)
  16411. {
  16412. usedNames.Add(methodParam->mName);
  16413. }
  16414. for (auto& methodParam : mCurMethodInstance->mParams)
  16415. {
  16416. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16417. {
  16418. int* refCount = NULL;
  16419. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16420. (*refCount)++;
  16421. }
  16422. }
  16423. for (auto& methodParam : mCurMethodInstance->mParams)
  16424. {
  16425. if (methodParam.mDelegateParamIdx != -1)
  16426. {
  16427. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16428. methodParam.mDelegateParamNameCombine = true;
  16429. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16430. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16431. if (usedNames.Contains(paramName))
  16432. methodParam.mDelegateParamNameCombine = true;
  16433. }
  16434. }
  16435. }
  16436. int argIdx = 0;
  16437. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16438. if (methodInstance->HasStructRet())
  16439. argIdx++;
  16440. if (!methodDef->mIsStatic)
  16441. {
  16442. if (methodInstance->GetParamIsSplat(-1))
  16443. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16444. else if (!methodInstance->GetOwner()->IsValuelessType())
  16445. argIdx++;
  16446. }
  16447. for (auto& methodParam : mCurMethodInstance->mParams)
  16448. {
  16449. if (methodParam.mResolvedType->IsMethodRef())
  16450. {
  16451. methodParam.mIsSplat = true;
  16452. }
  16453. else if (methodParam.mResolvedType->IsComposite())
  16454. {
  16455. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16456. if (methodParam.mResolvedType->IsSplattable())
  16457. {
  16458. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16459. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16460. {
  16461. methodParam.mIsSplat = true;
  16462. argIdx += splatCount;
  16463. continue;
  16464. }
  16465. }
  16466. }
  16467. argIdx++;
  16468. }
  16469. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16470. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16471. {
  16472. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16473. }
  16474. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16475. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16476. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16477. (!methodDef->mIsSkipCall))
  16478. {
  16479. if (methodDeclaration->mEndSemicolon == NULL)
  16480. {
  16481. AssertParseErrorState();
  16482. }
  16483. else
  16484. {
  16485. bool isError = true;
  16486. if (typeInstance->IsTypedPrimitive())
  16487. {
  16488. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16489. {
  16490. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16491. {
  16492. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16493. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16494. {
  16495. isError = false;
  16496. }
  16497. }
  16498. }
  16499. }
  16500. if (isError)
  16501. {
  16502. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16503. MethodToString(methodInstance).c_str()),
  16504. methodDef->GetRefNode());
  16505. }
  16506. }
  16507. }
  16508. if (methodDef->IsEmptyPartial())
  16509. hasExternSpecifier = true;
  16510. if (!methodInstance->IsAutocompleteMethod())
  16511. {
  16512. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16513. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16514. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16515. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16516. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16517. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16518. int paramIdx = 0;
  16519. int defaultParamIdx = 0;
  16520. while (true)
  16521. {
  16522. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16523. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16524. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16525. {
  16526. paramIdx++;
  16527. continue;
  16528. }
  16529. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16530. {
  16531. defaultParamIdx++;
  16532. continue;
  16533. }
  16534. if ((isDone) || (isDefaultDone))
  16535. {
  16536. // 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
  16537. // to cause us to throw an assertion in the declaration here
  16538. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16539. BF_ASSERT((isDone) && (isDefaultDone));
  16540. break;
  16541. }
  16542. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16543. paramIdx++;
  16544. defaultParamIdx++;
  16545. }
  16546. }
  16547. StringT<128> mangledName;
  16548. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16549. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16550. {
  16551. auto paramType = methodInstance->GetParamType(paramIdx);
  16552. if (paramType->IsComposite())
  16553. PopulateType(paramType, BfPopulateType_Data);
  16554. if (!methodInstance->IsParamSkipped(paramIdx))
  16555. {
  16556. if (paramType->IsStruct())
  16557. {
  16558. //
  16559. }
  16560. else
  16561. {
  16562. PopulateType(paramType, BfPopulateType_Declaration);
  16563. }
  16564. }
  16565. }
  16566. // Only process method in default unspecialized mode, not in variations
  16567. if (methodInstance->mIsUnspecializedVariation)
  16568. return;
  16569. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16570. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16571. if (resolvedReturnType->IsValuelessType())
  16572. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16573. if (!mBfIRBuilder->mIgnoreWrites)
  16574. {
  16575. bool isIntrinsic = false;
  16576. if (!methodInstance->mIRFunction)
  16577. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16578. if (isIntrinsic)
  16579. {
  16580. addToWorkList = false;
  16581. }
  16582. }
  16583. auto func = methodInstance->mIRFunction;
  16584. // if (methodInstance->mIsReified)
  16585. // CheckHotMethod(methodInstance, mangledName);
  16586. 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);
  16587. SizedArray<BfIRMDNode, 8> diParams;
  16588. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16589. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16590. {
  16591. //CS0708
  16592. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16593. }
  16594. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16595. {
  16596. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16597. methodDef->mIsVirtual = false;
  16598. }
  16599. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16600. {
  16601. if (methodDef->mIsStatic)
  16602. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16603. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16604. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16605. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16606. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16607. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16608. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16609. }
  16610. if (isTemporaryFunc)
  16611. {
  16612. // This handles temporary methods for autocomplete types
  16613. BF_ASSERT(mIsScratchModule);
  16614. BF_ASSERT(mCompiler->IsAutocomplete());
  16615. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16616. return; // Bail out early for autocomplete pass
  16617. }
  16618. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16619. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16620. // autocompleter. Why did we have this check anyway?
  16621. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16622. {
  16623. AddMethodReference(methodInstance);
  16624. mFuncReferences[methodInstance] = func;
  16625. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16626. }*/
  16627. if (mParentModule != NULL)
  16628. {
  16629. // For extension modules we need to keep track of our own methods so we can know which methods
  16630. // we have defined ourselves and which are from the parent module or other extensions
  16631. if (!func.IsFake())
  16632. mFuncReferences[methodInstance] = func;
  16633. }
  16634. if (addToWorkList)
  16635. {
  16636. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16637. if (wasAwaitingDecl)
  16638. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16639. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16640. {
  16641. if (!wasAwaitingDecl)
  16642. AddMethodToWorkList(methodInstance);
  16643. }
  16644. else
  16645. {
  16646. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16647. methodInstance->mIgnoreBody = true;
  16648. if (typeInstance->IsUnspecializedType())
  16649. {
  16650. // Don't hold on to actual Function for unspecialized types
  16651. methodInstance->mIRFunction = BfIRFunction();
  16652. }
  16653. }
  16654. }
  16655. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16656. (!methodDef->mIsLocalMethod) &&
  16657. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16658. {
  16659. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16660. {
  16661. //TODO:
  16662. //CS0053
  16663. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16664. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16665. methodDef->mReturnTypeRef, true);
  16666. }
  16667. else
  16668. {
  16669. //CS0050
  16670. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16671. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16672. methodDef->mReturnTypeRef, true);
  16673. }
  16674. }
  16675. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16676. {
  16677. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16678. }
  16679. // Don't compare specialized generic methods against normal methods
  16680. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16681. (!methodDef->mIsLocalMethod))
  16682. {
  16683. if (!methodInstance->mIsForeignMethodDef)
  16684. {
  16685. typeDef->PopulateMemberSets();
  16686. BfMethodDef* nextMethod = NULL;
  16687. BfMemberSetEntry* entry = NULL;
  16688. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16689. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16690. while (nextMethod != NULL)
  16691. {
  16692. auto checkMethod = nextMethod;
  16693. nextMethod = nextMethod->mNextWithSameName;
  16694. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16695. {
  16696. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16697. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16698. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16699. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16700. {
  16701. bool canChain = false;
  16702. if ((methodDef->mParams.empty()) &&
  16703. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16704. {
  16705. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16706. canChain = true;
  16707. else if (methodDef->mMethodType == BfMethodType_Normal)
  16708. {
  16709. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16710. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16711. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16712. canChain = true;
  16713. }
  16714. }
  16715. if (canChain)
  16716. {
  16717. bool isBetter;
  16718. bool isWorse;
  16719. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16720. if (isBetter && !isWorse)
  16721. {
  16722. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16723. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16724. }
  16725. else
  16726. {
  16727. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16728. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16729. }
  16730. }
  16731. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16732. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16733. {
  16734. // We're allowed to override an empty-bodied method
  16735. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16736. }
  16737. else
  16738. {
  16739. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16740. continue;
  16741. bool silentlyAllow = false;
  16742. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16743. {
  16744. if (typeInstance->IsInterface())
  16745. {
  16746. if (methodDef->mIsOverride)
  16747. silentlyAllow = true;
  16748. }
  16749. else
  16750. silentlyAllow = true;
  16751. }
  16752. if (!silentlyAllow)
  16753. {
  16754. if (!methodDef->mName.IsEmpty())
  16755. {
  16756. auto refNode = methodDef->GetRefNode();
  16757. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16758. if (bfError != NULL)
  16759. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16760. }
  16761. }
  16762. }
  16763. }
  16764. }
  16765. }
  16766. }
  16767. // Virtual methods give their error while slotting
  16768. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16769. (!methodDef->mIsLocalMethod) &&
  16770. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16771. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16772. {
  16773. bool foundHiddenMethod = false;
  16774. auto baseType = typeInstance->mBaseType;
  16775. while (baseType != NULL)
  16776. {
  16777. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16778. auto baseTypeDef = baseType->mTypeDef;
  16779. baseTypeDef->PopulateMemberSets();
  16780. BfMethodDef* checkMethod = NULL;
  16781. BfMemberSetEntry* entry = NULL;
  16782. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16783. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16784. while (checkMethod != NULL)
  16785. {
  16786. if (checkMethod->mMethodDeclaration == NULL)
  16787. continue;
  16788. if (baseType->mMethodInstanceGroups.size() == 0)
  16789. {
  16790. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16791. break;
  16792. }
  16793. if (checkMethod == methodDef)
  16794. continue;
  16795. if (checkMethod->mName != methodDef->mName)
  16796. continue;
  16797. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16798. if (checkMethodInstance != NULL)
  16799. {
  16800. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16801. (checkMethod->mProtection != BfProtection_Private) &&
  16802. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16803. {
  16804. if (!methodDef->mIsNew)
  16805. {
  16806. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16807. if (refNode != NULL)
  16808. {
  16809. 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?
  16810. if (bfError != NULL)
  16811. bfError->mIsPersistent = true;
  16812. }
  16813. }
  16814. foundHiddenMethod = true;
  16815. break;
  16816. }
  16817. }
  16818. checkMethod = checkMethod->mNextWithSameName;
  16819. }
  16820. if (foundHiddenMethod)
  16821. break;
  16822. baseType = baseType->mBaseType;
  16823. }
  16824. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16825. {
  16826. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16827. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16828. methodDeclaration->mNewSpecifier;
  16829. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16830. }
  16831. }
  16832. }
  16833. mCompiler->mStats.mMethodDeclarations++;
  16834. mCompiler->UpdateCompletion();
  16835. }
  16836. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16837. {
  16838. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16839. auto typeInstance = mCurTypeInstance;
  16840. auto methodDef = methodInstance->mMethodDef;
  16841. int virtualMethodMatchIdx = -1;
  16842. if (typeInstance->mHotTypeData != NULL)
  16843. {
  16844. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16845. {
  16846. BF_ASSERT(mCompiler->IsHotCompile());
  16847. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16848. // may slot this override anyway (?)
  16849. int vTableStart = 0;
  16850. if (typeInstance->mBaseType != NULL)
  16851. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16852. StringT<128> mangledName;
  16853. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16854. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16855. {
  16856. // O(1) checking when virtual methods haven't changed
  16857. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16858. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16859. if (mangledName == entry.mFuncName)
  16860. {
  16861. virtualMethodMatchIdx = vTableStart + checkIdx;
  16862. break;
  16863. }
  16864. }
  16865. if (virtualMethodMatchIdx != -1)
  16866. {
  16867. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16868. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16869. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16870. }
  16871. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16872. }
  16873. }
  16874. if (virtualMethodMatchIdx == -1)
  16875. {
  16876. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16877. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16878. typeInstance->mVirtualMethodTable.push_back(entry);
  16879. }
  16880. }
  16881. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16882. {
  16883. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16884. {
  16885. // When we provide an extension override in the same project a root type override
  16886. isBetter = true;
  16887. isWorse = false;
  16888. }
  16889. else
  16890. {
  16891. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  16892. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  16893. }
  16894. }
  16895. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  16896. {
  16897. BP_ZONE("BfModule::SlotVirtualMethod");
  16898. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  16899. return false;
  16900. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  16901. {
  16902. if (!mCompiler->mOptions.mAllowHotSwapping)
  16903. return;
  16904. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  16905. return;
  16906. if (methodInstance->mHotMethod == NULL)
  16907. CheckHotMethod(methodInstance, "");
  16908. if (methodInstance->mHotMethod == NULL)
  16909. return;
  16910. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  16911. if (declMethodInstance->mHotMethod == NULL)
  16912. CheckHotMethod(declMethodInstance, "");
  16913. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  16914. virtualDecl->mRefCount++;
  16915. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  16916. };
  16917. auto typeInstance = mCurTypeInstance;
  16918. auto typeDef = typeInstance->mTypeDef;
  16919. auto methodDef = methodInstance->mMethodDef;
  16920. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16921. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16922. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  16923. BfAstNode* declaringNode = methodDeclaration;
  16924. if (propertyMethodDeclaration != NULL)
  16925. declaringNode = propertyMethodDeclaration->mNameNode;
  16926. BfMethodInstance* methodOverriden = NULL;
  16927. bool usedMethod = false;
  16928. BfTokenNode* virtualToken = NULL;
  16929. if (propertyDeclaration != NULL)
  16930. virtualToken = propertyDeclaration->mVirtualSpecifier;
  16931. else if (methodDeclaration != NULL)
  16932. virtualToken = methodDeclaration->mVirtualSpecifier;
  16933. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  16934. {
  16935. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  16936. }
  16937. else if (methodDef->mIsVirtual)
  16938. {
  16939. if (mCompiler->IsHotCompile())
  16940. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  16941. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  16942. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  16943. BfTypeInstance* checkBase = typeInstance;
  16944. // If we are in an extension, look in ourselves first
  16945. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  16946. checkBase = checkBase->mBaseType;
  16947. if (typeInstance->IsValueType())
  16948. {
  16949. if (typeInstance->mBaseType == NULL)
  16950. return false; // It's actually ValueType
  16951. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  16952. if (!methodDef->mIsOverride)
  16953. {
  16954. Fail("Structs cannot have virtual methods", virtualToken, true);
  16955. return false;
  16956. }
  16957. checkBase = mContext->mBfObjectType;
  16958. if (checkBase->mVirtualMethodTableSize == 0)
  16959. PopulateType(checkBase, BfPopulateType_Full);
  16960. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  16961. return false; // System circular ref, don't do struct checking on those
  16962. }
  16963. int virtualMethodMatchIdx = -1;
  16964. bool hadHidingError = false;
  16965. BfMethodInstance* bestOverrideMethodInstance = NULL;
  16966. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  16967. int bestOverrideMethodIdx = -1;
  16968. int ambiguousOverrideMethodIdx = -1;
  16969. if (checkBase != NULL)
  16970. {
  16971. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  16972. auto lookupType = checkBase;
  16973. while (lookupType != NULL)
  16974. {
  16975. lookupType->mTypeDef->PopulateMemberSets();
  16976. BfMethodDef* nextMethodDef = NULL;
  16977. BfMemberSetEntry* entry;
  16978. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  16979. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  16980. while (nextMethodDef != NULL)
  16981. {
  16982. auto checkMethodDef = nextMethodDef;
  16983. nextMethodDef = nextMethodDef->mNextWithSameName;
  16984. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  16985. continue;
  16986. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  16987. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  16988. continue;
  16989. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  16990. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  16991. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  16992. {
  16993. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  16994. continue;
  16995. }
  16996. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  16997. if (baseMethodInstance == NULL)
  16998. {
  16999. AssertErrorState();
  17000. continue;
  17001. }
  17002. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17003. {
  17004. if (methodDef->mIsOverride)
  17005. {
  17006. BfMethodInstance* checkMethodInstance;
  17007. if (typeInstance->IsValueType())
  17008. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17009. else
  17010. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17011. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17012. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17013. continue;
  17014. if (bestOverrideMethodInstance != NULL)
  17015. {
  17016. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17017. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17018. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17019. if (isBetter == isWorse)
  17020. {
  17021. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17022. }
  17023. else
  17024. {
  17025. if (isWorse)
  17026. continue;
  17027. ambiguousOverrideMethodInstance = NULL;
  17028. }
  17029. }
  17030. bestOverrideMethodInstance = checkMethodInstance;
  17031. bestOverrideMethodIdx = checkMethodIdx;
  17032. }
  17033. else
  17034. {
  17035. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17036. {
  17037. if (!hadHidingError)
  17038. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17039. hadHidingError = true;
  17040. }
  17041. }
  17042. }
  17043. }
  17044. lookupType = lookupType->mBaseType;
  17045. }
  17046. }
  17047. //TODO:
  17048. if ((checkBase != NULL)
  17049. && (false)
  17050. )
  17051. {
  17052. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17053. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17054. {
  17055. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17056. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17057. {
  17058. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17059. continue;
  17060. }
  17061. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17062. if (baseMethodInstance == NULL)
  17063. {
  17064. AssertErrorState();
  17065. continue;
  17066. }
  17067. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17068. {
  17069. if (methodDef->mIsOverride)
  17070. {
  17071. BfMethodInstance* checkMethodInstance;
  17072. if (typeInstance->IsValueType())
  17073. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17074. else
  17075. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17076. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17077. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17078. continue;
  17079. if (bestOverrideMethodInstance != NULL)
  17080. {
  17081. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17082. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17083. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17084. if (isBetter == isWorse)
  17085. {
  17086. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17087. }
  17088. else
  17089. {
  17090. if (isWorse)
  17091. continue;
  17092. ambiguousOverrideMethodInstance = NULL;
  17093. }
  17094. }
  17095. bestOverrideMethodInstance = checkMethodInstance;
  17096. bestOverrideMethodIdx = checkMethodIdx;
  17097. }
  17098. else
  17099. {
  17100. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17101. {
  17102. if (!hadHidingError)
  17103. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17104. hadHidingError = true;
  17105. }
  17106. }
  17107. }
  17108. }
  17109. }
  17110. if (bestOverrideMethodInstance != NULL)
  17111. {
  17112. if (ambiguousOverrideMethodInstance != NULL)
  17113. {
  17114. bool allow = false;
  17115. // 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.
  17116. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17117. bool canSeeEachOther = false;
  17118. //
  17119. {
  17120. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17121. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17122. canSeeEachOther = true;
  17123. }
  17124. //
  17125. {
  17126. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17127. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17128. canSeeEachOther = true;
  17129. }
  17130. if (!canSeeEachOther)
  17131. {
  17132. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17133. }
  17134. else
  17135. {
  17136. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17137. if (error != NULL)
  17138. {
  17139. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17140. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17141. }
  17142. }
  17143. }
  17144. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17145. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17146. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17147. {
  17148. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17149. {
  17150. BfTypeReference* returnTypeRef;
  17151. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17152. {
  17153. returnTypeRef = propertyDeclaration->mTypeRef;
  17154. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17155. }
  17156. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17157. {
  17158. returnTypeRef = methodDeclaration->mReturnType;
  17159. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17160. }
  17161. else
  17162. {
  17163. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17164. }
  17165. return usedMethod;
  17166. }
  17167. }
  17168. if (methodDef->mIsOverride)
  17169. {
  17170. // We can have multiple matches when a virtual method is used to implement interface methods
  17171. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17172. // vtable entries for this method signature
  17173. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17174. if (!typeInstance->IsValueType())
  17175. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17176. if (typeInstance->IsValueType())
  17177. {
  17178. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17179. }
  17180. else
  17181. {
  17182. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17183. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17184. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17185. {
  17186. methodOverriden = overridenRef;
  17187. BfMethodInstance* setMethodInstance = methodInstance;
  17188. bool doOverride = true;
  17189. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17190. {
  17191. bool isBetter = false;
  17192. bool isWorse = false;
  17193. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17194. if (isBetter == isWorse)
  17195. {
  17196. // We have to resolve later per-project
  17197. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17198. {
  17199. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17200. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17201. }
  17202. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17203. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17204. doOverride = false;
  17205. }
  17206. else
  17207. {
  17208. if ((isBetter) && (ambiguityContext != NULL))
  17209. {
  17210. ambiguityContext->Remove(virtualMethodMatchIdx);
  17211. }
  17212. doOverride = isBetter;
  17213. }
  17214. }
  17215. if (doOverride)
  17216. {
  17217. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17218. _AddVirtualDecl(declMethodInstance);
  17219. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17220. }
  17221. }
  17222. }
  17223. if (methodOverriden != NULL)
  17224. {
  17225. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17226. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17227. {
  17228. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17229. BfAstNode* protectionRefNode = NULL;
  17230. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17231. {
  17232. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17233. if (protectionRefNode == NULL)
  17234. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17235. if (protectionRefNode == NULL)
  17236. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17237. }
  17238. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17239. {
  17240. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17241. if (protectionRefNode == NULL)
  17242. protectionRefNode = methodDeclaration->mNameNode;
  17243. }
  17244. if (protectionRefNode != NULL)
  17245. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17246. }
  17247. }
  17248. }
  17249. }
  17250. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17251. {
  17252. if (methodDef->mIsOverride)
  17253. {
  17254. BfTokenNode* overrideToken = NULL;
  17255. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17256. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17257. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17258. overrideToken = methodDeclaration->mVirtualSpecifier;
  17259. if (overrideToken != NULL)
  17260. {
  17261. Fail("No suitable method found to override", overrideToken, true);
  17262. }
  17263. return usedMethod;
  17264. }
  17265. UniqueSlotVirtualMethod(methodInstance);
  17266. }
  17267. else
  17268. usedMethod = true;
  17269. if (typeInstance->IsValueType())
  17270. return usedMethod;
  17271. }
  17272. bool foundInterface = false;
  17273. bool hadAnyMatch = false;
  17274. // See if this method matches interfaces
  17275. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17276. {
  17277. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17278. if (ifaceInst->IsIncomplete())
  17279. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17280. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17281. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17282. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17283. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17284. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17285. continue;
  17286. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17287. continue;
  17288. bool hadMatch = false;
  17289. bool hadNameMatch = false;
  17290. BfType* expectedReturnType = NULL;
  17291. bool showedError = false;
  17292. // We go through our VTable looking for NULL entries within the interface sections
  17293. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17294. // because a normal method declared in this type could have matched earlier
  17295. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17296. ifaceInst->mTypeDef->PopulateMemberSets();
  17297. BfMethodDef* checkMethodDef = NULL;
  17298. BfMemberSetEntry* entry;
  17299. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17300. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17301. while (checkMethodDef != NULL)
  17302. {
  17303. int iMethodIdx = checkMethodDef->mIdx;
  17304. int iTableIdx = iMethodIdx + startIdx;
  17305. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17306. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17307. bool storeIFaceMethod = false;
  17308. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17309. continue;
  17310. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17311. auto iMethodInst = iMethodGroup.mDefault;
  17312. if (iMethodInst == NULL)
  17313. {
  17314. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17315. AssertErrorState();
  17316. continue;
  17317. }
  17318. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17319. hadNameMatch = true;
  17320. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17321. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17322. {
  17323. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17324. }
  17325. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17326. {
  17327. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17328. {
  17329. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17330. {
  17331. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17332. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17333. if (error != NULL)
  17334. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17335. showedError = true;
  17336. }
  17337. }
  17338. }
  17339. if (doesMethodSignatureMatch)
  17340. {
  17341. usedMethod = true;
  17342. hadMatch = true;
  17343. hadAnyMatch = true;
  17344. storeIFaceMethod = true;
  17345. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17346. {
  17347. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17348. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17349. {
  17350. // When autocompletion regenerates a single method body but not the whole type then
  17351. // we will see ourselves in the vtable already
  17352. return usedMethod;
  17353. }
  17354. bool isBetter = false;
  17355. bool isWorse = false;
  17356. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17357. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17358. if (isBetter == isWorse)
  17359. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17360. if (isBetter == isWorse)
  17361. {
  17362. if (ambiguityContext != NULL)
  17363. {
  17364. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17365. }
  17366. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17367. storeIFaceMethod = true;
  17368. }
  17369. else
  17370. {
  17371. if ((isBetter) && (ambiguityContext != NULL))
  17372. ambiguityContext->Remove(~iTableIdx);
  17373. storeIFaceMethod = isBetter;
  17374. }
  17375. }
  17376. }
  17377. if (storeIFaceMethod)
  17378. {
  17379. _AddVirtualDecl(iMethodInst);
  17380. *iMethodPtr = methodInstance;
  17381. }
  17382. checkMethodDef = checkMethodDef->mNextWithSameName;
  17383. }
  17384. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17385. {
  17386. if (expectedReturnType != NULL)
  17387. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17388. else if (hadNameMatch)
  17389. Fail("Method parameters don't match interface method", declaringNode, true);
  17390. else
  17391. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17392. }
  17393. }
  17394. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17395. if (methodOverriden != NULL)
  17396. {
  17397. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17398. {
  17399. if (methodEntry.mMethodRef == methodOverriden)
  17400. methodEntry.mMethodRef = methodInstance;
  17401. }
  17402. }
  17403. return usedMethod;
  17404. }
  17405. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17406. {
  17407. auto typeInstance = mCurTypeInstance;
  17408. auto methodDef = methodInstance->mMethodDef;
  17409. if (methodDef->mMethodType == BfMethodType_Ctor)
  17410. return true;
  17411. bool foundOverride = false;
  17412. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17413. {
  17414. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17415. }
  17416. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17417. {
  17418. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17419. }
  17420. BfAstNode* declaringNode = methodDef->GetRefNode();
  17421. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17422. {
  17423. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17424. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17425. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17426. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17427. continue;
  17428. ifaceInst->mTypeDef->PopulateMemberSets();
  17429. BfMethodDef* nextMethod = NULL;
  17430. BfMemberSetEntry* entry = NULL;
  17431. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17432. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17433. while (nextMethod != NULL)
  17434. {
  17435. auto checkMethod = nextMethod;
  17436. nextMethod = nextMethod->mNextWithSameName;
  17437. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17438. if (ifaceMethod == NULL)
  17439. continue;
  17440. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17441. {
  17442. if (methodDef->mIsOverride)
  17443. {
  17444. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17445. {
  17446. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17447. if (error != NULL)
  17448. {
  17449. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17450. }
  17451. }
  17452. foundOverride = true;
  17453. }
  17454. else if (!methodDef->mIsNew)
  17455. {
  17456. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17457. }
  17458. }
  17459. }
  17460. }
  17461. if ((methodDef->mIsOverride) && (!foundOverride))
  17462. {
  17463. // This allows us to declare a method in the base definition or in an extension and then provide
  17464. // an implementation in a more-specific extension
  17465. typeInstance->mTypeDef->PopulateMemberSets();
  17466. BfMethodDef* nextMethod = NULL;
  17467. BfMemberSetEntry* entry = NULL;
  17468. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17469. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17470. while (nextMethod != NULL)
  17471. {
  17472. auto checkMethod = nextMethod;
  17473. nextMethod = nextMethod->mNextWithSameName;
  17474. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17475. if (ifaceMethod == NULL)
  17476. continue;
  17477. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17478. continue;
  17479. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17480. {
  17481. foundOverride = true;
  17482. }
  17483. }
  17484. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17485. // {
  17486. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17487. // if (ifaceMethod == NULL)
  17488. // continue;
  17489. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17490. // continue;
  17491. //
  17492. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17493. // {
  17494. // foundOverride = true;
  17495. // }
  17496. // }
  17497. }
  17498. if (methodDef->mIsOverride)
  17499. {
  17500. if (!foundOverride)
  17501. {
  17502. BfTokenNode* overrideToken = NULL;
  17503. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17504. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17505. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17506. overrideToken = methodDeclaration->mVirtualSpecifier;
  17507. if (overrideToken != NULL)
  17508. {
  17509. Fail("No suitable method found to override", overrideToken, true);
  17510. }
  17511. else
  17512. {
  17513. // Possible cause - DTOR with params
  17514. AssertErrorState();
  17515. }
  17516. }
  17517. return true;
  17518. }
  17519. // Generic methods can't be called virtually
  17520. if (methodInstance->GetNumGenericParams() != 0)
  17521. return true;
  17522. // Only public methods can be called virtually
  17523. if (methodDef->mProtection != BfProtection_Public)
  17524. return true;
  17525. UniqueSlotVirtualMethod(methodInstance);
  17526. return true;
  17527. }
  17528. void BfModule::DbgFinish()
  17529. {
  17530. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17531. return;
  17532. if (mAwaitingInitFinish)
  17533. FinishInit();
  17534. if (mHasForceLinkMarker)
  17535. return;
  17536. String markerName;
  17537. BfIRValue linkMarker;
  17538. if (mBfIRBuilder->DbgHasInfo())
  17539. {
  17540. bool needForceLinking = false;
  17541. for (auto& ownedType : mOwnedTypeInstances)
  17542. {
  17543. bool hasConfirmedReference = false;
  17544. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17545. {
  17546. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17547. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17548. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17549. {
  17550. hasConfirmedReference = true;
  17551. }
  17552. }
  17553. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17554. needForceLinking = true;
  17555. }
  17556. if (needForceLinking)
  17557. {
  17558. BfMethodState methodState;
  17559. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17560. methodState.mTempKind = BfMethodState::TempKind_Static;
  17561. mHasForceLinkMarker = true;
  17562. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17563. SizedArray<BfIRType, 0> paramTypes;
  17564. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17565. String linkName = "FORCELINKMOD_" + mModuleName;
  17566. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17567. mBfIRBuilder->SetActiveFunction(func);
  17568. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17569. mBfIRBuilder->SetInsertPoint(entryBlock);
  17570. auto firstType = mOwnedTypeInstances[0];
  17571. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17572. SizedArray<BfIRMDNode, 1> diParamTypes;
  17573. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17574. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17575. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17576. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17577. methodState.mCurScope->mDIScope = diScope;
  17578. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17579. SizedArray<BfIRValue, 8> args;
  17580. BfExprEvaluator exprEvaluator(this);
  17581. for (auto& ownedType : mOwnedTypeInstances)
  17582. {
  17583. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17584. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17585. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17586. }
  17587. mBfIRBuilder->CreateRetVoid();
  17588. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17589. }
  17590. }
  17591. }
  17592. bool BfModule::Finish()
  17593. {
  17594. BP_ZONE("BfModule::Finish");
  17595. BfLogSysM("BfModule finish: %p\n", this);
  17596. if (mCompiler->mCanceling)
  17597. {
  17598. NOP;
  17599. }
  17600. if (mModuleName == "System_Array")
  17601. {
  17602. NOP;
  17603. }
  17604. if (mHadBuildError)
  17605. {
  17606. // Don't AssertErrorState here, this current pass may not have failed but
  17607. // the module was still queued in mFinishedModuleWorkList
  17608. ClearModule();
  17609. return true;
  17610. }
  17611. if (mUsedSlotCount != -1)
  17612. {
  17613. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17614. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17615. }
  17616. BF_ASSERT(mAddedToCount);
  17617. mAddedToCount = false;
  17618. mAwaitingFinish = false;
  17619. mCompiler->mStats.mModulesFinished++;
  17620. if (HasCompiledOutput())
  17621. {
  17622. DbgFinish();
  17623. if (mAwaitingInitFinish)
  17624. FinishInit();
  17625. for (auto ownedTypeInst : mOwnedTypeInstances)
  17626. {
  17627. // Generate dbg info and add global variables if we haven't already
  17628. mBfIRBuilder->PopulateType(ownedTypeInst);
  17629. }
  17630. if (mBfIRBuilder->DbgHasInfo())
  17631. {
  17632. mBfIRBuilder->DbgFinalize();
  17633. }
  17634. String objOutputPath;
  17635. String irOutputPath;
  17636. mIsModuleMutable = false;
  17637. //mOutFileNames.Clear();
  17638. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17639. bool writeModule = mBfIRBuilder->HasExports();
  17640. // if ((!writeModule) && (!IsOptimized()))
  17641. // {
  17642. // CreateForceLinkMarker(this);
  17643. // mHasForceLinkMarker = true;
  17644. // writeModule = true;
  17645. // }
  17646. String outputPath;
  17647. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17648. auto& compilerOpts = mCompiler->mOptions;
  17649. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17650. auto moduleOptions = GetModuleOptions();
  17651. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17652. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17653. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17654. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17655. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17656. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17657. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17658. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17659. bool allowWriteToLib = true;
  17660. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17661. {
  17662. codeGenOptions.mWriteToLib = true;
  17663. mWroteToLib = true;
  17664. }
  17665. else
  17666. {
  17667. mWroteToLib = false;
  17668. }
  17669. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17670. {
  17671. outputPath = mModuleName;
  17672. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17673. BfModuleFileName moduleFileName;
  17674. if (mParentModule != NULL)
  17675. {
  17676. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17677. {
  17678. if (checkPair.mValue == this)
  17679. moduleFileName.mProjects = checkPair.mKey;
  17680. }
  17681. }
  17682. moduleFileName.mProjects.Add(mProject);
  17683. if (fileIdx > 0)
  17684. outputPath += StrFormat("@%d", fileIdx + 1);
  17685. if (mCompiler->mOptions.mWriteIR)
  17686. irOutputPath = outputPath + ".ll";
  17687. if (mCompiler->mOptions.mGenerateObj)
  17688. {
  17689. objOutputPath = outputPath + BF_OBJ_EXT;
  17690. moduleFileName.mFileName = objOutputPath;
  17691. }
  17692. else if (mCompiler->mOptions.mWriteIR)
  17693. {
  17694. moduleFileName.mFileName = irOutputPath;
  17695. }
  17696. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mWriteIR))
  17697. {
  17698. BF_FATAL("Neither obj nor IR specified");
  17699. }
  17700. moduleFileName.mModuleWritten = writeModule;
  17701. moduleFileName.mWroteToLib = mWroteToLib;
  17702. if (!mOutFileNames.Contains(moduleFileName))
  17703. mOutFileNames.Add(moduleFileName);
  17704. }
  17705. if (mCompiler->IsHotCompile())
  17706. {
  17707. codeGenOptions.mIsHotCompile = true;
  17708. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17709. // is required for rebuilding vdata after we hot create a vdata
  17710. //if (mWroteToLib)
  17711. {
  17712. if (mParentModule != NULL)
  17713. mParentModule->mHadHotObjectWrites = true;
  17714. mHadHotObjectWrites = true;
  17715. }
  17716. }
  17717. //TODO: Testing VDATA
  17718. /*if (mModuleName == "vdata")
  17719. {
  17720. codeGenOptions.mOptLevel = 4;
  17721. }*/
  17722. codeGenOptions.GenerateHash();
  17723. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17724. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17725. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17726. mLastModuleWrittenRevision = mCompiler->mRevision;
  17727. }
  17728. else
  17729. {
  17730. for (auto type : mOwnedTypeInstances)
  17731. {
  17732. BF_ASSERT(!type->IsIncomplete());
  17733. }
  17734. }
  17735. for (auto& specModulePair : mSpecializedMethodModules)
  17736. {
  17737. auto specModule = specModulePair.mValue;
  17738. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17739. {
  17740. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17741. }
  17742. }
  17743. CleanupFileInstances();
  17744. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17745. return true;
  17746. }
  17747. void BfModule::ReportMemory(MemReporter* memReporter)
  17748. {
  17749. memReporter->Add(sizeof(BfModule));
  17750. if (mBfIRBuilder != NULL)
  17751. {
  17752. memReporter->BeginSection("IRBuilder_ConstData");
  17753. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17754. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17755. memReporter->EndSection();
  17756. memReporter->BeginSection("IRBuilder_BFIR");
  17757. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17758. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17759. memReporter->EndSection();
  17760. memReporter->Add(sizeof(BfIRBuilder));
  17761. }
  17762. memReporter->BeginSection("FileInstanceMap");
  17763. memReporter->AddMap(mFileInstanceMap);
  17764. memReporter->AddMap(mNamedFileInstanceMap);
  17765. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17766. memReporter->EndSection();
  17767. memReporter->AddVec(mOwnedTypeInstances, false);
  17768. memReporter->AddVec(mSpecializedMethodModules, false);
  17769. memReporter->AddVec(mOutFileNames, false);
  17770. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17771. memReporter->AddMap(mInterfaceSlotRefs, false);
  17772. memReporter->AddMap(mStaticFieldRefs, false);
  17773. memReporter->AddMap(mClassVDataRefs, false);
  17774. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17775. memReporter->AddMap(mTypeDataRefs, false);
  17776. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17777. memReporter->AddMap(mDeferredMethodCallData, false);
  17778. memReporter->AddHashSet(mDeferredMethodIds, false);
  17779. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17780. }
  17781. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17782. // be transient through the next compile
  17783. void BfModule::ClearModuleData()
  17784. {
  17785. BfLogSysM("ClearModuleData %p\n", this);
  17786. if (mAddedToCount)
  17787. {
  17788. mCompiler->mStats.mModulesFinished++;
  17789. mAddedToCount = false;
  17790. }
  17791. if (mCompiler->mCanceling)
  17792. {
  17793. NOP;
  17794. }
  17795. mDICompileUnit = BfIRMDNode();
  17796. mIsModuleMutable = false;
  17797. mIncompleteMethodCount = 0;
  17798. mHasGenericMethods = false;
  17799. // We don't want to clear these because we want it to persist through module extensions-
  17800. // otherwise we may think an extension succeeds even though the base module failed
  17801. //mHadBuildError = false;
  17802. //mHadBuildWarning = false;
  17803. mClassVDataRefs.Clear();
  17804. mClassVDataExtRefs.Clear();
  17805. for (auto& kv : mTypeDataRefs)
  17806. kv.mValue = BfIRValue();
  17807. mStringCharPtrPool.Clear();
  17808. mStringObjectPool.Clear();
  17809. mStaticFieldRefs.Clear();
  17810. BF_ASSERT(!mIgnoreErrors);
  17811. for (auto prevIRBuilder : mPrevIRBuilders)
  17812. delete prevIRBuilder;
  17813. mPrevIRBuilders.Clear();
  17814. for (auto& specPair : mSpecializedMethodModules)
  17815. {
  17816. auto specModule = specPair.mValue;
  17817. specModule->ClearModuleData();
  17818. }
  17819. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17820. mBuiltInFuncs[i] = BfIRFunction();
  17821. if (mNextAltModule != NULL)
  17822. mNextAltModule->ClearModuleData();
  17823. for (auto typeInstance : mOwnedTypeInstances)
  17824. {
  17825. if (typeInstance->IsSpecializedType())
  17826. {
  17827. for (auto&& methodGroup : typeInstance->mMethodInstanceGroups)
  17828. {
  17829. if (methodGroup.mDefault != NULL)
  17830. methodGroup.mDefault->mDeclModule = NULL;
  17831. }
  17832. }
  17833. }
  17834. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17835. delete mBfIRBuilder;
  17836. mBfIRBuilder = NULL;
  17837. mWantsIRIgnoreWrites = false;
  17838. }
  17839. void BfModule::DisownMethods()
  17840. {
  17841. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17842. mBuiltInFuncs[i] = BfIRFunction();
  17843. BfModule* methodModule = this;
  17844. if (mParentModule != NULL)
  17845. methodModule = mParentModule;
  17846. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17847. {
  17848. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17849. {
  17850. if (methodGroup.mDefault != NULL)
  17851. {
  17852. if (methodGroup.mDefault->mDeclModule == this)
  17853. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17854. }
  17855. if (methodGroup.mMethodSpecializationMap != NULL)
  17856. {
  17857. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17858. {
  17859. auto methodInstance = mapPair.mValue;
  17860. if (methodInstance->mDeclModule == this)
  17861. methodInstance->mIRFunction = BfIRFunction();
  17862. }
  17863. }
  17864. }
  17865. }
  17866. }
  17867. void BfModule::ClearModule()
  17868. {
  17869. ClearModuleData();
  17870. DisownMethods();
  17871. for (auto& specPair : mSpecializedMethodModules)
  17872. {
  17873. auto specModule = specPair.mValue;
  17874. specModule->ClearModule();
  17875. }
  17876. if (mNextAltModule != NULL)
  17877. mNextAltModule->ClearModule();
  17878. }