2
0

BfModule.cpp 699 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mHadIgnoredError = false;
  698. mReportErrors = true;
  699. mIsInsideAutoComplete = false;
  700. mIsDeleting = false;
  701. mSkipInnerLookup = false;
  702. mIsHotModule = false;
  703. mSetIllegalSrcPosition = false;
  704. mNoResolveGenericParams = false;
  705. mWroteToLib = false;
  706. mContext = context;
  707. mCompiler = context->mCompiler;
  708. mSystem = mCompiler->mSystem;
  709. mProject = NULL;
  710. mCurMethodState = NULL;
  711. mAttributeState = NULL;
  712. mCurLocalMethodId = 0;
  713. mParentNodeEntry = NULL;
  714. mRevision = -1;
  715. mRebuildIdx = 0;
  716. mLastModuleWrittenRevision = 0;
  717. mIsModuleMutable = false;
  718. mExtensionCount = 0;
  719. mIncompleteMethodCount = 0;
  720. mOnDemandMethodCount = 0;
  721. mHasGenericMethods = false;
  722. mCurMethodInstance = NULL;
  723. mCurTypeInstance = NULL;
  724. mAwaitingInitFinish = false;
  725. mAwaitingFinish = false;
  726. mHasFullDebugInfo = false;
  727. mHadHotObjectWrites = false;
  728. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  729. mBuiltInFuncs[i] = BfIRFunction();
  730. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  731. }
  732. void BfReportMemory();
  733. BfModule::~BfModule()
  734. {
  735. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  736. if (!mIsDeleting)
  737. RemoveModuleData();
  738. }
  739. void BfModule::RemoveModuleData()
  740. {
  741. BF_ASSERT(!mIsDeleting);
  742. if (!mModuleName.empty())
  743. {
  744. // Note: module names not necessarily unique
  745. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  746. }
  747. CleanupFileInstances();
  748. delete mBfIRBuilder;
  749. mBfIRBuilder = NULL;
  750. //delete mCpu;
  751. for (auto prevModule : mPrevIRBuilders)
  752. delete prevModule;
  753. mPrevIRBuilders.Clear();
  754. for (auto& pairVal : mDeferredMethodCallData)
  755. delete pairVal.mValue;
  756. mDeferredMethodCallData.Clear();
  757. mDeferredMethodIds.Clear();
  758. for (auto& specModulePair : mSpecializedMethodModules)
  759. delete specModulePair.mValue;
  760. mSpecializedMethodModules.Clear();
  761. if (mNextAltModule != NULL)
  762. delete mNextAltModule;
  763. mNextAltModule = NULL;
  764. if (mModuleOptions != NULL)
  765. delete mModuleOptions;
  766. mModuleOptions = NULL;
  767. BfReportMemory();
  768. }
  769. void BfModule::Init(bool isFullRebuild)
  770. {
  771. mContext->mFinishedModuleWorkList.Remove(this);
  772. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  773. BF_ASSERT(mIsReified);
  774. if (!mIsScratchModule)
  775. {
  776. mCompiler->mStats.mModulesStarted++;
  777. if (mIsReified)
  778. mCompiler->mStats.mReifiedModuleCount++;
  779. mAddedToCount = true;
  780. }
  781. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  782. mFuncReferences.Clear();
  783. mClassVDataRefs.Clear();
  784. mClassVDataExtRefs.Clear();
  785. //mTypeDataRefs.Clear();
  786. mDbgRawAllocDataRefs.Clear();
  787. CleanupFileInstances();
  788. mStaticFieldRefs.Clear();
  789. //mInterfaceSlotRefs.Clear();
  790. // If we are just doing an extension then the ownede types aren't rebuilt.
  791. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  792. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  793. if (isFullRebuild)
  794. mRevision = mCompiler->mRevision;
  795. BF_ASSERT(mCurTypeInstance == NULL);
  796. mIsModuleMutable = true;
  797. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  798. #ifdef _DEBUG
  799. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  800. #else
  801. EnsureIRBuilder(false);
  802. #endif
  803. mCurMethodState = NULL;
  804. mAwaitingInitFinish = true;
  805. mOnDemandMethodCount = 0;
  806. mAwaitingFinish = false;
  807. mHasForceLinkMarker = false;
  808. mUsedSlotCount = -1;
  809. }
  810. bool BfModule::WantsFinishModule()
  811. {
  812. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  813. }
  814. void BfModule::FinishInit()
  815. {
  816. BF_ASSERT(mAwaitingInitFinish);
  817. auto moduleOptions = GetModuleOptions();
  818. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  819. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  820. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  821. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  822. {
  823. // Og+ requires debug info
  824. moduleOptions.mEmitDebugInfo = 1;
  825. }
  826. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  827. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  828. {
  829. mBfIRBuilder->DbgInit();
  830. }
  831. else
  832. mHasFullDebugInfo = false;
  833. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  834. ((moduleOptions.mEmitDebugInfo != 0)))
  835. {
  836. if (mCompiler->mOptions.IsCodeView())
  837. {
  838. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  839. }
  840. else
  841. {
  842. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  843. }
  844. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  845. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  846. }
  847. mAwaitingInitFinish = false;
  848. }
  849. void BfModule::ReifyModule()
  850. {
  851. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  852. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  853. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  854. mIsReified = true;
  855. mReifyQueued = false;
  856. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  857. mCompiler->mStats.mModulesReified++;
  858. }
  859. void BfModule::UnreifyModule()
  860. {
  861. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  862. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  863. mIsReified = false;
  864. mReifyQueued = false;
  865. StartNewRevision(RebuildKind_None, true);
  866. mCompiler->mStats.mModulesUnreified++;
  867. }
  868. void BfModule::CleanupFileInstances()
  869. {
  870. for (auto& itr : mNamedFileInstanceMap)
  871. {
  872. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  873. delete itr.mValue;
  874. }
  875. mCurFilePosition.mFileInstance = NULL;//
  876. mFileInstanceMap.Clear();
  877. mNamedFileInstanceMap.Clear();
  878. }
  879. void BfModule::Cleanup()
  880. {
  881. CleanupFileInstances();
  882. }
  883. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  884. {
  885. if (HasCompiledOutput())
  886. {
  887. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  888. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  889. {
  890. StartExtension();
  891. }
  892. }
  893. else
  894. {
  895. EnsureIRBuilder();
  896. }
  897. }
  898. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  899. {
  900. BF_ASSERT(!mIsDeleting);
  901. if (mBfIRBuilder == NULL)
  902. {
  903. if ((!mIsScratchModule) && (!mAddedToCount))
  904. {
  905. mCompiler->mStats.mModulesStarted++;
  906. mAddedToCount = true;
  907. }
  908. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  909. /*if (mCompiler->mIsResolveOnly)
  910. BF_ASSERT(mIsResolveOnly);*/
  911. mBfIRBuilder = new BfIRBuilder(this);
  912. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  913. if (mIsScratchModule)
  914. {
  915. mBfIRBuilder->mIgnoreWrites = true;
  916. BF_ASSERT(!dbgVerifyCodeGen);
  917. }
  918. #ifdef _DEBUG
  919. if (mCompiler->mIsResolveOnly)
  920. {
  921. // For "deep" verification testing
  922. /*if (!mIsSpecialModule)
  923. dbgVerifyCodeGen = true;*/
  924. // We only want to turn this off on smaller builds for testing
  925. mBfIRBuilder->mIgnoreWrites = true;
  926. if (dbgVerifyCodeGen)
  927. mBfIRBuilder->mIgnoreWrites = false;
  928. if (!mBfIRBuilder->mIgnoreWrites)
  929. {
  930. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  931. mBfIRBuilder->mDbgVerifyCodeGen = true;
  932. }
  933. }
  934. else if (!mIsReified)
  935. {
  936. mBfIRBuilder->mIgnoreWrites = true;
  937. }
  938. else
  939. {
  940. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  941. // code as we walk the AST
  942. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  943. if (
  944. (mModuleName == "-")
  945. //|| (mModuleName == "System_Internal")
  946. //|| (mModuleName == "vdata")
  947. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  948. )
  949. mBfIRBuilder->mDbgVerifyCodeGen = true;
  950. // Just for testing!
  951. //mBfIRBuilder->mIgnoreWrites = true;
  952. }
  953. #else
  954. if (mCompiler->mIsResolveOnly)
  955. {
  956. // Always ignore writes in resolveOnly for release builds
  957. mBfIRBuilder->mIgnoreWrites = true;
  958. }
  959. else
  960. {
  961. // Just for memory testing! This breaks everything.
  962. //mBfIRBuilder->mIgnoreWrites = true;
  963. // For "deep" verification testing
  964. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  965. }
  966. #endif
  967. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  968. }
  969. }
  970. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  971. {
  972. String name = "FORCELINKMOD_" + module->mModuleName;
  973. if (outName != NULL)
  974. *outName = name;
  975. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  976. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  977. }
  978. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  979. {
  980. BP_ZONE("BfModule::StartNewRevision");
  981. // The project MAY be deleted because disabling a project can cause types to be deleted which
  982. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  983. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  984. // Already on new revision?
  985. if ((mRevision == mCompiler->mRevision) && (!force))
  986. return;
  987. mHadBuildError = false;
  988. mHadBuildWarning = false;
  989. mExtensionCount = 0;
  990. mRevision = mCompiler->mRevision;
  991. mRebuildIdx++;
  992. ClearModuleData();
  993. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  994. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  995. mStringPoolRefs.Clear();
  996. mDllImportEntries.Clear();
  997. mImportFileNames.Clear();
  998. for (auto& pairVal : mDeferredMethodCallData)
  999. delete pairVal.mValue;
  1000. mDeferredMethodCallData.Clear();
  1001. mDeferredMethodIds.Clear();
  1002. mModuleRefs.Clear();
  1003. mOutFileNames.Clear();
  1004. mTypeDataRefs.Clear();
  1005. mInterfaceSlotRefs.Clear();
  1006. if (rebuildKind == BfModule::RebuildKind_None)
  1007. {
  1008. for (auto& specPair : mSpecializedMethodModules)
  1009. {
  1010. auto specModule = specPair.mValue;
  1011. if (specModule->mIsReified != mIsReified)
  1012. {
  1013. if (mIsReified)
  1014. specModule->ReifyModule();
  1015. else
  1016. specModule->UnreifyModule();
  1017. }
  1018. }
  1019. }
  1020. else
  1021. {
  1022. for (auto& specPair : mSpecializedMethodModules)
  1023. {
  1024. auto specModule = specPair.mValue;
  1025. delete specModule;
  1026. }
  1027. }
  1028. mSpecializedMethodModules.Clear();
  1029. delete mNextAltModule;
  1030. mNextAltModule = NULL;
  1031. BF_ASSERT(mModuleOptions == NULL);
  1032. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1033. bool needsTypePopulated = false;
  1034. int oldOnDemandCount = 0;
  1035. // We don't have to rebuild types in the unspecialized module because there is no
  1036. // data that's needed -- their method instances are all NULL and the module
  1037. // doesn't get included in the build
  1038. if (this != mContext->mScratchModule)
  1039. {
  1040. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1041. {
  1042. auto typeInst = mOwnedTypeInstances[typeIdx];
  1043. if (!typeInst->IsDeleting())
  1044. {
  1045. typeInst->mIsReified = mIsReified;
  1046. if (rebuildKind != BfModule::RebuildKind_None)
  1047. {
  1048. if (typeInst->IsOnDemand())
  1049. {
  1050. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1051. if (rebuildKind == BfModule::RebuildKind_All)
  1052. mContext->DeleteType(typeInst);
  1053. else
  1054. {
  1055. RebuildMethods(typeInst);
  1056. }
  1057. }
  1058. else
  1059. mContext->RebuildType(typeInst, false, false, false);
  1060. }
  1061. else
  1062. {
  1063. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1064. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1065. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1066. {
  1067. oldOnDemandCount++;
  1068. }
  1069. }
  1070. if (typeInst->IsDeleting())
  1071. typeIdx--;
  1072. }
  1073. }
  1074. }
  1075. if (!mIsDeleting)
  1076. Init();
  1077. mOnDemandMethodCount += oldOnDemandCount;
  1078. }
  1079. void BfModule::StartExtension()
  1080. {
  1081. BF_ASSERT(!mIsModuleMutable);
  1082. BfLogSysM("Extension started of module %p\n", this);
  1083. mExtensionCount++;
  1084. if (mBfIRBuilder != NULL)
  1085. mPrevIRBuilders.push_back(mBfIRBuilder);
  1086. mBfIRBuilder = NULL;
  1087. mWantsIRIgnoreWrites = false;
  1088. mFuncReferences.Clear();
  1089. mClassVDataRefs.Clear();
  1090. mClassVDataExtRefs.Clear();
  1091. for (auto& kv : mTypeDataRefs)
  1092. kv.mValue = BfIRValue();
  1093. mDbgRawAllocDataRefs.Clear();
  1094. mStringCharPtrPool.Clear();
  1095. mStringObjectPool.Clear();
  1096. mStaticFieldRefs.Clear();
  1097. for (auto& kv : mInterfaceSlotRefs)
  1098. kv.mValue = BfIRValue();
  1099. mDeferredMethodCallData.Clear();
  1100. mDeferredMethodIds.Clear();
  1101. DisownMethods();
  1102. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1103. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1104. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1105. Init(false);
  1106. if (!wasAwaitingInitFinish)
  1107. FinishInit();
  1108. mOnDemandMethodCount = prevOnDemandMethodCount;
  1109. }
  1110. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1111. {
  1112. BfIRValue vDataValue;
  1113. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1114. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1115. else
  1116. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1117. typeValueParams.push_back(vDataValue);
  1118. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1119. {
  1120. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1121. typeValueParams.push_back(GetDefaultValue(primType));
  1122. }
  1123. }
  1124. BfIRValue BfModule::GetConstValue(int64 val)
  1125. {
  1126. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1127. }
  1128. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1129. {
  1130. BfType* checkType = type;
  1131. if (type->IsTypedPrimitive())
  1132. {
  1133. checkType = type->GetUnderlyingType();
  1134. }
  1135. if (checkType->IsPrimitiveType())
  1136. {
  1137. auto primType = (BfPrimitiveType*)checkType;
  1138. if (checkType->IsFloat())
  1139. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1140. else
  1141. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1142. }
  1143. return BfIRValue();
  1144. }
  1145. BfIRValue BfModule::GetConstValue8(int val)
  1146. {
  1147. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1148. }
  1149. BfIRValue BfModule::GetConstValue32(int32 val)
  1150. {
  1151. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1152. }
  1153. BfIRValue BfModule::GetConstValue64(int64 val)
  1154. {
  1155. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1156. }
  1157. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1158. {
  1159. PopulateType(type, BfPopulateType_Data);
  1160. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1161. if (type->IsTypedPrimitive())
  1162. {
  1163. auto underlyingType = type->GetUnderlyingType();
  1164. if (underlyingType == NULL)
  1165. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1166. return GetDefaultValue(type->GetUnderlyingType());
  1167. }
  1168. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1169. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1170. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1171. if ((type->IsIntegral()) || (type->IsBoolean()))
  1172. {
  1173. auto primType = (BfPrimitiveType*)type;
  1174. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1175. }
  1176. if (type->IsFloat())
  1177. {
  1178. auto primType = (BfPrimitiveType*)type;
  1179. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1180. }
  1181. if (type->IsVoid())
  1182. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1183. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1184. }
  1185. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1186. {
  1187. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1188. if (type->mSize == 0)
  1189. return BfTypedValue(BfIRValue(), type);
  1190. else
  1191. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1192. }
  1193. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1194. {
  1195. PopulateType(type, BfPopulateType_Data);
  1196. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1197. if (defaultValueKind == BfDefaultValueKind_Undef)
  1198. {
  1199. auto primType = type->ToPrimitiveType();
  1200. if (primType != NULL)
  1201. {
  1202. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1203. }
  1204. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1205. }
  1206. BfTypedValue typedValue;
  1207. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1208. {
  1209. if (type->IsRef())
  1210. {
  1211. BfRefType* refType = (BfRefType*)type;
  1212. BfType* underlyingType = refType->GetUnderlyingType();
  1213. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1214. }
  1215. else
  1216. {
  1217. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1218. }
  1219. if (!mBfIRBuilder->mIgnoreWrites)
  1220. {
  1221. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1222. GetConstValue(type->mSize), type->mAlign);
  1223. }
  1224. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1225. typedValue = LoadValue(typedValue);
  1226. return typedValue;
  1227. }
  1228. if ((type->IsRef()) && (!allowRef))
  1229. {
  1230. BfRefType* refType = (BfRefType*)type;
  1231. BfType* underlyingType = refType->GetUnderlyingType();
  1232. if (underlyingType->IsValuelessType())
  1233. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1234. else
  1235. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1236. }
  1237. else
  1238. {
  1239. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1240. }
  1241. return typedValue;
  1242. }
  1243. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1244. {
  1245. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1246. BfIRType strCharType;
  1247. //
  1248. {
  1249. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1250. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1251. }
  1252. BfIRValue strConstant;
  1253. if (define)
  1254. {
  1255. strConstant = mBfIRBuilder->CreateConstString(str);
  1256. }
  1257. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1258. true, BfIRLinkageType_External,
  1259. strConstant, stringDataName);
  1260. if (define)
  1261. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1262. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1263. }
  1264. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1265. {
  1266. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1267. mBfIRBuilder->PopulateType(stringTypeInst);
  1268. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1269. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1270. BfIRValue stringValData;
  1271. if (define)
  1272. {
  1273. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1274. mStringCharPtrPool[stringId] = stringCharsVal;
  1275. SizedArray<BfIRValue, 8> typeValueParams;
  1276. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1277. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1278. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1279. typeValueParams.clear();
  1280. typeValueParams.push_back(objData);
  1281. if (lenByteCount == 4)
  1282. {
  1283. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1284. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1285. }
  1286. else
  1287. {
  1288. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1289. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1290. }
  1291. typeValueParams.push_back(stringCharsVal); // mPtr
  1292. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1293. }
  1294. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1295. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1296. true,
  1297. BfIRLinkageType_External,
  1298. define ? stringValData : BfIRValue(),
  1299. stringObjName);
  1300. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1301. return stringVal;
  1302. }
  1303. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1304. {
  1305. BF_ASSERT(constantStr.IsConst());
  1306. if (constHolder == NULL)
  1307. constHolder = mBfIRBuilder;
  1308. auto constant = constHolder->GetConstant(constantStr);
  1309. if (constant->mTypeCode == BfTypeCode_Int32)
  1310. {
  1311. return constant->mInt32;
  1312. }
  1313. while (constant->mConstType == BfConstType_BitCast)
  1314. {
  1315. auto constBitCast = (BfConstantBitCast*)constant;
  1316. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1317. }
  1318. if (constant->mConstType == BfConstType_GEP32_2)
  1319. {
  1320. auto constGEP = (BfConstantGEP32_2*)constant;
  1321. constant = constHolder->GetConstantById(constGEP->mTarget);
  1322. }
  1323. if (constant->mConstType == BfConstType_GlobalVar)
  1324. {
  1325. auto constGV = (BfGlobalVar*)constant;
  1326. const char* strDataPrefix = "__bfStrData";
  1327. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1328. return atoi(constGV->mName + strlen(strDataPrefix));
  1329. const char* strObjPrefix = "__bfStrObj";
  1330. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1331. return atoi(constGV->mName + strlen(strObjPrefix));
  1332. }
  1333. return -1;
  1334. }
  1335. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1336. {
  1337. int strId = GetStringPoolIdx(constantStr, constHolder);
  1338. if (strId != -1)
  1339. {
  1340. auto& entry = mContext->mStringObjectIdMap[strId];
  1341. return &entry.mString;
  1342. }
  1343. return NULL;
  1344. }
  1345. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1346. {
  1347. BfIRValue* irValue = NULL;
  1348. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1349. return *irValue;
  1350. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1351. if (!mStringObjectPool.ContainsKey(stringId))
  1352. mStringPoolRefs.Add(stringId);
  1353. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1354. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1355. *irValue = strCharPtrConst;
  1356. return strCharPtrConst;
  1357. }
  1358. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1359. {
  1360. if (strValue.IsConst())
  1361. {
  1362. int stringId = GetStringPoolIdx(strValue);
  1363. BF_ASSERT(stringId != -1);
  1364. return GetStringCharPtr(stringId);
  1365. }
  1366. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1367. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1368. return charPtr;
  1369. }
  1370. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1371. {
  1372. return GetStringCharPtr(GetStringObjectValue(str));
  1373. }
  1374. BfIRValue BfModule::GetStringObjectValue(int strId)
  1375. {
  1376. BfIRValue* objValue;
  1377. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1378. return *objValue;
  1379. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1380. return GetStringObjectValue(stringPoolEntry.mString, true);
  1381. }
  1382. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1383. {
  1384. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1385. mBfIRBuilder->PopulateType(stringType);
  1386. int strId = mContext->GetStringLiteralId(str);
  1387. BfIRValue* irValuePtr = NULL;
  1388. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1389. return *irValuePtr;
  1390. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1391. if (!mStringCharPtrPool.ContainsKey(strId))
  1392. mStringPoolRefs.Add(strId);
  1393. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1394. *irValuePtr = strObject;
  1395. mStringPoolRefs.Add(strId);
  1396. return strObject;
  1397. }
  1398. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1399. {
  1400. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1401. type,
  1402. true,
  1403. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1404. constant,
  1405. name.c_str());
  1406. return newConst;
  1407. }
  1408. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1409. {
  1410. auto curScope = mCurMethodState->mCurScope;
  1411. if (curScope->mLabelNode != NULL)
  1412. curScope->mLabelNode->ToString(curScope->mLabel);
  1413. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1414. {
  1415. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1416. while (checkScope != NULL)
  1417. {
  1418. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1419. {
  1420. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1421. if (errorNode != NULL)
  1422. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1423. break;
  1424. }
  1425. checkScope = checkScope->mPrevScope;
  1426. }
  1427. }
  1428. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1429. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1430. {
  1431. if (prevScope->mHadScopeValueRetain)
  1432. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1433. else
  1434. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1435. }
  1436. mCurMethodState->mBlockNestLevel++;
  1437. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1438. {
  1439. // DIScope could be NULL if we're in an unspecialized method (for example)
  1440. if (mCurMethodState->mCurScope->mDIScope)
  1441. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1442. }
  1443. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1444. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1445. }
  1446. void BfModule::RestoreScoreState_LocalVariables()
  1447. {
  1448. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1449. {
  1450. auto localVar = mCurMethodState->mLocals.back();
  1451. LocalVariableDone(localVar, false);
  1452. mCurMethodState->mLocals.pop_back();
  1453. if (localVar->mShadowedLocal != NULL)
  1454. {
  1455. BfLocalVarEntry* localVarEntryPtr;
  1456. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1457. {
  1458. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1459. }
  1460. }
  1461. else
  1462. {
  1463. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1464. }
  1465. delete localVar;
  1466. }
  1467. }
  1468. void BfModule::RestoreScopeState()
  1469. {
  1470. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1471. mCurMethodState->mBlockNestLevel--;
  1472. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1473. {
  1474. BfIRBlock afterEndBlock;
  1475. if (!mCurMethodState->mLeftBlockUncond)
  1476. {
  1477. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1478. mBfIRBuilder->CreateBr(afterEndBlock);
  1479. mBfIRBuilder->ClearDebugLocation_Last();
  1480. }
  1481. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1482. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1483. if (afterEndBlock)
  1484. {
  1485. mBfIRBuilder->AddBlock(afterEndBlock);
  1486. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1487. }
  1488. }
  1489. if (!mCurMethodState->mLeftBlockUncond)
  1490. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1491. RestoreScoreState_LocalVariables();
  1492. if (mCurMethodState->mCurScope->mValueScopeStart)
  1493. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1494. mCurMethodState->mCurScope = prevScopeData;
  1495. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1496. }
  1497. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1498. {
  1499. if (mBfIRBuilder->mIgnoreWrites)
  1500. return mBfIRBuilder->GetFakeVal();
  1501. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1502. mBfIRBuilder->PopulateType(type);
  1503. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1504. if (!mBfIRBuilder->mIgnoreWrites)
  1505. BF_ASSERT(!prevInsertBlock.IsFake());
  1506. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1507. BfIRValue allocaInst;
  1508. if (arraySize)
  1509. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1510. else
  1511. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1512. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1513. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1514. if (name != NULL)
  1515. mBfIRBuilder->SetName(allocaInst, name);
  1516. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1517. if ((addLifetime) && (WantsLifetimes()))
  1518. {
  1519. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1520. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1521. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1522. }
  1523. return allocaInst;
  1524. }
  1525. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1526. {
  1527. if (mBfIRBuilder->mIgnoreWrites)
  1528. return mBfIRBuilder->GetFakeVal();
  1529. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1530. mBfIRBuilder->PopulateType(typeInst);
  1531. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1532. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1533. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1534. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1535. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1536. if (name != NULL)
  1537. mBfIRBuilder->SetName(allocaInst, name);
  1538. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1539. if ((addLifetime) && (WantsLifetimes()))
  1540. {
  1541. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1542. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1543. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1544. }
  1545. return allocaInst;
  1546. }
  1547. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1548. {
  1549. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1550. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1551. /*if (mCurMethodState->mInHeadScope)
  1552. isScopeAlloc = true;*/
  1553. if (scopeData == NULL)
  1554. return;
  1555. auto checkBaseType = val.mType->ToTypeInstance();
  1556. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1557. {
  1558. bool hadDtorCall = false;
  1559. while (checkBaseType != NULL)
  1560. {
  1561. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1562. {
  1563. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1564. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1565. BfIRValue useVal = val.mValue;
  1566. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1567. if (isDynAlloc)
  1568. {
  1569. //
  1570. }
  1571. else if (condAlloca)
  1572. {
  1573. BF_ASSERT(!IsTargetingBeefBackend());
  1574. BF_ASSERT(!isDynAlloc);
  1575. auto valPtr = CreateAlloca(checkBaseType);
  1576. mBfIRBuilder->CreateStore(useVal, valPtr);
  1577. useVal = valPtr;
  1578. }
  1579. SizedArray<BfIRValue, 1> llvmArgs;
  1580. llvmArgs.push_back(useVal);
  1581. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1582. if (deferredCall != NULL)
  1583. {
  1584. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1585. if (condAlloca)
  1586. deferredCall->mArgsNeedLoad = true;
  1587. }
  1588. hadDtorCall = true;
  1589. break;
  1590. }
  1591. checkBaseType = checkBaseType->mBaseType;
  1592. }
  1593. return;
  1594. }
  1595. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1596. if (mayEscape)
  1597. {
  1598. // Is this worth it?
  1599. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1600. // {
  1601. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1602. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1603. // if (!isDyn)
  1604. // {
  1605. // int clearSize = val.mType->mSize;
  1606. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1607. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1608. // SizedArray<BfIRValue, 1> llvmArgs;
  1609. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1610. // llvmArgs.push_back(GetConstValue8(0xDD));
  1611. // llvmArgs.push_back(GetConstValue(clearSize));
  1612. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1613. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1614. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1615. // }
  1616. // else
  1617. // {
  1618. // const char* funcName = "SetDeleted1";
  1619. // if (val.mType->mSize >= 16)
  1620. // funcName = "SetDeleted16";
  1621. // else if (val.mType->mSize >= 8)
  1622. // funcName = "SetDeleted8";
  1623. // else if (val.mType->mSize >= 4)
  1624. // funcName = "SetDeleted4";
  1625. //
  1626. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1627. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1628. // SizedArray<BfIRValue, 1> llvmArgs;
  1629. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1630. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1631. // }
  1632. // }
  1633. }
  1634. }
  1635. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1636. {
  1637. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1638. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1639. return false;
  1640. auto checkTypeInstance = startTypeInstance;
  1641. while (checkTypeInstance != NULL)
  1642. {
  1643. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1644. {
  1645. if (fieldInstance.mMergedDataIdx != -1)
  1646. {
  1647. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1648. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1649. {
  1650. // For fields added in extensions, we automatically initialize those if necessary
  1651. auto fieldDef = fieldInstance.GetFieldDef();
  1652. if (!fieldDef->mDeclaringType->IsExtension())
  1653. return false;
  1654. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1655. {
  1656. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1657. mBfIRBuilder->SaveDebugLocation();
  1658. if (localVar->IsParam())
  1659. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1660. else
  1661. {
  1662. BF_ASSERT(localVar->mDeclBlock);
  1663. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1664. }
  1665. mBfIRBuilder->ClearDebugLocation();
  1666. BfIRValue curVal;
  1667. if (localVar->mIsThis)
  1668. curVal = mBfIRBuilder->GetArgument(0);
  1669. else
  1670. curVal = localVar->mAddr;
  1671. auto subTypeInstance = startTypeInstance;
  1672. while (subTypeInstance != checkTypeInstance)
  1673. {
  1674. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1675. subTypeInstance = subTypeInstance->mBaseType;
  1676. }
  1677. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1678. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1679. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1680. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1681. mBfIRBuilder->RestoreDebugLocation();
  1682. }
  1683. localVar->mUnassignedFieldFlags &= ~checkMask;
  1684. if (localVar->mUnassignedFieldFlags == 0)
  1685. localVar->mIsAssigned = true;
  1686. }
  1687. }
  1688. }
  1689. checkTypeInstance = checkTypeInstance->mBaseType;
  1690. }
  1691. return localVar->mIsAssigned;
  1692. }
  1693. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1694. {
  1695. //if (localVar->mAddr == NULL)
  1696. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1697. {
  1698. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1699. {
  1700. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1701. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1702. }
  1703. }*/
  1704. BfAstNode* localNameNode = localVar->mNameNode;
  1705. if (localVar->mIsThis)
  1706. {
  1707. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1708. }
  1709. if (localNameNode != NULL)
  1710. {
  1711. bool isOut = false;
  1712. if (localVar->mResolvedType->IsRef())
  1713. {
  1714. auto refType = (BfRefType*)localVar->mResolvedType;
  1715. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1716. }
  1717. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1718. {
  1719. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1720. TryLocalVariableInit(localVar);
  1721. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1722. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1723. //bool deferFullAnalysis = true;
  1724. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1725. if (!localVar->mIsAssigned)
  1726. {
  1727. if (deferUsageWarning)
  1728. {
  1729. // Ignore
  1730. }
  1731. else if (localVar->mIsThis)
  1732. {
  1733. bool foundFields = false;
  1734. auto checkTypeInstance = mCurTypeInstance;
  1735. while (checkTypeInstance != NULL)
  1736. {
  1737. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1738. {
  1739. if (fieldInstance.mMergedDataIdx != -1)
  1740. {
  1741. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1742. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1743. {
  1744. auto fieldDef = fieldInstance.GetFieldDef();
  1745. if (fieldDef->mProtection != BfProtection_Hidden)
  1746. {
  1747. if (checkTypeInstance == mCurTypeInstance)
  1748. {
  1749. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1750. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1751. }
  1752. else
  1753. {
  1754. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1755. TypeToString(checkTypeInstance).c_str(),
  1756. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1757. }
  1758. }
  1759. foundFields = true;
  1760. }
  1761. }
  1762. }
  1763. checkTypeInstance = checkTypeInstance->mBaseType;
  1764. }
  1765. if (!foundFields)
  1766. {
  1767. if (mCurTypeInstance->mInstSize > 0)
  1768. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1769. }
  1770. }
  1771. else if (localVar->IsParam())
  1772. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1773. else if (!deferUsageWarning)
  1774. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1775. }
  1776. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1777. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1778. }
  1779. }
  1780. }
  1781. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1782. {
  1783. auto checkScope = mCurMethodState->mCurScope;
  1784. while (true)
  1785. {
  1786. if (checkScope == scopeData)
  1787. break;
  1788. checkScope->mHadOuterDynStack = true;
  1789. checkScope = checkScope->mPrevScope;
  1790. }
  1791. }
  1792. void BfModule::SaveStackState(BfScopeData* scopeData)
  1793. {
  1794. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1795. // scopes within scopeData restore the stack
  1796. auto checkScope = mCurMethodState->mCurScope;
  1797. while (true)
  1798. {
  1799. if (checkScope == scopeData)
  1800. {
  1801. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1802. {
  1803. if (mBfIRBuilder->mHasDebugInfo)
  1804. mBfIRBuilder->SaveDebugLocation();
  1805. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1806. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1807. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1808. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1809. mBfIRBuilder->SetInsertPoint(prevPos);
  1810. if (mBfIRBuilder->mHasDebugInfo)
  1811. mBfIRBuilder->RestoreDebugLocation();
  1812. }
  1813. break;
  1814. }
  1815. if (checkScope->mSavedStack)
  1816. {
  1817. for (auto usage : checkScope->mSavedStackUses)
  1818. mBfIRBuilder->EraseInstFromParent(usage);
  1819. checkScope->mSavedStackUses.Clear();
  1820. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1821. checkScope->mSavedStack = BfIRValue();
  1822. }
  1823. checkScope = checkScope->mPrevScope;
  1824. }
  1825. }
  1826. BfIRValue BfModule::ValueScopeStart()
  1827. {
  1828. if (IsTargetingBeefBackend())
  1829. return mBfIRBuilder->CreateValueScopeStart();
  1830. return BfIRValue();
  1831. }
  1832. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1833. {
  1834. if (valueScopeStart)
  1835. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1836. }
  1837. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1838. {
  1839. auto bfParser = astNode->GetSourceData()->ToParserData();
  1840. if (bfParser == NULL)
  1841. return NULL;
  1842. BfFileInstance** fileInstancePtr = NULL;
  1843. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1844. {
  1845. return *fileInstancePtr;
  1846. }
  1847. else
  1848. {
  1849. // It's possible two parsers have the same file name (ie: mNextRevision)
  1850. BfFileInstance** namedFileInstancePtr = NULL;
  1851. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1852. {
  1853. auto bfFileInstance = *namedFileInstancePtr;
  1854. *fileInstancePtr = bfFileInstance;
  1855. return bfFileInstance;
  1856. }
  1857. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1858. auto bfFileInstance = new BfFileInstance();
  1859. *fileInstancePtr = bfFileInstance;
  1860. *namedFileInstancePtr = bfFileInstance;
  1861. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1862. bfFileInstance->mParser = bfParser;
  1863. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1864. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1865. {
  1866. String fileName = bfParser->mFileName;
  1867. for (int i = 0; i < (int)fileName.length(); i++)
  1868. {
  1869. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1870. fileName[i] = DIR_SEP_CHAR;
  1871. }
  1872. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1873. }
  1874. return bfFileInstance;
  1875. }
  1876. }
  1877. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1878. {
  1879. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1880. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1881. return;
  1882. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1883. if (astNode == NULL)
  1884. return;
  1885. auto bfParser = astNode->GetSourceData()->ToParserData();
  1886. if (bfParser == NULL)
  1887. return;
  1888. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1889. {
  1890. if (mCurFilePosition.mFileInstance != NULL)
  1891. {
  1892. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1893. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1894. }
  1895. auto bfFileInstance = GetFileFromNode(astNode);
  1896. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1897. {
  1898. mCurFilePosition = bfFileInstance->mPrevPosition;
  1899. }
  1900. else
  1901. {
  1902. mCurFilePosition.mFileInstance = bfFileInstance;
  1903. mCurFilePosition.mCurLine = 0;
  1904. mCurFilePosition.mCurSrcPos = 0;
  1905. }
  1906. }
  1907. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1908. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1909. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1910. if (jumpEntry->mCharIdx > srcPos)
  1911. jumpEntry--;
  1912. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1913. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1914. mCurFilePosition.mCurColumn = 0;
  1915. while (mCurFilePosition.mCurSrcPos < srcPos)
  1916. {
  1917. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1918. {
  1919. mCurFilePosition.mCurLine++;
  1920. mCurFilePosition.mCurColumn = 0;
  1921. }
  1922. else
  1923. {
  1924. mCurFilePosition.mCurColumn++;
  1925. }
  1926. mCurFilePosition.mCurSrcPos++;
  1927. }
  1928. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1929. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1930. {
  1931. int column = mCurFilePosition.mCurColumn + 1;
  1932. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1933. {
  1934. // Set to illegal position
  1935. column = 0;
  1936. }
  1937. if (mSetIllegalSrcPosition)
  1938. column = 0;
  1939. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1940. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1941. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1942. {
  1943. // This is from a different scope...
  1944. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1945. {
  1946. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1947. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1948. }
  1949. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1950. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1951. }
  1952. else
  1953. {
  1954. if (mCurMethodState->mCurScope->mAltDIFile)
  1955. {
  1956. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1957. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1958. }
  1959. }
  1960. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1961. if (mCurMethodState->mCrossingMixin)
  1962. inlineAt = BfIRMDNode();
  1963. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1964. if ((flags & BfSrcPosFlag_Expression) == 0)
  1965. mBfIRBuilder->CreateStatementStart();
  1966. }
  1967. }
  1968. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  1969. {
  1970. // We've turned off expr src pos (for now?)
  1971. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1972. }
  1973. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  1974. {
  1975. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  1976. }
  1977. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  1978. {
  1979. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1980. {
  1981. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  1982. {
  1983. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  1984. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1985. }
  1986. else
  1987. {
  1988. // Set to whatever it previously was but at column zero, which we will know to be illegal
  1989. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1990. }
  1991. if ((flags & BfSrcPosFlag_Expression) == 0)
  1992. mBfIRBuilder->CreateStatementStart();
  1993. }
  1994. }
  1995. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  1996. {
  1997. // We've turned off expr src pos (for now?)
  1998. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1999. }
  2000. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2001. {
  2002. if ((protection == BfProtection_Public) ||
  2003. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2004. ((protection == BfProtection_Private) && (allowPrivate)))
  2005. return true;
  2006. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2007. return true;
  2008. return false;
  2009. }
  2010. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2011. {
  2012. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2013. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2014. {
  2015. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2016. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2017. }
  2018. allowProtected = allowPrivate;
  2019. }
  2020. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2021. {
  2022. if (memberProtection == BfProtection_Hidden)
  2023. return false;
  2024. if (memberProtection == BfProtection_Public)
  2025. return true;
  2026. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2027. {
  2028. BfTypeInstance* curCheckType = mCurTypeInstance;
  2029. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2030. {
  2031. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2032. curCheckType = mixinOwner;
  2033. }
  2034. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2035. if (allowPrivate)
  2036. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2037. else
  2038. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2039. }
  2040. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2041. return true;
  2042. if (memberProtection == BfProtection_Protected)
  2043. {
  2044. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2045. {
  2046. bool allowProtected = false;
  2047. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2048. auto curCheckType = mCurTypeInstance;
  2049. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2050. {
  2051. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2052. curCheckType = mixinOwner;
  2053. }
  2054. auto lookupCheckType = lookupStartType;
  2055. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2056. {
  2057. if (lookupCheckType == curCheckType)
  2058. {
  2059. allowProtected = true;
  2060. break;
  2061. }
  2062. if (lookupCheckType == memberOwner)
  2063. break;
  2064. lookupCheckType = lookupCheckType->mBaseType;
  2065. if (lookupCheckType == NULL)
  2066. break;
  2067. }
  2068. if (!allowProtected)
  2069. {
  2070. // It's possible our outer type is derived from 'memberOwner'
  2071. while (curCheckType->mTypeDef->mNestDepth > 0)
  2072. {
  2073. curCheckType = GetOuterType(curCheckType);
  2074. if (curCheckType == NULL)
  2075. break;
  2076. auto lookupCheckType = lookupStartType;
  2077. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2078. {
  2079. if (lookupCheckType == curCheckType)
  2080. {
  2081. allowProtected = true;
  2082. break;
  2083. }
  2084. if (lookupCheckType == memberOwner)
  2085. break;
  2086. lookupCheckType = lookupCheckType->mBaseType;
  2087. if (lookupCheckType == NULL)
  2088. break;
  2089. }
  2090. }
  2091. }
  2092. if (allowProtected)
  2093. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2094. else
  2095. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2096. }
  2097. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2098. return true;
  2099. }
  2100. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2101. return true;
  2102. return false;
  2103. }
  2104. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2105. {
  2106. if ((mCompiler->mResolvePassData != NULL) &&
  2107. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2108. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2109. {
  2110. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2111. }
  2112. }
  2113. void BfModule::SetHadVarUsage()
  2114. {
  2115. mHadVarUsage = true;
  2116. mHadBuildError = true;
  2117. }
  2118. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2119. {
  2120. BP_ZONE("BfModule::Fail");
  2121. if (mIgnoreErrors)
  2122. {
  2123. mHadIgnoredError = true;
  2124. return NULL;
  2125. }
  2126. if (!mReportErrors)
  2127. {
  2128. mCompiler->mPassInstance->SilentFail();
  2129. return NULL;
  2130. }
  2131. if (refNode != NULL)
  2132. refNode = BfNodeToNonTemporary(refNode);
  2133. //BF_ASSERT(refNode != NULL);
  2134. if (mCurMethodInstance != NULL)
  2135. mCurMethodInstance->mHasFailed = true;
  2136. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2137. return NULL;
  2138. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2139. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2140. if (!mHadBuildError)
  2141. mHadBuildError = true;
  2142. if (mParentModule != NULL)
  2143. mParentModule->mHadBuildError = true;
  2144. if (mCurTypeInstance != NULL)
  2145. AddFailType(mCurTypeInstance);
  2146. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2147. String errorString = error;
  2148. bool isWhileSpecializing = false;
  2149. bool isWhileSpecializingMethod = false;
  2150. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2151. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2152. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2153. errorString += StrFormat("\n while generating append size calculating method");
  2154. else if (refNode == NULL)
  2155. {
  2156. if (mCurTypeInstance != NULL)
  2157. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2158. else if (mProject != NULL)
  2159. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2160. }
  2161. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2162. {
  2163. auto checkMethodState = mCurMethodState;
  2164. while (checkMethodState != NULL)
  2165. {
  2166. auto methodInstance = checkMethodState->mMethodInstance;
  2167. if (methodInstance == NULL)
  2168. {
  2169. checkMethodState = checkMethodState->mPrevMethodState;
  2170. continue;
  2171. }
  2172. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2173. methodInstance->mHasFailed = true;
  2174. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2175. if (isSpecializedMethod)
  2176. {
  2177. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2178. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2179. if (unspecializedMethod->mHasFailed)
  2180. return NULL; // At least SOME error has already been reported
  2181. }
  2182. if (isSpecializedMethod)
  2183. {
  2184. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2185. isWhileSpecializing = true;
  2186. isWhileSpecializingMethod = true;
  2187. }
  2188. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2189. {
  2190. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2191. isWhileSpecializing = true;
  2192. isWhileSpecializingMethod = true;
  2193. }
  2194. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2195. {
  2196. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2197. isWhileSpecializing = true;
  2198. }
  2199. checkMethodState = checkMethodState->mPrevMethodState;
  2200. }
  2201. // Keep in mind that all method specializations with generic type instances as its method generic params
  2202. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2203. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2204. // those method specializations if that occurs
  2205. if (isWhileSpecializing)
  2206. {
  2207. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2208. if (bfError != NULL)
  2209. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2210. return bfError;
  2211. }
  2212. }
  2213. if (!mHadBuildError)
  2214. mHadBuildError = true;
  2215. // Check mixins
  2216. {
  2217. auto checkMethodInstance = mCurMethodState;
  2218. while (checkMethodInstance != NULL)
  2219. {
  2220. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2221. if (rootMixinState != NULL)
  2222. {
  2223. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2224. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2225. auto mixinState = checkMethodInstance->mMixinState;
  2226. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2227. {
  2228. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2229. mixinState = mixinState->mPrevMixinState;
  2230. }
  2231. return bfError;
  2232. }
  2233. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2234. }
  2235. }
  2236. BfError* bfError = NULL;
  2237. if (refNode == NULL)
  2238. bfError = mCompiler->mPassInstance->Fail(errorString);
  2239. else
  2240. {
  2241. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2242. }
  2243. if (bfError != NULL)
  2244. {
  2245. bfError->mIsPersistent = isPersistent;
  2246. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2247. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2248. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2249. }
  2250. return bfError;
  2251. }
  2252. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2253. {
  2254. if (mIgnoreErrors)
  2255. return NULL;
  2256. if (refNode != NULL)
  2257. refNode = BfNodeToNonTemporary(refNode);
  2258. mHadBuildError = true;
  2259. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2260. }
  2261. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2262. {
  2263. if (mIgnoreErrors || mIgnoreWarnings)
  2264. return NULL;
  2265. if (!mReportErrors)
  2266. {
  2267. mCompiler->mPassInstance->SilentFail();
  2268. return NULL;
  2269. }
  2270. BfAstNode* unwarnNode = refNode;
  2271. //
  2272. {
  2273. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2274. while (parentNodeEntry != NULL)
  2275. {
  2276. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2277. break;
  2278. unwarnNode = parentNodeEntry->mNode;
  2279. parentNodeEntry = parentNodeEntry->mPrev;
  2280. }
  2281. }
  2282. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2283. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2284. {
  2285. return NULL;
  2286. }
  2287. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2288. if (mCurMethodInstance != NULL)
  2289. {
  2290. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2291. return NULL;
  2292. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2293. return NULL; // No ctorCalcAppend warnings
  2294. }
  2295. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2296. return NULL;
  2297. if (refNode != NULL)
  2298. refNode = BfNodeToNonTemporary(refNode);
  2299. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2300. {
  2301. // We used to bubble up warnings into the mixin injection site, BUT
  2302. // we are now assuming any relevant warnings will be given at the declaration site
  2303. return NULL;
  2304. // AddFailType(mCurTypeInstance);
  2305. //
  2306. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2307. // if (bfError == NULL)
  2308. // return NULL;
  2309. // mHadBuildWarning = true;
  2310. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2311. }
  2312. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2313. if (bfError != NULL)
  2314. {
  2315. AddFailType(mCurTypeInstance);
  2316. mHadBuildWarning = true;
  2317. bfError->mIsPersistent = isPersistent;
  2318. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2319. {
  2320. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2321. if (parser != NULL)
  2322. {
  2323. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2324. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2325. }
  2326. }
  2327. }
  2328. return bfError;
  2329. }
  2330. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2331. {
  2332. if (mBfIRBuilder->mOpFailed)
  2333. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2334. }
  2335. void BfModule::NotImpl(BfAstNode* astNode)
  2336. {
  2337. Fail("INTERNAL ERROR: Not implemented", astNode);
  2338. }
  2339. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2340. {
  2341. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2342. if (!allowPrivate)
  2343. allowPrivate |= memberType->IsInterface();
  2344. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2345. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2346. {
  2347. return false;
  2348. }
  2349. return true;
  2350. }
  2351. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2352. {
  2353. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2354. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2355. auto memberTypeInstance = memberType->ToTypeInstance();
  2356. if (memberTypeInstance == NULL)
  2357. {
  2358. auto underlyingType = memberType->GetUnderlyingType();
  2359. if (underlyingType != NULL)
  2360. return CheckDefineMemberProtection(protection, underlyingType);
  2361. return true;
  2362. }
  2363. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2364. return false;
  2365. if (memberTypeInstance->IsGenericTypeInstance())
  2366. {
  2367. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2368. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2369. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2370. {
  2371. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2372. return false;
  2373. }
  2374. }
  2375. return true;
  2376. }
  2377. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2378. {
  2379. if (usedType == usingType)
  2380. return;
  2381. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2382. return;
  2383. if (usedType->IsSpecializedByAutoCompleteMethod())
  2384. return;
  2385. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2386. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2387. {
  2388. bool addType = true;
  2389. auto checkType = usedType;
  2390. while (true)
  2391. {
  2392. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2393. checkType = checkType->GetUnderlyingType();
  2394. else if (checkType->IsArray())
  2395. {
  2396. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2397. }
  2398. else
  2399. break;
  2400. }
  2401. PopulateType(checkType, BfPopulateType_Data);
  2402. if (checkType->IsValuelessType())
  2403. addType = false;
  2404. else if (checkType->IsPrimitiveType())
  2405. addType = false;
  2406. else
  2407. {
  2408. auto checkTypeInst = checkType->ToTypeInstance();
  2409. if (checkTypeInst == NULL)
  2410. {
  2411. addType = false;
  2412. }
  2413. else
  2414. {
  2415. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2416. addType = false;
  2417. }
  2418. }
  2419. if (addType)
  2420. {
  2421. auto checkTypeInst = checkType->ToTypeInstance();
  2422. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2423. BF_ASSERT(hotTypeVersion != NULL);
  2424. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2425. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2426. (checkType->IsComposite()))
  2427. isAllocation = true;
  2428. if (isAllocation)
  2429. {
  2430. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2431. }
  2432. else
  2433. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2434. }
  2435. }
  2436. //BP_ZONE("BfModule::AddDependency");
  2437. /*if (usedType->IsMethodRef())
  2438. {
  2439. auto methodRefType = (BfMethodRefType*)usedType;
  2440. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2441. return;
  2442. }*/
  2443. // Why in the world were we doing this?
  2444. // This caused functions to get immediately deleted since they appear to have no references ever....
  2445. // if (usedType->IsFunction())
  2446. // {
  2447. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2448. // }
  2449. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2450. {
  2451. auto usingModule = usingType->GetModule();
  2452. BfModule* usedModule;
  2453. if (usedType->IsFunction())
  2454. {
  2455. auto typeInst = usedType->ToTypeInstance();
  2456. if (typeInst->mBaseType == NULL)
  2457. PopulateType(typeInst);
  2458. usedModule = typeInst->mBaseType->GetModule();
  2459. }
  2460. else
  2461. usedModule = usedType->GetModule();
  2462. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2463. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2464. {
  2465. usingModule->mModuleRefs.Add(usedModule);
  2466. }
  2467. }
  2468. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2469. {
  2470. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2471. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2472. if (genericArg == usedType)
  2473. return;
  2474. }
  2475. auto underlyingType = usedType->GetUnderlyingType();
  2476. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2477. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2478. BfDependedType* checkDType = usedType->ToDependedType();
  2479. if (checkDType == NULL)
  2480. return;
  2481. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2482. mContext->MarkAsReferenced(checkDType);
  2483. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2484. if (checkDType->IsGenericTypeInstance())
  2485. {
  2486. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2487. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2488. {
  2489. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2490. }
  2491. }
  2492. }
  2493. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2494. {
  2495. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2496. {
  2497. if (methodInstance->mHotMethod == NULL)
  2498. CheckHotMethod(methodInstance, "");
  2499. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2500. if (devirtualized)
  2501. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2502. else
  2503. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2504. }
  2505. }
  2506. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2507. {
  2508. auto checkTypeInst = typeInst;
  2509. while (checkTypeInst != NULL)
  2510. {
  2511. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2512. return true;
  2513. checkTypeInst = checkTypeInst->mBaseType;
  2514. }
  2515. return false;
  2516. }
  2517. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2518. {
  2519. if (mContext->mCurTypeState == NULL)
  2520. return;
  2521. BP_ZONE("PopulateGlobalContainersList");
  2522. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2523. if (userTypeDef == NULL)
  2524. userTypeDef = mCurTypeInstance->mTypeDef;
  2525. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2526. {
  2527. mContext->mCurTypeState->mGlobalContainers.Clear();
  2528. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2529. {
  2530. BfAtomComposite findStr;
  2531. if (namespaceIdx != -1)
  2532. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2533. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2534. while (typeDefItr)
  2535. {
  2536. auto typeDef = *typeDefItr;
  2537. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2538. {
  2539. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2540. {
  2541. BfGlobalContainerEntry globalEntry;
  2542. globalEntry.mTypeDef = typeDef;
  2543. globalEntry.mTypeInst = NULL;
  2544. typeDef->PopulateMemberSets();
  2545. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2546. }
  2547. }
  2548. else if (!typeDef->mIsPartial)
  2549. {
  2550. //break;
  2551. }
  2552. typeDefItr.MoveToNextHashMatch();
  2553. }
  2554. }
  2555. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2556. }
  2557. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2558. // reifing types
  2559. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2560. {
  2561. if (globalEntry.mTypeInst == NULL)
  2562. {
  2563. bool include = false;
  2564. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2565. include = true;
  2566. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2567. {
  2568. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2569. include = true;
  2570. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2571. include = true;
  2572. }
  2573. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2574. {
  2575. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2576. include = true;
  2577. }
  2578. if (include)
  2579. {
  2580. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2581. if (type != NULL)
  2582. globalEntry.mTypeInst = type->ToTypeInstance();
  2583. }
  2584. }
  2585. }
  2586. }
  2587. void PrintUsers(llvm::MDNode* md);
  2588. BfModuleOptions BfModule::GetModuleOptions()
  2589. {
  2590. if (mIsScratchModule)
  2591. return BfModuleOptions();
  2592. if (mModuleOptions != NULL)
  2593. return *mModuleOptions;
  2594. BfModuleOptions moduleOptions;
  2595. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2596. if (mProject != NULL)
  2597. {
  2598. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2599. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2600. }
  2601. auto headModule = this;
  2602. while (headModule->mParentModule != NULL)
  2603. headModule = headModule->mParentModule;
  2604. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2605. if (headModule->mOwnedTypeInstances.size() > 0)
  2606. {
  2607. auto typeInst = headModule->mOwnedTypeInstances[0];
  2608. PopulateType(typeInst);
  2609. if (typeInst->mTypeOptionsIdx != -1)
  2610. {
  2611. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2612. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2613. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2614. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2615. }
  2616. }
  2617. return moduleOptions;
  2618. }
  2619. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2620. {
  2621. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2622. auto typeOptions = GetTypeOptions();
  2623. if (typeOptions != NULL)
  2624. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2625. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2626. }
  2627. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2628. {
  2629. mContext->mFailTypes.Add(typeInstance);
  2630. }
  2631. void BfModule::CheckAddFailType()
  2632. {
  2633. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2634. // but we still need to add the owning type to the FailTypes list
  2635. //.. OLD:
  2636. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2637. /*if (mCurTypeInstance->mModule != this)
  2638. return;*/
  2639. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2640. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2641. // being recompiled. This forces types with warnings to be recompiled.
  2642. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2643. // constantly warning-aware
  2644. if ((mHadBuildError) ||
  2645. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2646. {
  2647. //mContext->mFailTypes.Add(mCurTypeInstance);
  2648. }
  2649. }
  2650. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2651. {
  2652. if (!mCompiler->IsHotCompile())
  2653. return;
  2654. typeInst->mDirty = true;
  2655. for (auto& dep : typeInst->mDependencyMap)
  2656. {
  2657. auto depType = dep.mKey;
  2658. auto depFlags = dep.mValue.mFlags;
  2659. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2660. {
  2661. MarkDerivedDirty(depType->ToTypeInstance());
  2662. }
  2663. }
  2664. }
  2665. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2666. {
  2667. auto fieldType = fieldInstance->GetResolvedType();
  2668. auto field = fieldInstance->GetFieldDef();
  2669. if (fieldType->IsVar())
  2670. return;
  2671. BfIRValue initValue;
  2672. if (field->mIsConst)
  2673. {
  2674. if (fieldType->IsPointer())
  2675. fieldType = fieldType->GetUnderlyingType();
  2676. }
  2677. if (!field->mIsExtern)
  2678. initValue = GetDefaultValue(fieldType);
  2679. if (fieldInstance->mOwner->IsUnspecializedType())
  2680. {
  2681. // Placeholder
  2682. auto ptrVal = CreatePointerType(fieldType);
  2683. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2684. }
  2685. else
  2686. {
  2687. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2688. StringT<128> staticVarName;
  2689. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2690. if (!fieldType->IsValuelessType())
  2691. {
  2692. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2693. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2694. false,
  2695. BfIRLinkageType_External,
  2696. initValue,
  2697. staticVarName,
  2698. isThreadLocal);
  2699. BF_ASSERT(globalVar);
  2700. mStaticFieldRefs[fieldInstance] = globalVar;
  2701. }
  2702. }
  2703. }
  2704. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2705. {
  2706. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2707. BfType* fieldType = NULL;
  2708. if (fieldInstance != NULL)
  2709. {
  2710. fieldType = fieldInstance->GetResolvedType();
  2711. if (fieldType == NULL)
  2712. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2713. }
  2714. else
  2715. {
  2716. BF_ASSERT(mCompiler->IsAutocomplete());
  2717. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2718. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2719. {
  2720. fieldType = typeInstance;
  2721. }
  2722. else
  2723. {
  2724. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2725. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2726. if (isLet || isVar)
  2727. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2728. else
  2729. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2730. if (fieldType == NULL)
  2731. fieldType = mContext->mBfObjectType;
  2732. }
  2733. }
  2734. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2735. return;
  2736. if (mContext->mFieldResolveReentrys.size() > 1)
  2737. {
  2738. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2739. {
  2740. String failStr = "Circular data reference detected between the following fields:";
  2741. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2742. {
  2743. if (i > 1)
  2744. failStr += ",";
  2745. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2746. }
  2747. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2748. if (err)
  2749. err->mIsPersistent = true;
  2750. return;
  2751. }
  2752. }
  2753. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2754. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2755. if (fieldInstance == NULL)
  2756. popTypeResolveReentry.Pop();
  2757. auto typeDef = typeInstance->mTypeDef;
  2758. BfIRValue constValue;
  2759. if (fieldDef->mIsExtern)
  2760. {
  2761. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2762. {
  2763. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2764. }
  2765. if (fieldDef->mInitializer != NULL)
  2766. {
  2767. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2768. }
  2769. }
  2770. else if (fieldDef->mInitializer == NULL)
  2771. {
  2772. if (fieldDef->IsEnumCaseEntry())
  2773. {
  2774. if (typeInstance->IsTypedPrimitive())
  2775. {
  2776. BfFieldInstance* prevFieldInstance = NULL;
  2777. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2778. {
  2779. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2780. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2781. {
  2782. prevFieldInstance = checkFieldInst;
  2783. break;
  2784. }
  2785. }
  2786. if (prevFieldInstance == NULL)
  2787. constValue = GetConstValue(0, typeInstance);
  2788. else
  2789. {
  2790. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2791. if (prevFieldInstance->mConstIdx == -1)
  2792. {
  2793. if (!mCompiler->IsAutocomplete())
  2794. AssertErrorState();
  2795. constValue = GetConstValue(0, typeInstance);
  2796. }
  2797. else
  2798. {
  2799. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2800. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2801. }
  2802. }
  2803. }
  2804. }
  2805. else
  2806. {
  2807. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2808. }
  2809. }
  2810. else
  2811. {
  2812. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2813. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2814. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2815. BfConstResolver constResolver(this);
  2816. BfMethodState methodState;
  2817. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2818. methodState.mTempKind = BfMethodState::TempKind_Static;
  2819. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2820. if (fieldType->IsVar())
  2821. {
  2822. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2823. if (!initValue)
  2824. {
  2825. AssertErrorState();
  2826. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2827. }
  2828. if (fieldInstance != NULL)
  2829. {
  2830. fieldInstance->mResolvedType = initValue.mType;
  2831. }
  2832. constValue = initValue.mValue;
  2833. }
  2834. else
  2835. {
  2836. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2837. constValue = uncastedInitValue.mValue;
  2838. }
  2839. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2840. }
  2841. if (fieldInstance != NULL)
  2842. {
  2843. fieldType = fieldInstance->GetResolvedType();
  2844. if ((fieldType == NULL) || (fieldType->IsVar()))
  2845. {
  2846. AssertErrorState();
  2847. // Default const type is 'int'
  2848. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2849. if (fieldInstance != NULL)
  2850. {
  2851. fieldInstance->mResolvedType = initValue.mType;
  2852. }
  2853. constValue = initValue.mValue;
  2854. }
  2855. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2856. {
  2857. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2858. CurrentAddToConstHolder(constValue);
  2859. fieldInstance->mConstIdx = constValue.mId;
  2860. }
  2861. }
  2862. }
  2863. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2864. {
  2865. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2866. auto fieldType = fieldInstance->GetResolvedType();
  2867. if ((field->mIsConst) && (!isDeclType))
  2868. {
  2869. ResolveConstField(typeInstance, fieldInstance, field);
  2870. return fieldInstance->GetResolvedType();
  2871. }
  2872. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2873. if (!fieldInstance->mIsInferredType)
  2874. return fieldType;
  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. SetHadVarUsage();
  2885. return GetPrimitiveType(BfTypeCode_Var);
  2886. }
  2887. bool hadInferenceCycle = false;
  2888. if (mContext->mFieldResolveReentrys.size() > 1)
  2889. {
  2890. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2891. {
  2892. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2893. {
  2894. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2895. auto fieldDef = fieldInst->GetFieldDef();
  2896. auto fieldOwner = fieldInst->mOwner;
  2897. auto fieldModule = fieldOwner->mModule;
  2898. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2899. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2900. }
  2901. SetHadVarUsage();
  2902. return GetPrimitiveType(BfTypeCode_Var);
  2903. }
  2904. }
  2905. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2906. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2907. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2908. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2909. if ((field->mInitializer == NULL) && (!isDeclType))
  2910. {
  2911. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2912. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2913. SetHadVarUsage();
  2914. return GetPrimitiveType(BfTypeCode_Var);
  2915. }
  2916. BfType* resolvedType = NULL;
  2917. if (!hadInferenceCycle)
  2918. {
  2919. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2920. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2921. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2922. BfMethodState methodState;
  2923. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2924. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2925. if (!staticOnly)
  2926. {
  2927. //BfLocalVariable localVar;
  2928. //methodState.mLocals.push_back(localVar);
  2929. }
  2930. if (isDeclType)
  2931. {
  2932. auto fieldDef = fieldInstance->GetFieldDef();
  2933. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2934. }
  2935. else
  2936. {
  2937. BfTypedValue valueFromExpr;
  2938. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2939. FixIntUnknown(valueFromExpr);
  2940. resolvedType = valueFromExpr.mType;
  2941. }
  2942. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2943. }
  2944. if (resolvedType == NULL)
  2945. return GetPrimitiveType(BfTypeCode_Var);
  2946. fieldInstance->SetResolvedType(resolvedType);
  2947. if (field->mIsStatic)
  2948. {
  2949. }
  2950. else if (fieldInstance->mDataIdx <= 0)
  2951. {
  2952. }
  2953. else
  2954. {
  2955. BF_ASSERT(typeInstance->IsIncomplete());
  2956. }
  2957. return resolvedType;
  2958. }
  2959. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2960. {
  2961. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2962. auto fieldType = fieldInstance->GetResolvedType();
  2963. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2964. {
  2965. int fieldDataCount = 1;
  2966. if (fieldType->IsStruct())
  2967. {
  2968. auto structTypeInst = fieldType->ToTypeInstance();
  2969. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2970. }
  2971. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2972. auto thisVariable = GetThisVariable();
  2973. if (thisVariable != NULL)
  2974. {
  2975. for (int i = 0; i < fieldDataCount; i++)
  2976. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2977. }
  2978. }
  2979. }
  2980. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2981. {
  2982. if (fieldInstance->mCustomAttributes == NULL)
  2983. return false;
  2984. auto fieldDef = fieldInstance->GetFieldDef();
  2985. if (!fieldDef->mIsStatic)
  2986. return false;
  2987. bool isThreadLocal = false;
  2988. if (fieldInstance->mCustomAttributes != NULL)
  2989. {
  2990. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2991. {
  2992. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  2993. return true;
  2994. }
  2995. }
  2996. return false;
  2997. }
  2998. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  2999. {
  3000. if (fieldDef == NULL)
  3001. fieldDef = fieldInstance->GetFieldDef();
  3002. if (fieldType == NULL)
  3003. fieldType = fieldInstance->GetResolvedType();
  3004. if (initializer == NULL)
  3005. {
  3006. if (fieldDef == NULL)
  3007. return BfTypedValue();
  3008. initializer = fieldDef->mInitializer;
  3009. }
  3010. BfTypedValue result;
  3011. if (initializer == NULL)
  3012. {
  3013. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3014. }
  3015. else
  3016. {
  3017. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3018. {
  3019. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3020. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3021. }
  3022. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3023. {
  3024. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3025. BfConstResolver constResolver(this);
  3026. constResolver.Resolve(initializer);
  3027. return GetDefaultTypedValue(fieldType);
  3028. }
  3029. else if (fieldDef->mIsConst)
  3030. {
  3031. BfTypeState typeState;
  3032. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3033. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3034. BfConstResolver constResolver(this);
  3035. if (fieldType->IsVar())
  3036. return constResolver.Resolve(initializer);
  3037. else
  3038. return constResolver.Resolve(initializer, fieldType);
  3039. }
  3040. if (fieldType->IsVar())
  3041. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3042. else
  3043. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3044. }
  3045. if (fieldInstance != NULL)
  3046. MarkFieldInitialized(fieldInstance);
  3047. return result;
  3048. }
  3049. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3050. {
  3051. }
  3052. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3053. {
  3054. PopulateType(classType);
  3055. if (isInterfacePass)
  3056. {
  3057. for (auto ifaceInst : classType->mInterfaces)
  3058. {
  3059. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3060. continue;
  3061. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3062. continue;
  3063. if (ifaceInst.mDeclaringType->IsExtension())
  3064. {
  3065. bool needsExCheck = false;
  3066. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3067. {
  3068. exChecks->push_back(ifaceInst.mInterfaceType);
  3069. continue;
  3070. }
  3071. }
  3072. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3073. }
  3074. }
  3075. else
  3076. {
  3077. outVals->push_back(classType->mTypeId);
  3078. }
  3079. if (classType->mBaseType != NULL)
  3080. {
  3081. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3082. }
  3083. }
  3084. void BfModule::CreateDynamicCastMethod()
  3085. {
  3086. auto objType = mContext->mBfObjectType;
  3087. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3088. {
  3089. // The main reason to punt on this method for ResolveOnly is because types can be created
  3090. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3091. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3092. // remove this punt when we recycle typeId's
  3093. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3094. mCurMethodState->mHadReturn = true;
  3095. return;
  3096. }
  3097. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3098. auto func = mCurMethodState->mIRFunction;
  3099. auto thisValue = mBfIRBuilder->GetArgument(0);
  3100. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3101. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3102. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3103. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3104. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3105. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3106. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3107. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3108. SizedArray<int, 8> typeMatches;
  3109. SizedArray<BfTypeInstance*, 8> exChecks;
  3110. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3111. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3112. {
  3113. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3114. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3115. BfTypeVector genericArgs;
  3116. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3117. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3118. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3119. typeMatches.push_back(unboundType->mTypeId);
  3120. }
  3121. if (mCurTypeInstance->IsBoxed())
  3122. {
  3123. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3124. BfTypeInstance* innerType = boxedType->mElementType;
  3125. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3126. if (innerType->IsTypedPrimitive())
  3127. {
  3128. auto underlyingType = innerType->GetUnderlyingType();
  3129. typeMatches.push_back(underlyingType->mTypeId);
  3130. }
  3131. auto innerTypeInst = innerType->ToTypeInstance();
  3132. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3133. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3134. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3135. {
  3136. PopulateType(innerTypeInst);
  3137. //TODO: What case was this supposed to handle?
  3138. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3139. }
  3140. }
  3141. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3142. BfIRValue vDataPtr;
  3143. if (!exChecks.empty())
  3144. {
  3145. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3146. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3147. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3148. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3149. }
  3150. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3151. for (auto typeMatch : typeMatches)
  3152. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3153. Array<BfIRValue> incomingFalses;
  3154. for (auto ifaceTypeInst : exChecks)
  3155. {
  3156. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3157. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3158. mBfIRBuilder->SetInsertPoint(nextBB);
  3159. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3160. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3161. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3162. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3163. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3164. incomingFalses.push_back(nextBB);
  3165. }
  3166. mBfIRBuilder->AddBlock(trueBB);
  3167. mBfIRBuilder->SetInsertPoint(trueBB);
  3168. mBfIRBuilder->CreateBr(exitBB);
  3169. mBfIRBuilder->AddBlock(exitBB);
  3170. mBfIRBuilder->SetInsertPoint(exitBB);
  3171. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3172. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3173. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3174. for (auto incomingFalseBlock : incomingFalses)
  3175. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3176. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3177. mBfIRBuilder->CreateRet(phi);
  3178. mCurMethodState->mHadReturn = true;
  3179. }
  3180. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3181. {
  3182. BfExprEvaluator exprEvaluator(this);
  3183. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3184. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3185. BfTypedValue result = exprEvaluator.GetResult();
  3186. if (result)
  3187. {
  3188. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3189. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3190. mBfIRBuilder->AddBlock(nextBB);
  3191. mBfIRBuilder->SetInsertPoint(nextBB);
  3192. }
  3193. }
  3194. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3195. {
  3196. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3197. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3198. SizedArray<BfIRType, 4> paramTypes;
  3199. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3200. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3201. mBfIRBuilder->SetActiveFunction(func);
  3202. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3203. mBfIRBuilder->SetInsertPoint(entryBlock);
  3204. SizedArray<BfIRValue, 8> args;
  3205. BfExprEvaluator exprEvaluator(this);
  3206. if (mCurMethodInstance->HasThis())
  3207. {
  3208. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3209. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3210. }
  3211. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3212. {
  3213. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3214. if (paramType->IsValuelessType())
  3215. continue;
  3216. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3217. }
  3218. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3219. mBfIRBuilder->CreateRetVoid();
  3220. }
  3221. void BfModule::CreateValueTypeEqualsMethod()
  3222. {
  3223. if (mCurMethodInstance->mIsUnspecialized)
  3224. return;
  3225. if (mCurTypeInstance->IsTypedPrimitive())
  3226. return;
  3227. if (mBfIRBuilder->mIgnoreWrites)
  3228. return;
  3229. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3230. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3231. bool isValid = true;
  3232. auto compareDType = compareType->ToDependedType();
  3233. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3234. if (compareTypeInst != NULL)
  3235. {
  3236. if (compareType->IsPrimitiveType())
  3237. compareTypeInst = GetWrappedStructType(compareType);
  3238. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3239. {
  3240. isValid = false;
  3241. }
  3242. mBfIRBuilder->PopulateType(compareTypeInst);
  3243. }
  3244. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3245. if (!isValid)
  3246. {
  3247. ClearLifetimeEnds();
  3248. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3249. return;
  3250. }
  3251. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3252. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3253. if (refNode == NULL)
  3254. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3255. UpdateSrcPos(refNode);
  3256. SetIllegalSrcPos();
  3257. auto resultVal = CreateAlloca(boolType);
  3258. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3259. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3260. if (compareType->IsSizedArray())
  3261. {
  3262. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3263. if (sizedArrayType->mElementCount > 6)
  3264. {
  3265. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3266. auto itr = CreateAlloca(intPtrType);
  3267. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3268. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3269. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3270. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3271. mBfIRBuilder->CreateBr(loopBB);
  3272. mBfIRBuilder->SetInsertPoint(loopBB);
  3273. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3274. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3275. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3276. mBfIRBuilder->SetInsertPoint(bodyBB);
  3277. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3278. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3279. EmitEquals(leftValue, rightValue, exitBB);
  3280. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3281. mBfIRBuilder->CreateStore(incValue, itr);
  3282. mBfIRBuilder->CreateBr(loopBB);
  3283. mBfIRBuilder->SetInsertPoint(doneBB);
  3284. }
  3285. else
  3286. {
  3287. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3288. {
  3289. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3290. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3291. EmitEquals(leftValue, rightValue, exitBB);
  3292. }
  3293. }
  3294. }
  3295. else if (compareType->IsMethodRef())
  3296. {
  3297. auto methodRefType = (BfMethodRefType*)compareType;
  3298. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3299. BfExprEvaluator exprEvaluator(this);
  3300. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3301. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3302. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3303. // values for the same method reference -- they will always refer back to the same local variables.
  3304. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3305. if (dataIdx != -1)
  3306. {
  3307. bool failed = false;
  3308. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3309. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3310. BF_ASSERT(!failed);
  3311. EmitEquals(leftValue, rightValue, exitBB);
  3312. }
  3313. }
  3314. else if (compareTypeInst->IsEnum())
  3315. {
  3316. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3317. BfExprEvaluator exprEvaluator(this);
  3318. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3319. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3320. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3321. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3322. leftValue = LoadValue(leftValue);
  3323. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3324. rightValue = LoadValue(rightValue);
  3325. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3326. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3327. EmitEquals(leftValue, rightValue, exitBB);
  3328. int enumCount = 0;
  3329. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3330. {
  3331. BfFieldInstance* fieldInstance = &fieldRef;
  3332. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3333. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3334. {
  3335. enumCount = -fieldInstance->mDataIdx;
  3336. }
  3337. }
  3338. if (enumCount > 0)
  3339. {
  3340. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3341. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3342. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3343. {
  3344. BfFieldInstance* fieldInstance = &fieldRef;
  3345. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3346. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3347. {
  3348. int enumIdx = -fieldInstance->mDataIdx - 1;
  3349. if (fieldInstance->mResolvedType->mSize == 0)
  3350. {
  3351. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3352. }
  3353. else
  3354. {
  3355. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3356. mBfIRBuilder->SetInsertPoint(caseBlock);
  3357. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3358. BfTypedValue leftTuple;
  3359. BfTypedValue rightTuple;
  3360. if (leftPayload.IsAddr())
  3361. {
  3362. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3363. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3364. }
  3365. else
  3366. {
  3367. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3368. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3369. }
  3370. EmitEquals(leftTuple, rightTuple, exitBB);
  3371. mBfIRBuilder->CreateBr(matchedBlock);
  3372. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3373. }
  3374. }
  3375. }
  3376. mBfIRBuilder->AddBlock(matchedBlock);
  3377. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3378. }
  3379. }
  3380. else if (compareTypeInst->IsUnion())
  3381. {
  3382. auto innerType = compareTypeInst->GetUnionInnerType();
  3383. if (!innerType->IsValuelessType())
  3384. {
  3385. BfExprEvaluator exprEvaluator(this);
  3386. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3387. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3388. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3389. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3390. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3391. }
  3392. }
  3393. else
  3394. {
  3395. BfExprEvaluator exprEvaluator(this);
  3396. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3397. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3398. bool hadComparison = false;
  3399. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3400. {
  3401. BfFieldInstance* fieldInstance = &fieldRef;
  3402. if (fieldInstance->mDataOffset == -1)
  3403. continue;
  3404. if (fieldInstance->mResolvedType->IsValuelessType())
  3405. continue;
  3406. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3407. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3408. if (!fieldInstance->mResolvedType->IsComposite())
  3409. {
  3410. leftValue = LoadValue(leftValue);
  3411. rightValue = LoadValue(rightValue);
  3412. }
  3413. EmitEquals(leftValue, rightValue, exitBB);
  3414. }
  3415. auto baseTypeInst = compareTypeInst->mBaseType;
  3416. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3417. {
  3418. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3419. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3420. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3421. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3422. EmitEquals(leftValue, rightValue, exitBB);
  3423. }
  3424. }
  3425. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3426. mBfIRBuilder->CreateBr(exitBB);
  3427. mBfIRBuilder->AddBlock(exitBB);
  3428. mBfIRBuilder->SetInsertPoint(exitBB);
  3429. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3430. ClearLifetimeEnds();
  3431. mBfIRBuilder->CreateRet(loadedResult);
  3432. mCurMethodState->mHadReturn = true;
  3433. }
  3434. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3435. {
  3436. if (mBfIRBuilder->mIgnoreWrites)
  3437. return mBfIRBuilder->GetFakeVal();
  3438. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3439. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3440. BfIRValue* globalVariablePtr = NULL;
  3441. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3442. int numElements = 1;
  3443. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3444. {
  3445. numElements += mCompiler->mMaxInterfaceSlots;
  3446. auto maxIFaceVirtIdx = 0;
  3447. if (!typeInstance->IsInterface())
  3448. {
  3449. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3450. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3451. numElements += typeInstance->GetOrigVTableSize();
  3452. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3453. if (typeInstance->mHotTypeData != NULL)
  3454. {
  3455. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3456. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3457. }
  3458. numElements += ifaceMethodLen;
  3459. }
  3460. if (outNumElements != NULL)
  3461. *outNumElements = numElements;
  3462. }
  3463. StringT<128> classVDataName;
  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);
  3627. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3628. if (typeInstanceType == NULL)
  3629. {
  3630. AssertErrorState();
  3631. return BfIRValue();
  3632. }
  3633. BfIRValue typeTypeData;
  3634. int typeFlags = 0;
  3635. if (needsTypeData)
  3636. {
  3637. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3638. BfTypeInstance* typeDataSource = NULL;
  3639. if (typeInstance != NULL)
  3640. {
  3641. if (typeInstance->IsUnspecializedType())
  3642. {
  3643. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3644. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3645. }
  3646. else if (typeInstance->IsArray())
  3647. {
  3648. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3649. typeFlags |= BfTypeFlags_Array;
  3650. }
  3651. else if (typeInstance->IsGenericTypeInstance())
  3652. {
  3653. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3654. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3655. }
  3656. else
  3657. typeDataSource = typeInstanceTypeInstance;
  3658. }
  3659. else if (type->IsPointer())
  3660. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3661. else if (type->IsSizedArray())
  3662. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3663. else
  3664. typeDataSource = mContext->mBfTypeType;
  3665. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3666. {
  3667. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3668. }
  3669. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3670. }
  3671. else
  3672. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3673. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3674. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3675. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3676. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3677. BfType* typeIdType = intType;
  3678. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3679. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3680. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3681. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3682. SizedArray<BfIRValue, 4> typeValueParams;
  3683. GetConstClassValueParam(typeTypeData, typeValueParams);
  3684. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3685. StringT<128> typeDataName;
  3686. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3687. {
  3688. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3689. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3690. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  3691. }
  3692. else
  3693. {
  3694. typeDataName += "sBfTypeData.";
  3695. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  3696. }
  3697. int typeCode = BfTypeCode_None;
  3698. if (typeInstance != NULL)
  3699. {
  3700. typeCode = typeInstance->mTypeDef->mTypeCode;
  3701. }
  3702. else if (type->IsPrimitiveType())
  3703. {
  3704. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3705. typeCode = primType->mTypeDef->mTypeCode;
  3706. }
  3707. else if (type->IsPointer())
  3708. {
  3709. typeCode = BfTypeCode_Pointer;
  3710. typeFlags |= BfTypeFlags_Pointer;
  3711. }
  3712. if (type->IsObject())
  3713. {
  3714. typeFlags |= BfTypeFlags_Object;
  3715. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3716. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3717. typeFlags |= BfTypeFlags_HasDestructor;
  3718. }
  3719. if (type->IsStruct())
  3720. typeFlags |= BfTypeFlags_Struct;
  3721. if (type->IsBoxed())
  3722. {
  3723. typeFlags |= BfTypeFlags_Boxed;
  3724. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3725. typeFlags |= BfTypeFlags_Pointer;
  3726. }
  3727. if (type->IsPrimitiveType())
  3728. typeFlags |= BfTypeFlags_Primitive;
  3729. if (type->IsTypedPrimitive())
  3730. typeFlags |= BfTypeFlags_TypedPrimitive;
  3731. if (type->IsTuple())
  3732. typeFlags |= BfTypeFlags_Tuple;
  3733. if (type->IsNullable())
  3734. typeFlags |= BfTypeFlags_Nullable;
  3735. if (type->IsSizedArray())
  3736. typeFlags |= BfTypeFlags_SizedArray;
  3737. if (type->IsSplattable())
  3738. typeFlags |= BfTypeFlags_Splattable;
  3739. if (type->IsUnion())
  3740. typeFlags |= BfTypeFlags_Union;
  3741. if (type->IsDelegate())
  3742. typeFlags |= BfTypeFlags_Delegate;
  3743. if (type->WantsGCMarking())
  3744. typeFlags |= BfTypeFlags_WantsMarking;
  3745. int memberDataOffset = 0;
  3746. if (typeInstance != NULL)
  3747. {
  3748. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3749. {
  3750. if (fieldInstance.mDataOffset != -1)
  3751. {
  3752. memberDataOffset = fieldInstance.mDataOffset;
  3753. break;
  3754. }
  3755. }
  3756. }
  3757. SizedArray<BfIRValue, 8> typeDataParams =
  3758. {
  3759. objectData,
  3760. GetConstValue(type->mSize, intType), // mSize
  3761. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3762. GetConstValue(typeFlags, intType), // mTypeFlags
  3763. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3764. GetConstValue(typeCode, byteType), // mTypeCode
  3765. GetConstValue(type->mAlign, byteType),
  3766. };
  3767. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3768. if (typeInstance == NULL)
  3769. {
  3770. BfIRValue typeDataVar;
  3771. if (needsTypeData)
  3772. {
  3773. if (type->IsPointer())
  3774. {
  3775. auto pointerType = (BfPointerType*)type;
  3776. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3777. {
  3778. typeData,
  3779. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3780. };
  3781. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3782. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3783. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3784. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3785. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3786. }
  3787. else if (type->IsSizedArray())
  3788. {
  3789. auto sizedArrayType = (BfSizedArrayType*)type;
  3790. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3791. {
  3792. typeData,
  3793. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3794. GetConstValue(sizedArrayType->mElementCount, intType)
  3795. };
  3796. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3797. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3798. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3799. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3800. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3801. }
  3802. else
  3803. {
  3804. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3805. BfIRLinkageType_External, typeData, typeDataName);
  3806. }
  3807. }
  3808. else
  3809. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3810. mTypeDataRefs[typeInstance] = typeDataVar;
  3811. return typeDataVar;
  3812. }
  3813. // Reserve position
  3814. mTypeDataRefs[typeInstance] = BfIRValue();
  3815. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3816. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3817. StringT<128> mangledName;
  3818. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  3819. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3820. {
  3821. auto methodDef = typeDef->mMethods[methodIdx];
  3822. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3823. if (methodInstance == NULL)
  3824. continue;
  3825. if (typeInstance->IsUnspecializedType())
  3826. continue;
  3827. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3828. {
  3829. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3830. {
  3831. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3832. // We need to create an empty thunk for this chained method
  3833. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3834. mBfIRBuilder->SetActiveFunction(func);
  3835. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3836. mBfIRBuilder->SetInsertPoint(block);
  3837. mBfIRBuilder->CreateRetVoid();
  3838. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3839. }
  3840. }
  3841. }
  3842. SizedArray<BfIRValue, 32> vData;
  3843. BfIRValue classVDataVar;
  3844. String classVDataName;
  3845. if (typeInstance->mSlotNum >= 0)
  3846. {
  3847. // For interfaces we ONLY emit the slot num
  3848. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3849. StringT<128> slotVarName;
  3850. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3851. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3852. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3853. GetConstValue32(virtSlotIdx), slotVarName);
  3854. }
  3855. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3856. {
  3857. int dynCastDataElems = 0;
  3858. int numElements = 1;
  3859. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3860. numElements += mCompiler->mMaxInterfaceSlots;
  3861. if (!typeInstance->IsInterface())
  3862. {
  3863. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3864. numElements += mCompiler->GetDynCastVDataCount();
  3865. numElements += typeInstance->mVirtualMethodTableSize;
  3866. }
  3867. int expectNumElements = 0;
  3868. if (!typeDef->mIsStatic)
  3869. {
  3870. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3871. }
  3872. vData.push_back(BfIRValue()); // Type*
  3873. SizedArray<BfIRValue, 1> extVTableData;
  3874. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3875. if (!typeInstance->IsInterface())
  3876. {
  3877. Array<int32> dynCastData;
  3878. if (typeInstance->IsBoxed())
  3879. {
  3880. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3881. dynCastData.Add(underlyingType->mInheritanceId);
  3882. }
  3883. else
  3884. dynCastData.Add(typeInstance->mInheritanceId);
  3885. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3886. dynCastData.Add(0);
  3887. dynCastData.Add(0);
  3888. auto checkTypeInst = typeInstance;
  3889. while (checkTypeInst != NULL)
  3890. {
  3891. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3892. {
  3893. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3894. {
  3895. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3896. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3897. }
  3898. }
  3899. checkTypeInst = checkTypeInst->GetImplBaseType();
  3900. }
  3901. if (mSystem->mPtrSize == 8)
  3902. {
  3903. int intPtrCount = (dynCastDataElems + 1) / 2;
  3904. vDataOfs += intPtrCount;
  3905. uint64* intPtrData = (uint64*)&dynCastData[0];
  3906. for (int i = 0; i < intPtrCount; i++)
  3907. {
  3908. uint64 val = intPtrData[i];
  3909. if (val == 0)
  3910. {
  3911. vData.push_back(voidPtrNull);
  3912. }
  3913. else
  3914. {
  3915. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3916. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3917. }
  3918. }
  3919. }
  3920. else
  3921. {
  3922. int intPtrCount = dynCastDataElems;
  3923. vDataOfs += intPtrCount;
  3924. uint32* intPtrData = (uint32*)&dynCastData[0];
  3925. for (int i = 0; i < intPtrCount; i++)
  3926. {
  3927. uint32 val = intPtrData[i];
  3928. if (val == 0)
  3929. {
  3930. vData.push_back(voidPtrNull);
  3931. }
  3932. else
  3933. {
  3934. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3935. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3936. }
  3937. }
  3938. }
  3939. }
  3940. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3941. vData.push_back(voidPtrNull);
  3942. struct _InterfaceMatchEntry
  3943. {
  3944. BfTypeInterfaceEntry* mEntry;
  3945. BfTypeInstance* mEntrySource;
  3946. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3947. };
  3948. int highestIFaceVirtIdx = 0;
  3949. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3950. auto checkTypeInst = typeInstance;
  3951. bool forceInterfaceSet = false;
  3952. while (checkTypeInst != NULL)
  3953. {
  3954. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3955. {
  3956. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3957. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3958. continue;
  3959. _InterfaceMatchEntry* matchEntry = NULL;
  3960. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3961. {
  3962. auto prevEntry = matchEntry->mEntry;
  3963. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3964. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3965. if (forceInterfaceSet)
  3966. {
  3967. isBetter = true;
  3968. isWorse = false;
  3969. }
  3970. if (isBetter == isWorse)
  3971. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3972. if (isBetter == isWorse)
  3973. {
  3974. if (matchEntry->mAmbiguousEntries.empty())
  3975. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3976. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3977. continue;
  3978. }
  3979. else if (isBetter)
  3980. {
  3981. matchEntry->mEntry = &interfaceEntry;
  3982. matchEntry->mEntrySource = checkTypeInst;
  3983. matchEntry->mAmbiguousEntries.Clear();
  3984. }
  3985. else
  3986. continue;
  3987. }
  3988. else
  3989. {
  3990. _InterfaceMatchEntry matchEntry;
  3991. matchEntry.mEntry = &interfaceEntry;
  3992. matchEntry.mEntrySource = checkTypeInst;
  3993. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  3994. }
  3995. }
  3996. checkTypeInst = checkTypeInst->GetImplBaseType();
  3997. }
  3998. for (auto interfacePair : interfaceMap)
  3999. {
  4000. auto& interfaceMatchEntry = interfacePair.mValue;
  4001. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4002. {
  4003. 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());
  4004. if (error != NULL)
  4005. {
  4006. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4007. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4008. }
  4009. }
  4010. }
  4011. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4012. {
  4013. int startTabIdx = (int)vData.size();
  4014. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4015. BfTypeInstance* checkTypeInst = typeInstance;
  4016. while (checkTypeInst != NULL)
  4017. {
  4018. origVirtTypeStack.push_back(checkTypeInst);
  4019. checkTypeInst = checkTypeInst->GetImplBaseType();
  4020. }
  4021. Array<BfVirtualMethodEntry> origVTable;
  4022. int origVirtIdx = 0;
  4023. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4024. {
  4025. HashSet<String> reslotNames;
  4026. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4027. {
  4028. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4029. if (entry.mDeclaringMethod.mMethodNum == -1)
  4030. continue;
  4031. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4032. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4033. {
  4034. if (origVTable.empty())
  4035. origVTable = typeInstance->mVirtualMethodTable;
  4036. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4037. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4038. {
  4039. // Prepare to reslot...
  4040. entry.mImplementingMethod = entry.mDeclaringMethod;
  4041. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4042. }
  4043. else
  4044. {
  4045. // Decl isn't accessible, null out entry
  4046. entry.mImplementingMethod = BfMethodRef();
  4047. }
  4048. }
  4049. }
  4050. if (!reslotNames.IsEmpty())
  4051. {
  4052. BfAmbiguityContext ambiguityContext;
  4053. ambiguityContext.mTypeInstance = typeInstance;
  4054. ambiguityContext.mModule = this;
  4055. ambiguityContext.mIsProjectSpecific = true;
  4056. ambiguityContext.mIsReslotting = true;
  4057. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4058. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4059. {
  4060. auto methodInstance = methodGroup.mDefault;
  4061. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4062. continue;
  4063. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4064. continue;
  4065. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4066. continue;
  4067. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4068. continue;
  4069. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4070. }
  4071. ambiguityContext.Finish();
  4072. }
  4073. }
  4074. bool isInExts = false;
  4075. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4076. {
  4077. BfIRValue vValue = voidPtrNull;
  4078. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4079. BfModuleMethodInstance moduleMethodInst;
  4080. if (entry.mDeclaringMethod.mMethodNum == -1)
  4081. {
  4082. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4083. isInExts = true;
  4084. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4085. if (vExt)
  4086. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4087. }
  4088. else
  4089. {
  4090. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4091. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4092. {
  4093. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4094. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4095. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4096. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4097. {
  4098. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4099. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4100. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4101. vValue = funcPtr;
  4102. }
  4103. }
  4104. }
  4105. while (origVirtTypeStack.size() != 0)
  4106. {
  4107. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4108. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4109. {
  4110. // Moved past current base vtable size
  4111. origVirtTypeStack.pop_back();
  4112. continue;
  4113. }
  4114. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4115. {
  4116. // We are within the original vtable size
  4117. int idx = startTabIdx + origVirtIdx;
  4118. origVirtIdx++;
  4119. vData.push_back(vValue);
  4120. }
  4121. else
  4122. {
  4123. // This is a new entry, it only gets added to the ext
  4124. BF_ASSERT(isInExts);
  4125. }
  4126. break;
  4127. }
  4128. }
  4129. if (!origVTable.empty())
  4130. typeInstance->mVirtualMethodTable = origVTable;
  4131. }
  4132. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4133. if (typeInstance->mHotTypeData != NULL)
  4134. {
  4135. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4136. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4137. }
  4138. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4139. int iFaceMethodStartIdx = (int)vData.size();
  4140. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4141. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4142. vData[i] = voidPtrNull;
  4143. if (expectNumElements != 0)
  4144. BF_ASSERT(expectNumElements == vData.size());
  4145. //BF_ASSERT(vData.size() == expectNumElements);
  4146. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4147. // ifaceMethodExtData.Add(voidPtrNull);
  4148. int ifaceEntryIdx = iFaceMethodStartIdx;
  4149. for (auto& interfacePair : interfaceMap)
  4150. {
  4151. auto interfaceEntry = interfacePair.mValue.mEntry;
  4152. bool makeEmpty = false;
  4153. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4154. makeEmpty = true;
  4155. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4156. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4157. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4158. {
  4159. BfIRValue pushValue;
  4160. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4161. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4162. continue;
  4163. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4164. continue;
  4165. if (makeEmpty)
  4166. {
  4167. pushValue = voidPtrNull;
  4168. }
  4169. else
  4170. {
  4171. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4172. auto methodInstance = (BfMethodInstance*)methodRef;
  4173. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4174. {
  4175. BF_ASSERT(methodInstance->mIsReified);
  4176. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4177. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4178. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4179. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4180. pushValue = funcPtr;
  4181. }
  4182. else
  4183. {
  4184. pushValue = voidPtrNull;
  4185. }
  4186. }
  4187. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4188. if (idx < ifaceMethodExtStart)
  4189. {
  4190. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4191. vData[iFaceMethodStartIdx + idx] = pushValue;
  4192. }
  4193. else
  4194. {
  4195. BF_ASSERT(useExt);
  4196. int extIdx = idx - ifaceMethodExtStart;
  4197. while (extIdx >= ifaceMethodExtData.size())
  4198. ifaceMethodExtData.Add(voidPtrNull);
  4199. ifaceMethodExtData[extIdx] = pushValue;
  4200. }
  4201. }
  4202. }
  4203. if (typeInstance->IsBoxed())
  4204. {
  4205. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4206. if (boxedType->IsBoxedStructPtr())
  4207. {
  4208. // Force override of GetHashCode so we use the pointer address as the hash code
  4209. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4210. // Force override of GetHashCode so we use the pointer address as the hash code
  4211. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4212. {
  4213. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4214. {
  4215. BfIRValue pushValue;
  4216. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4217. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4218. continue;
  4219. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4220. continue;
  4221. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4222. auto methodInstance = (BfMethodInstance*)methodRef;
  4223. BF_ASSERT(methodInstance->mIsReified);
  4224. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4225. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4226. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4227. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4228. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4229. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4230. }
  4231. }
  4232. }
  4233. }
  4234. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4235. {
  4236. BfIRValue ifaceMethodExtVar;
  4237. if (!ifaceMethodExtData.IsEmpty())
  4238. {
  4239. StringT<128> classVDataName;
  4240. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4241. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4242. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4243. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4244. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4245. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4246. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4247. }
  4248. for (auto& ifaceInstPair : interfaceMap)
  4249. {
  4250. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4251. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4252. if (slotNum >= 0)
  4253. {
  4254. BfIRValue vtablePtr;
  4255. int idx = interfaceEntry->mStartVirtualIdx;
  4256. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4257. if (endVirtualIdx > ifaceMethodExtStart)
  4258. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4259. else
  4260. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4261. int slotVirtIdx = slotNum + vDataOfs;
  4262. if (vData[slotVirtIdx] == voidPtrNull)
  4263. {
  4264. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4265. }
  4266. else
  4267. {
  4268. if (mCompiler->IsHotCompile())
  4269. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4270. else
  4271. Fail("Interface slot collision error", typeDef->GetRefNode());
  4272. }
  4273. }
  4274. }
  4275. }
  4276. }
  4277. BfIRValue typeNameConst;
  4278. BfIRValue namespaceConst;
  4279. if (needsTypeNames)
  4280. {
  4281. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4282. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4283. }
  4284. else
  4285. {
  4286. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4287. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4288. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4289. }
  4290. int baseTypeId = 0;
  4291. if (typeInstance->mBaseType != NULL)
  4292. {
  4293. baseTypeId = typeInstance->mBaseType->mTypeId;
  4294. }
  4295. SizedArray<BfIRValue, 16> customAttrs;
  4296. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4297. BfIRValue castedClassVData;
  4298. if (classVDataVar)
  4299. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4300. else
  4301. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4302. bool freflectIncludeTypeData = false;
  4303. bool reflectIncludeAllFields = false;
  4304. bool reflectIncludeAllMethods = false;
  4305. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4306. {
  4307. reflectIncludeAllFields = true;
  4308. reflectIncludeAllMethods = true;
  4309. }
  4310. enum ReflectKind
  4311. {
  4312. ReflectKind_None = 0,
  4313. ReflectKind_Type = 1,
  4314. ReflectKind_NonStaticFields = 2,
  4315. ReflectKind_StaticFields = 4,
  4316. ReflectKind_DefaultConstructor = 8,
  4317. ReflectKind_Constructors = 0x10,
  4318. ReflectKind_StaticMethods = 0x20,
  4319. ReflectKind_Methods = 0x40,
  4320. ReflectKind_User = 0x80,
  4321. ReflectKind_All = 0x7F,
  4322. ReflectKind_ApplyToInnerTypes = 0x80
  4323. };
  4324. ReflectKind reflectKind = ReflectKind_Type;
  4325. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4326. {
  4327. ReflectKind reflectKind = ReflectKind_None;
  4328. if (attrType->mCustomAttributes != NULL)
  4329. {
  4330. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4331. {
  4332. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4333. {
  4334. for (auto& prop : customAttr.mSetProperties)
  4335. {
  4336. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4337. if (propDef->mName == "ReflectUser")
  4338. {
  4339. if (prop.mParam.mValue.IsConst())
  4340. {
  4341. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4342. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4343. }
  4344. }
  4345. }
  4346. // Check for Flags arg
  4347. if (customAttr.mCtorArgs.size() < 2)
  4348. continue;
  4349. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4350. if (constant == NULL)
  4351. continue;
  4352. if (constant->mTypeCode == BfTypeCode_Boolean)
  4353. continue;
  4354. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4355. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4356. }
  4357. }
  4358. }
  4359. return reflectKind;
  4360. };
  4361. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4362. {
  4363. ReflectKind reflectKind = ReflectKind_None;
  4364. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4365. if (customAttrs != NULL)
  4366. {
  4367. for (auto& attr : customAttrs->mAttributes)
  4368. {
  4369. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4370. }
  4371. }
  4372. return reflectKind;
  4373. };
  4374. //
  4375. {
  4376. auto checkTypeInstance = typeInstance;
  4377. while (checkTypeInstance != NULL)
  4378. {
  4379. if (checkTypeInstance->mCustomAttributes != NULL)
  4380. {
  4381. auto checkReflectKind = ReflectKind_None;
  4382. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4383. {
  4384. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4385. {
  4386. if (customAttr.mCtorArgs.size() > 0)
  4387. {
  4388. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4389. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4390. }
  4391. else
  4392. {
  4393. checkReflectKind = ReflectKind_All;
  4394. }
  4395. }
  4396. else
  4397. {
  4398. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4399. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4400. }
  4401. }
  4402. if ((checkTypeInstance == typeInstance) ||
  4403. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4404. {
  4405. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4406. }
  4407. }
  4408. checkTypeInstance = GetOuterType(checkTypeInstance);
  4409. }
  4410. }
  4411. // Fields
  4412. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4413. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4414. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4415. {
  4416. if (customAttributes == NULL)
  4417. return -1;
  4418. Array<BfCustomAttribute*> reflectAttributes;
  4419. for (auto& attr : customAttributes->mAttributes)
  4420. {
  4421. bool wantAttribute = false;
  4422. if (attr.mType->mCustomAttributes != NULL)
  4423. {
  4424. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4425. if (usageAttribute != NULL)
  4426. {
  4427. // Check for Flags arg
  4428. if (usageAttribute->mCtorArgs.size() < 2)
  4429. continue;
  4430. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4431. if (constant == NULL)
  4432. continue;
  4433. if (constant->mTypeCode == BfTypeCode_Boolean)
  4434. continue;
  4435. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4436. wantAttribute = true;
  4437. }
  4438. }
  4439. if ((wantAttribute) && (attr.mType->mIsReified))
  4440. {
  4441. reflectAttributes.Add(&attr);
  4442. }
  4443. }
  4444. if (reflectAttributes.size() == 0)
  4445. return -1;
  4446. #define PUSH_INT8(val) data.push_back((uint8)val)
  4447. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4448. #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); }
  4449. #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); \
  4450. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4451. SizedArray<uint8, 16> data;
  4452. int customAttrIdx = (int)customAttrs.size();
  4453. data.push_back((uint8)reflectAttributes.size());
  4454. for (auto attr : reflectAttributes)
  4455. {
  4456. // Size prefix
  4457. int sizeIdx = (int)data.size();
  4458. PUSH_INT16(0); // mSize
  4459. PUSH_INT32(attr->mType->mTypeId); // mType
  4460. PUSH_INT16(attr->mCtor->mIdx);
  4461. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4462. int argIdx = 0;
  4463. for (auto arg : attr->mCtorArgs)
  4464. {
  4465. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4466. bool handled = false;
  4467. if (constant != NULL)
  4468. {
  4469. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4470. if (argType->IsObject())
  4471. {
  4472. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4473. int stringId = constant->mInt32;
  4474. int* orderedIdPtr;
  4475. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4476. {
  4477. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4478. }
  4479. GetStringObjectValue(stringId);
  4480. PUSH_INT8(0xFF); // String
  4481. PUSH_INT32(*orderedIdPtr);
  4482. continue;
  4483. }
  4484. PUSH_INT8(constant->mTypeCode);
  4485. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4486. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4487. (constant->mTypeCode == BfTypeCode_Double))
  4488. {
  4489. PUSH_INT64(constant->mInt64);
  4490. }
  4491. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4492. (constant->mTypeCode == BfTypeCode_UInt32))
  4493. {
  4494. PUSH_INT32(constant->mInt32);
  4495. }
  4496. else if (constant->mTypeCode == BfTypeCode_Single)
  4497. {
  4498. float val = (float)constant->mDouble;
  4499. PUSH_INT32(*(int*)&val);
  4500. }
  4501. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4502. (constant->mTypeCode == BfTypeCode_UInt16))
  4503. {
  4504. PUSH_INT16(constant->mInt16);
  4505. }
  4506. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4507. (constant->mTypeCode == BfTypeCode_UInt8))
  4508. {
  4509. PUSH_INT8(constant->mInt8);
  4510. }
  4511. else if (constant->mTypeCode == BfTypeCode_Object)
  4512. {
  4513. BF_FATAL("Unhandled");
  4514. }
  4515. else
  4516. {
  4517. BF_FATAL("Unhandled");
  4518. }
  4519. }
  4520. else if (!handled)
  4521. {
  4522. BF_FATAL("Unhandled");
  4523. }
  4524. argIdx++;
  4525. }
  4526. int size = (int)data.size() - sizeIdx;
  4527. *((uint16*)&data[sizeIdx]) = size;
  4528. }
  4529. #undef PUSH_INT8
  4530. #undef PUSH_INT16
  4531. #undef PUSH_INT32
  4532. SizedArray<BfIRValue, 16> dataValues;
  4533. for (uint8 val : data)
  4534. dataValues.push_back(GetConstValue8(val));
  4535. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4536. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4537. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4538. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4539. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4540. customAttrs.push_back(customAttrArrayPtr);
  4541. return customAttrIdx;
  4542. };
  4543. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4544. SizedArray<int, 16> reflectFieldIndices;
  4545. for (int pass = 0; pass < 2; pass++)
  4546. {
  4547. bool skippedField = false;
  4548. reflectFieldIndices.clear();
  4549. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4550. {
  4551. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4552. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4553. if (fieldDef == NULL)
  4554. continue;
  4555. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4556. bool includeField = reflectIncludeAllFields;
  4557. if (fieldInstance->mCustomAttributes != NULL)
  4558. {
  4559. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4560. {
  4561. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4562. {
  4563. includeField = true;
  4564. }
  4565. else
  4566. {
  4567. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4568. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4569. }
  4570. }
  4571. }
  4572. if ((fieldReflectKind & ReflectKind_User) != 0)
  4573. includeField = true;
  4574. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4575. includeField = true;
  4576. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4577. includeField = true;
  4578. includeField |= forceReflectFields;
  4579. if (!includeField)
  4580. {
  4581. skippedField = true;
  4582. continue;
  4583. }
  4584. reflectFieldIndices.Add(fieldIdx);
  4585. }
  4586. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4587. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4588. // possible because we write out a SplatData structure containing just TypeIds in that case
  4589. if (pass == 0)
  4590. {
  4591. if (!typeInstance->IsSplattable())
  4592. break;
  4593. if (!skippedField)
  4594. break;
  4595. if (reflectFieldIndices.size() == 0)
  4596. break;
  4597. }
  4598. }
  4599. SizedArray<BfIRValue, 16> fieldTypes;
  4600. enum FieldFlags
  4601. {
  4602. FieldFlags_Protected = 3,
  4603. FieldFlags_Public = 6,
  4604. FieldFlags_Static = 0x10,
  4605. FieldFlags_Const = 0x40,
  4606. FieldFlags_SpecialName = 0x80,
  4607. FieldFlags_EnumPayload = 0x100,
  4608. FieldFlags_EnumDiscriminator = 0x200
  4609. };
  4610. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4611. {
  4612. BfType* payloadType = typeInstance->GetUnionInnerType();
  4613. if (!payloadType->IsValuelessType())
  4614. {
  4615. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4616. SizedArray<BfIRValue, 8> payloadFieldVals =
  4617. {
  4618. emptyValueType,
  4619. payloadNameConst, // mName
  4620. GetConstValue(0, longType), // mConstValue
  4621. GetConstValue(0, intType), // mDataOffset
  4622. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4623. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4624. GetConstValue(-1, intType), // mCustomAttributesIdx
  4625. };
  4626. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4627. fieldTypes.push_back(payloadFieldData);
  4628. }
  4629. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4630. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4631. SizedArray<BfIRValue, 8> dscrFieldVals =
  4632. {
  4633. emptyValueType,
  4634. dscrNameConst, // mName
  4635. GetConstValue(0, longType), // mConstValue
  4636. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4637. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4638. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4639. GetConstValue(-1, intType), // mCustomAttributesIdx
  4640. };
  4641. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4642. fieldTypes.push_back(dscrFieldData);
  4643. }
  4644. for (auto fieldIdx : reflectFieldIndices)
  4645. {
  4646. if (!needsTypeData)
  4647. break;
  4648. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4649. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4650. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4651. int typeId = 0;
  4652. auto fieldType = fieldInstance->GetResolvedType();
  4653. if (fieldType->IsGenericParam())
  4654. {
  4655. //TODO:
  4656. }
  4657. else
  4658. typeId = fieldType->mTypeId;
  4659. FieldFlags fieldFlags = (FieldFlags)0;
  4660. if (fieldDef->mProtection == BfProtection_Protected)
  4661. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4662. if (fieldDef->mProtection == BfProtection_Public)
  4663. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4664. if (fieldDef->mIsStatic)
  4665. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4666. if (fieldDef->mIsConst)
  4667. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4668. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4669. BfIRValue constValue = GetConstValue(0, longType);
  4670. if (fieldInstance->GetFieldDef()->mIsConst)
  4671. {
  4672. if (fieldInstance->mConstIdx != -1)
  4673. {
  4674. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4675. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4676. }
  4677. }
  4678. SizedArray<BfIRValue, 8> fieldVals =
  4679. {
  4680. emptyValueType,
  4681. fieldNameConst, // mName
  4682. constValue, // mConstValue
  4683. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4684. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4685. GetConstValue(fieldFlags, shortType), // mFlags
  4686. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4687. };
  4688. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4689. fieldTypes.push_back(fieldData);
  4690. }
  4691. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4692. BfIRValue fieldDataPtr;
  4693. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4694. if (fieldTypes.size() == 0)
  4695. {
  4696. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4697. {
  4698. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4699. SizedArray<BfIRValue, 3> splatTypes;
  4700. SizedArray<BfIRValue, 3> splatOffsets;
  4701. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4702. {
  4703. auto checkTypeInstance = checkType->ToTypeInstance();
  4704. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4705. PopulateType(checkTypeInstance);
  4706. if (checkType->IsStruct())
  4707. {
  4708. int dataEnd = offset;
  4709. if (checkTypeInstance->mBaseType != NULL)
  4710. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4711. if (checkTypeInstance->mIsUnion)
  4712. {
  4713. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4714. _CheckSplat(unionInnerType, offset);
  4715. }
  4716. else
  4717. {
  4718. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4719. {
  4720. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4721. if (fieldInstance->mDataIdx >= 0)
  4722. {
  4723. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4724. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4725. }
  4726. }
  4727. }
  4728. if (checkTypeInstance->IsEnum())
  4729. {
  4730. // Add discriminator
  4731. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4732. if (!checkTypeInstance->mIsPacked)
  4733. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4734. _CheckSplat(dscrType, dataEnd);
  4735. }
  4736. }
  4737. else if (checkType->IsMethodRef())
  4738. {
  4739. // auto methodRefType = (BfMethodRefType*)checkType;
  4740. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4741. // {
  4742. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4743. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4744. // else
  4745. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4746. // }
  4747. }
  4748. else if (!checkType->IsValuelessType())
  4749. {
  4750. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4751. splatOffsets.Add(GetConstValue(offset, intType));
  4752. }
  4753. };
  4754. _CheckSplat(type, 0);
  4755. while (splatTypes.size() < 3)
  4756. {
  4757. splatTypes.Add(GetConstValue(0, typeIdType));
  4758. splatOffsets.Add(GetConstValue(0, intType));
  4759. }
  4760. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4761. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4762. SizedArray<BfIRValue, 8> splatVals =
  4763. {
  4764. emptyValueType,
  4765. splatTypesConst,
  4766. splatOffsetsConst
  4767. };
  4768. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4769. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4770. fieldSplatData, typeDataName + ".splats");
  4771. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4772. }
  4773. else
  4774. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4775. }
  4776. else
  4777. {
  4778. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4779. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4780. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4781. fieldDataConst, "fields." + typeDataName);
  4782. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4783. }
  4784. /// Methods
  4785. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4786. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4787. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4788. SizedArray<BfIRValue, 16> methodTypes;
  4789. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4790. {
  4791. if (!needsTypeData)
  4792. break;
  4793. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4794. if (!methodInstanceGroup->IsImplemented())
  4795. continue;
  4796. auto methodDef = typeDef->mMethods[methodIdx];
  4797. if (methodDef->mNoReflect)
  4798. continue;
  4799. auto defaultMethod = methodInstanceGroup->mDefault;
  4800. if (defaultMethod == NULL)
  4801. continue;
  4802. if (defaultMethod->mIsUnspecialized)
  4803. continue;
  4804. if (!defaultMethod->mIsReified)
  4805. continue;
  4806. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4807. continue;
  4808. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4809. continue;
  4810. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4811. bool includeMethod = reflectIncludeAllMethods;
  4812. BfCustomAttributes* methodCustomAttributes = NULL;
  4813. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4814. {
  4815. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4816. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4817. {
  4818. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4819. {
  4820. includeMethod = true;
  4821. }
  4822. else
  4823. {
  4824. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4825. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4826. }
  4827. }
  4828. }
  4829. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4830. continue;
  4831. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4832. {
  4833. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4834. {
  4835. if (paramDecl->mAttributes != NULL)
  4836. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4837. }
  4838. if (methodDeclaration->mReturnAttributes != NULL)
  4839. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4840. }
  4841. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4842. includeMethod = true;
  4843. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4844. includeMethod = true;
  4845. if (!includeMethod)
  4846. continue;
  4847. BfModuleMethodInstance moduleMethodInstance;
  4848. BfIRValue funcVal = voidPtrNull;
  4849. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4850. (!typeInstance->IsUnspecializedType()) &&
  4851. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4852. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4853. (!methodDef->mIsAbstract) &&
  4854. (methodDef->mGenericParams.size() == 0))
  4855. {
  4856. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4857. if (moduleMethodInstance.mFunc)
  4858. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4859. }
  4860. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4861. enum MethodFlags
  4862. {
  4863. MethodFlags_Protected = 3,
  4864. MethodFlags_Public = 6,
  4865. MethodFlags_Static = 0x10,
  4866. MethodFlags_Virtual = 0x40,
  4867. MethodFlags_StdCall = 0x1000,
  4868. MethodFlags_FastCall = 0x2000,
  4869. MethodFlags_Mutating = 0x4000,
  4870. };
  4871. MethodFlags methodFlags = (MethodFlags)0;
  4872. if (methodDef->mProtection == BfProtection_Protected)
  4873. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4874. if (methodDef->mProtection == BfProtection_Public)
  4875. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4876. if (methodDef->mIsStatic)
  4877. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4878. if (methodDef->mIsVirtual)
  4879. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4880. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4881. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4882. if (methodDef->mIsMutating)
  4883. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4884. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4885. enum ParamFlags
  4886. {
  4887. ParamFlag_None = 0,
  4888. ParamFlag_Splat = 1,
  4889. ParamFlag_Implicit = 2,
  4890. };
  4891. SizedArray<BfIRValue, 8> paramVals;
  4892. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4893. {
  4894. String paramName = defaultMethod->GetParamName(paramIdx);
  4895. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4896. ParamFlags paramFlags = ParamFlag_None;
  4897. if (defaultMethod->GetParamIsSplat(paramIdx))
  4898. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4899. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4900. SizedArray<BfIRValue, 8> paramDataVals =
  4901. {
  4902. emptyValueType,
  4903. paramNameConst,
  4904. GetConstValue(paramType->mTypeId, typeIdType),
  4905. GetConstValue((int32)paramFlags, shortType),
  4906. GetConstValue(customAttrIdx, intType) // defaultIdx
  4907. };
  4908. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4909. paramVals.Add(paramData);
  4910. }
  4911. BfIRValue paramsVal;
  4912. if (paramVals.size() > 0)
  4913. {
  4914. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4915. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4916. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4917. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4918. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4919. }
  4920. else
  4921. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4922. int vDataVal = -1;
  4923. if (defaultMethod->mVirtualTableIdx != -1)
  4924. {
  4925. int vDataIdx = -1;
  4926. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4927. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4928. {
  4929. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4930. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4931. if (extMethodIdx >= 0)
  4932. {
  4933. // Extension?
  4934. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4935. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4936. }
  4937. else
  4938. {
  4939. // Map this new virtual index back to the original index
  4940. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4941. }
  4942. }
  4943. else
  4944. {
  4945. vDataIdx += defaultMethod->mVirtualTableIdx;
  4946. }
  4947. if (vDataVal == -1)
  4948. vDataVal = vDataIdx * mSystem->mPtrSize;
  4949. }
  4950. SizedArray<BfIRValue, 8> methodDataVals =
  4951. {
  4952. emptyValueType,
  4953. methodNameConst, // mName
  4954. funcVal, // mFuncPtr
  4955. paramsVal,
  4956. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4957. GetConstValue((int)paramVals.size(), shortType),
  4958. GetConstValue(methodFlags, shortType),
  4959. GetConstValue(vDataVal, intType),
  4960. GetConstValue(-1, intType),
  4961. };
  4962. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4963. methodTypes.push_back(methodData);
  4964. }
  4965. BfIRValue methodDataPtr;
  4966. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4967. if (methodTypes.size() == 0)
  4968. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4969. else
  4970. {
  4971. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4972. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4973. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4974. methodDataConst, "methods." + typeDataName);
  4975. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4976. }
  4977. /////
  4978. int underlyingType = 0;
  4979. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4980. {
  4981. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4982. }
  4983. int outerTypeId = 0;
  4984. auto outerType = GetOuterType(typeInstance);
  4985. if (outerType != NULL)
  4986. outerTypeId = outerType->mTypeId;
  4987. BfIRValue customAttrDataPtr;
  4988. if (customAttrs.size() > 0)
  4989. {
  4990. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  4991. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  4992. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  4993. customAttrsConst, "customAttrs." + typeDataName);
  4994. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  4995. }
  4996. else
  4997. {
  4998. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  4999. }
  5000. SizedArray<BfIRValue, 32> typeDataVals =
  5001. {
  5002. typeData,
  5003. castedClassVData, // mTypeClassVData
  5004. typeNameConst, // mName
  5005. namespaceConst, // mNamespace
  5006. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5007. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5008. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5009. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5010. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5011. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5012. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5013. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5014. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5015. GetConstValue(0, byteType), // mInterfaceCount
  5016. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5017. GetConstValue(0, shortType), // mPropertyDataCount
  5018. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5019. GetConstValue(0, shortType), // mConstructorDataCount
  5020. voidPtrNull, // mInterfaceDataPtr
  5021. methodDataPtr, // mMethodDataPtr
  5022. voidPtrNull, // mPropertyDataPtr
  5023. fieldDataPtr, // mFieldDataPtr
  5024. voidPtrNull, // mConstructorDataPtr
  5025. customAttrDataPtr, // mCustomAttrDataPtr
  5026. };
  5027. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5028. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5029. if (!needsTypeData)
  5030. {
  5031. // No need for anything beyond typeInstanceData
  5032. }
  5033. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5034. {
  5035. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5036. SizedArray<BfIRValue, 4> unspecializedData =
  5037. {
  5038. typeInstanceData,
  5039. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5040. };
  5041. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5042. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5043. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5044. }
  5045. else if (typeInstance->IsGenericTypeInstance())
  5046. {
  5047. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5048. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5049. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5050. SizedArray<BfIRValue, 4> resolvedTypes;
  5051. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5052. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5053. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5054. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5055. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5056. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5057. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5058. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5059. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5060. SizedArray<BfIRValue, 3> specGenericData =
  5061. {
  5062. typeInstanceData,
  5063. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5064. resovledTypesPtr, // mFieldDataPtr
  5065. };
  5066. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5067. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5068. if (typeInstance->IsArray())
  5069. {
  5070. auto arrayType = (BfArrayType*)typeInstance;
  5071. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5072. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5073. SizedArray<BfIRValue, 4> arrayData =
  5074. {
  5075. typeInstanceData,
  5076. GetConstValue(elementType->mSize, intType), // mElementSize
  5077. GetConstValue(1, byteType), // mRank
  5078. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5079. };
  5080. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5081. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5082. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5083. }
  5084. }
  5085. BfIRValue typeDataVar;
  5086. if (needsTypeData)
  5087. {
  5088. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5089. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5090. if (mBfIRBuilder->DbgHasInfo())
  5091. {
  5092. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5093. }
  5094. }
  5095. else
  5096. {
  5097. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5098. }
  5099. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5100. mTypeDataRefs[typeInstance] = typeDataVar;
  5101. if (classVDataVar)
  5102. {
  5103. BF_ASSERT(!classVDataName.IsEmpty());
  5104. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5105. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5106. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5107. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5108. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5109. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5110. else
  5111. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5112. if (mBfIRBuilder->DbgHasInfo())
  5113. {
  5114. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5115. BfType* voidPtrType = CreatePointerType(voidType);
  5116. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5117. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5118. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5119. }
  5120. }
  5121. return typeDataVar;
  5122. }
  5123. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5124. {
  5125. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5126. return value;
  5127. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5128. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5129. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5130. }
  5131. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5132. {
  5133. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5134. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5135. // When we access classes with static constructors FROM a static constructor,
  5136. // we call that other class's static constructor first. Recursion cannot occur, since
  5137. // we simply ignore subsequent attempts to re-enter the constructor
  5138. if (!typeInstance->mHasStaticInitMethod)
  5139. return;
  5140. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5141. return;
  5142. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5143. return;
  5144. auto checkTypeDef = typeInstance->mTypeDef;
  5145. checkTypeDef->PopulateMemberSets();
  5146. BfMethodDef* nextMethodDef = NULL;
  5147. BfMemberSetEntry* entry;
  5148. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5149. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5150. while (nextMethodDef != NULL)
  5151. {
  5152. auto checkMethod = nextMethodDef;
  5153. nextMethodDef = nextMethodDef->mNextWithSameName;
  5154. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5155. if (methodModule)
  5156. {
  5157. auto methodInstance = methodModule.mMethodInstance;
  5158. if ((methodInstance != NULL) &&
  5159. (methodInstance->mMethodDef->mIsStatic) &&
  5160. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5161. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5162. {
  5163. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5164. break;
  5165. }
  5166. }
  5167. }
  5168. }
  5169. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5170. {
  5171. auto methodOwner = methodInstance->GetOwner();
  5172. auto methodDef = methodInstance->mMethodDef;
  5173. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5174. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5175. if (!hasExternSpecifier)
  5176. return BfIRFunction();
  5177. if (methodInstance->GetCustomAttributes() == NULL)
  5178. return BfIRFunction();
  5179. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5180. {
  5181. String typeName = TypeToString(customAttribute.mType);
  5182. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5183. {
  5184. methodInstance->mIsIntrinsic = true;
  5185. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5186. String error;
  5187. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5188. {
  5189. int stringId = constant->mInt32;
  5190. auto entry = mContext->mStringObjectIdMap[stringId];
  5191. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5192. if (intrinId != -1)
  5193. {
  5194. if (intrinId == BfIRIntrinsic_Malloc)
  5195. {
  5196. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5197. }
  5198. else if (intrinId == BfIRIntrinsic_Free)
  5199. {
  5200. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5201. }
  5202. SizedArray<BfIRType, 2> paramTypes;
  5203. for (auto& param : methodInstance->mParams)
  5204. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5205. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5206. }
  5207. else if (reportFailure)
  5208. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5209. }
  5210. else if (reportFailure)
  5211. error = "Intrinsic name must be a constant string";
  5212. if (reportFailure)
  5213. {
  5214. BfAstNode* ref = methodDeclaration->mAttributes;
  5215. Fail(error, ref);
  5216. }
  5217. }
  5218. }
  5219. return BfIRFunction();
  5220. }
  5221. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5222. {
  5223. if (mBfIRBuilder->mIgnoreWrites)
  5224. return mBfIRBuilder->GetFakeFunction();
  5225. if (!mBuiltInFuncs[(int)funcTypeId])
  5226. {
  5227. SizedArray<BfIRType, 4> paramTypes;
  5228. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5229. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5230. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5231. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5232. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5233. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5234. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5235. BfIRFunctionType funcType;
  5236. BfIRFunction func;
  5237. switch (funcTypeId)
  5238. {
  5239. case BfBuiltInFuncType_PrintF:
  5240. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5241. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5242. break;
  5243. case BfBuiltInFuncType_Malloc:
  5244. {
  5245. if (mCompiler->mOptions.mDebugAlloc)
  5246. {
  5247. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5248. }
  5249. else
  5250. {
  5251. String funcName = mCompiler->mOptions.mMallocLinkName;
  5252. if (funcName.IsEmpty())
  5253. funcName = "malloc";
  5254. func = mBfIRBuilder->GetFunction(funcName);
  5255. if (!func)
  5256. {
  5257. paramTypes.clear();
  5258. paramTypes.push_back(intType);
  5259. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5260. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5261. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5262. }
  5263. }
  5264. }
  5265. break;
  5266. case BfBuiltInFuncType_Free:
  5267. {
  5268. if (mCompiler->mOptions.mDebugAlloc)
  5269. {
  5270. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5271. }
  5272. else
  5273. {
  5274. String funcName = mCompiler->mOptions.mFreeLinkName;
  5275. if (funcName.IsEmpty())
  5276. funcName = "free";
  5277. func = mBfIRBuilder->GetFunction(funcName);
  5278. if (!func)
  5279. {
  5280. paramTypes.clear();
  5281. paramTypes.push_back(nullPtrType);
  5282. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5283. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5284. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5285. }
  5286. }
  5287. }
  5288. break;
  5289. case BfBuiltInFuncType_LoadSharedLibraries:
  5290. paramTypes.clear();
  5291. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5292. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5293. break;
  5294. default: break;
  5295. }
  5296. mBuiltInFuncs[(int)funcTypeId] = func;
  5297. return func;
  5298. }
  5299. return mBuiltInFuncs[(int)funcTypeId];
  5300. }
  5301. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5302. {
  5303. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5304. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5305. BfAutoComplete* bfAutocomplete = NULL;
  5306. if (mCompiler->mResolvePassData != NULL)
  5307. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5308. if (bfAutocomplete != NULL)
  5309. {
  5310. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5311. {
  5312. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5313. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5314. {
  5315. String filter = nameNode->ToString();
  5316. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5317. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5318. if (nameIdx != 0)
  5319. {
  5320. for (auto checkGenericParam : genericParamDefs)
  5321. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5322. }
  5323. }
  5324. }
  5325. }
  5326. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5327. {
  5328. if (bfAutocomplete != NULL)
  5329. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5330. //TODO: Constraints may refer to other generic params (of either type or method)
  5331. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5332. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5333. if (constraintType != NULL)
  5334. {
  5335. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5336. {
  5337. bool isValidTypeCode = false;
  5338. BfTypeCode typeCode = BfTypeCode_None;
  5339. if (constraintType->IsTypedPrimitive())
  5340. {
  5341. auto underlyingType = constraintType->GetUnderlyingType();
  5342. if (underlyingType->IsPrimitiveType())
  5343. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5344. }
  5345. if (constraintType->IsPrimitiveType())
  5346. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5347. switch (typeCode)
  5348. {
  5349. case BfTypeCode_Int8:
  5350. case BfTypeCode_UInt8:
  5351. case BfTypeCode_Int16:
  5352. case BfTypeCode_UInt16:
  5353. case BfTypeCode_Int32:
  5354. case BfTypeCode_UInt32:
  5355. case BfTypeCode_Int64:
  5356. case BfTypeCode_UInt64:
  5357. case BfTypeCode_IntPtr:
  5358. case BfTypeCode_UIntPtr:
  5359. case BfTypeCode_IntUnknown:
  5360. case BfTypeCode_UIntUnknown:
  5361. case BfTypeCode_Single:
  5362. case BfTypeCode_Double:
  5363. case BfTypeCode_Char8:
  5364. case BfTypeCode_Char16:
  5365. case BfTypeCode_Char32:
  5366. isValidTypeCode = true;
  5367. break;
  5368. default: break;
  5369. }
  5370. if (isValidTypeCode)
  5371. {
  5372. genericParamInstance->mTypeConstraint = constraintType;
  5373. }
  5374. else
  5375. {
  5376. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5377. }
  5378. }
  5379. else
  5380. {
  5381. if (constraintType->IsPrimitiveType())
  5382. {
  5383. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5384. continue;
  5385. }
  5386. if (constraintType->IsArray())
  5387. {
  5388. 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);
  5389. continue;
  5390. }
  5391. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5392. {
  5393. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5394. continue;
  5395. }
  5396. if (constraintType->IsInterface())
  5397. {
  5398. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5399. }
  5400. else
  5401. {
  5402. auto constraintTypeInst = constraintType->ToTypeInstance();
  5403. if (genericParamInstance->mTypeConstraint != NULL)
  5404. {
  5405. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5406. {
  5407. // Allow more specific type
  5408. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5409. }
  5410. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5411. {
  5412. // Silently ignore less-specific type
  5413. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5414. {
  5415. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5416. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5417. }
  5418. }
  5419. else
  5420. {
  5421. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5422. return;
  5423. }
  5424. }
  5425. else
  5426. genericParamInstance->mTypeConstraint = constraintType;
  5427. }
  5428. }
  5429. }
  5430. }
  5431. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5432. (genericParamInstance->mTypeConstraint == NULL))
  5433. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5434. }
  5435. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5436. {
  5437. if (genericParamSource.mMethodInstance != NULL)
  5438. {
  5439. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5440. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5441. return MethodToString(methodInst);
  5442. }
  5443. else
  5444. {
  5445. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5446. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5447. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5448. return TypeToString(typeInst);
  5449. }
  5450. }
  5451. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5452. {
  5453. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5454. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5455. BfType* origCheckArgType = checkArgType;
  5456. if (origCheckArgType->IsRef())
  5457. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5458. bool argMayBeReferenceType = false;
  5459. int checkGenericParamFlags = 0;
  5460. if (checkArgType->IsGenericParam())
  5461. {
  5462. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5463. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5464. if (checkGenericParamInst->mTypeConstraint != NULL)
  5465. checkArgType = checkGenericParamInst->mTypeConstraint;
  5466. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5467. {
  5468. argMayBeReferenceType = false;
  5469. }
  5470. else
  5471. {
  5472. argMayBeReferenceType = true;
  5473. }
  5474. }
  5475. if (checkArgType->IsObjectOrInterface())
  5476. argMayBeReferenceType = true;
  5477. BfTypeInstance* typeConstraintInst = NULL;
  5478. if (genericParamInst->mTypeConstraint != NULL)
  5479. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5480. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5481. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5482. {
  5483. if (!ignoreErrors)
  5484. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5485. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5486. return false;
  5487. }
  5488. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5489. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5490. {
  5491. if (!ignoreErrors)
  5492. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5493. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5494. return false;
  5495. }
  5496. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5497. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5498. {
  5499. if (!ignoreErrors)
  5500. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5501. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5502. return false;
  5503. }
  5504. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5505. {
  5506. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5507. {
  5508. if (!ignoreErrors)
  5509. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5510. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5511. return false;
  5512. }
  5513. }
  5514. else
  5515. {
  5516. if (checkArgType->IsConstExprValue())
  5517. {
  5518. if (!ignoreErrors)
  5519. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5520. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5521. return false;
  5522. }
  5523. }
  5524. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5525. return true;
  5526. if (checkArgType->IsPointer())
  5527. {
  5528. auto ptrType = (BfPointerType*)checkArgType;
  5529. checkArgType = ptrType->mElementType;
  5530. }
  5531. if (genericParamInst->mTypeConstraint != NULL)
  5532. {
  5533. bool constraintMatched = false;
  5534. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5535. {
  5536. if (checkArgType->IsConstExprValue())
  5537. {
  5538. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5539. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5540. {
  5541. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5542. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5543. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5544. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5545. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5546. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5547. {
  5548. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5549. {
  5550. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5551. {
  5552. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5553. {
  5554. if (!ignoreErrors)
  5555. *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(),
  5556. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5557. return false;
  5558. }
  5559. }
  5560. else
  5561. {
  5562. if (!ignoreErrors)
  5563. *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(),
  5564. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5565. return false;
  5566. }
  5567. }
  5568. else
  5569. {
  5570. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5571. {
  5572. char valStr[64];
  5573. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5574. if (!ignoreErrors)
  5575. *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(),
  5576. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5577. return false;
  5578. }
  5579. }
  5580. }
  5581. }
  5582. }
  5583. }
  5584. else
  5585. {
  5586. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5587. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5588. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5589. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5590. {
  5591. auto methodRefType = (BfMethodRefType*)checkArgType;
  5592. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5593. BfExprEvaluator exprEvaluator(this);
  5594. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5595. constraintMatched = true;
  5596. }
  5597. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5598. {
  5599. constraintMatched = true;
  5600. }
  5601. else if (origCheckArgType->IsWrappableType())
  5602. {
  5603. if (origCheckArgType->IsSizedArray())
  5604. {
  5605. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5606. if (convCheckConstraint->IsGenericTypeInstance())
  5607. {
  5608. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5609. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5610. {
  5611. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5612. {
  5613. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5614. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5615. constraintMatched = true;
  5616. }
  5617. }
  5618. }
  5619. }
  5620. if (!constraintMatched)
  5621. {
  5622. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5623. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5624. constraintMatched = true;
  5625. }
  5626. }
  5627. if (!constraintMatched)
  5628. {
  5629. if (!ignoreErrors)
  5630. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5631. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5632. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5633. return false;
  5634. }
  5635. }
  5636. }
  5637. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5638. {
  5639. PopulateType(origCheckArgType);
  5640. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5641. if (checkTypeInst->mTypeDef->mIsConcrete)
  5642. {
  5643. if (!ignoreErrors)
  5644. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5645. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5646. return false;
  5647. }
  5648. }
  5649. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5650. {
  5651. BfType* convCheckConstraint = checkConstraint;
  5652. if (convCheckConstraint->IsUnspecializedType())
  5653. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5654. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5655. bool implementsInterface = false;
  5656. if (origCheckArgType != checkArgType)
  5657. {
  5658. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5659. }
  5660. if (!implementsInterface)
  5661. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5662. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5663. {
  5664. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5665. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5666. implementsInterface = true;
  5667. }
  5668. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5669. {
  5670. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5671. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5672. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5673. implementsInterface = true;
  5674. }
  5675. if (!implementsInterface)
  5676. {
  5677. if (!ignoreErrors)
  5678. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5679. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5680. return false;
  5681. }
  5682. }
  5683. return true;
  5684. }
  5685. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5686. {
  5687. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5688. {
  5689. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5690. return genericParamType;
  5691. }
  5692. auto genericParamType = new BfGenericParamType();
  5693. genericParamType->mContext = mContext;
  5694. genericParamType->mGenericParamKind = paramKind;
  5695. genericParamType->mGenericParamIdx = paramIdx;
  5696. PopulateType(genericParamType);
  5697. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5698. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5699. BfResolvedTypeSet::LookupContext lookupCtx;
  5700. lookupCtx.mModule = this;
  5701. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5702. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5703. BF_ASSERT(inserted);
  5704. typeEntry->mValue = genericParamType;
  5705. return genericParamType;
  5706. }
  5707. static int sValueFromExprIdx = 0;
  5708. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5709. {
  5710. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5711. if ((result) && (!ignoreNullable))
  5712. {
  5713. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5714. //TODO: Make this work, needed for 'void' and such
  5715. BfType* nullableType = NULL;
  5716. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5717. {
  5718. BfTypeVector typeVec;
  5719. typeVec.push_back(result.mType);
  5720. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5721. BF_ASSERT(nullableType != NULL);
  5722. }
  5723. // Go back to start and do any setup we need
  5724. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5725. BfTypedValue nullableTypedValue;
  5726. if (nullableType != NULL)
  5727. {
  5728. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5729. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5730. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5731. }
  5732. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5733. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5734. mBfIRBuilder->SetInsertPoint(notNullBB);
  5735. result = LoadValue(result);
  5736. if (nullableTypedValue)
  5737. {
  5738. auto elementType = nullableType->GetUnderlyingType();
  5739. if (elementType->IsValuelessType())
  5740. {
  5741. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5742. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5743. result = nullableTypedValue;
  5744. }
  5745. else
  5746. {
  5747. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5748. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5749. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5750. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5751. result = nullableTypedValue;
  5752. }
  5753. }
  5754. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5755. AddBasicBlock(pendingNullCond->mDoneBB);
  5756. if (nullableType == NULL)
  5757. {
  5758. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5759. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5760. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5761. result.mValue = phi;
  5762. }
  5763. }
  5764. else
  5765. {
  5766. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5767. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5768. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5769. AddBasicBlock(pendingNullCond->mDoneBB);
  5770. }
  5771. delete mCurMethodState->mPendingNullConditional;
  5772. mCurMethodState->mPendingNullConditional = NULL;
  5773. return result;
  5774. }
  5775. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5776. {
  5777. BfScopeData newScope;
  5778. newScope.mOuterIsConditional = true;
  5779. newScope.mAllowTargeting = false;
  5780. mCurMethodState->AddScope(&newScope);
  5781. NewScopeState();
  5782. exprEvaluator.mBfEvalExprFlags = flags;
  5783. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5784. RestoreScopeState();
  5785. }
  5786. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5787. {
  5788. //
  5789. {
  5790. BP_ZONE("CreateValueFromExpression:CheckStack");
  5791. StackHelper stackHelper;
  5792. if (!stackHelper.CanStackExpand(64 * 1024))
  5793. {
  5794. BfTypedValue result;
  5795. if (!stackHelper.Execute([&]()
  5796. {
  5797. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5798. }))
  5799. {
  5800. Fail("Expression too complex to compile", expr);
  5801. }
  5802. return result;
  5803. }
  5804. }
  5805. BP_ZONE("BfModule::CreateValueFromExpression");
  5806. if (outOrigType != NULL)
  5807. *outOrigType = NULL;
  5808. exprEvaluator.mExpectingType = wantTypeRef;
  5809. exprEvaluator.mBfEvalExprFlags = flags;
  5810. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5811. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5812. {
  5813. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5814. }
  5815. else
  5816. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5817. if (!exprEvaluator.mResult)
  5818. {
  5819. if (!mCompiler->mPassInstance->HasFailed())
  5820. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5821. return BfTypedValue();
  5822. }
  5823. auto typedVal = exprEvaluator.mResult;
  5824. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5825. {
  5826. BF_ASSERT(typedVal.mType->IsGenericParam());
  5827. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5828. bool handled = false;
  5829. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5830. {
  5831. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5832. if (genericTypeConstraint != NULL)
  5833. {
  5834. auto primType = genericTypeConstraint->ToPrimitiveType();
  5835. if (primType != NULL)
  5836. {
  5837. BfTypedValue result;
  5838. result.mKind = BfTypedValueKind_Value;
  5839. result.mType = genericTypeConstraint;
  5840. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5841. typedVal = result;
  5842. handled = true;
  5843. }
  5844. }
  5845. }
  5846. if (!handled)
  5847. {
  5848. //Fail("Only const generic parameters can be used as values", expr);
  5849. AssertErrorState();
  5850. return BfTypedValue();
  5851. }
  5852. }
  5853. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5854. FixIntUnknown(typedVal);
  5855. exprEvaluator.CheckResultForReading(typedVal);
  5856. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5857. {
  5858. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5859. {
  5860. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5861. bool allowRef = false;
  5862. BfExpression* checkExpr = expr;
  5863. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5864. checkExpr = parenExpr->mExpression;
  5865. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5866. {
  5867. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5868. allowRef = true;
  5869. }
  5870. if (!allowRef)
  5871. typedVal = RemoveRef(typedVal);
  5872. }
  5873. }
  5874. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5875. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5876. if (wantTypeRef != NULL)
  5877. {
  5878. if (outOrigType != NULL)
  5879. *outOrigType = typedVal.mType;
  5880. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5881. {
  5882. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5883. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5884. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5885. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5886. if (!typedVal)
  5887. return typedVal;
  5888. }
  5889. //WTF- why did we have this?
  5890. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5891. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5892. if (exprEvaluator.mIsVolatileReference)
  5893. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5894. }
  5895. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5896. // typedVal = MakeAddressable(typedVal);
  5897. //typedVal = AggregateSplat(typedVal);
  5898. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5899. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5900. return typedVal;
  5901. }
  5902. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5903. {
  5904. BfExprEvaluator exprEvaluator(this);
  5905. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5906. }
  5907. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5908. {
  5909. BfExprEvaluator exprEvaluator(this);
  5910. exprEvaluator.Evaluate(expr);
  5911. if (!exprEvaluator.mResult)
  5912. {
  5913. Fail("Invalid expression type", expr);
  5914. return BfTypedValue();
  5915. }
  5916. if (!exprEvaluator.mResult.IsAddr())
  5917. {
  5918. Fail("Cannot assign to value", expr);
  5919. return BfTypedValue();
  5920. }
  5921. return exprEvaluator.mResult;
  5922. }
  5923. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5924. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5925. {
  5926. auto typeInstance = typedValue.mType->ToTypeInstance();
  5927. if (zeroMemory)
  5928. {
  5929. int zeroAlign = typedValue.mType->mAlign;
  5930. if (typeInstance != NULL)
  5931. zeroAlign = typeInstance->mInstAlign;
  5932. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5933. }
  5934. if (!typedValue.mType->IsObject())
  5935. {
  5936. return;
  5937. }
  5938. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5939. return; // Handled in heap alloc funcs
  5940. auto typeDef = typeInstance->mTypeDef;
  5941. mBfIRBuilder->PopulateType(typedValue.mType);
  5942. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5943. bool isAutocomplete = mCompiler->IsAutocomplete();
  5944. BfIRValue vDataRef;
  5945. if (!isAutocomplete)
  5946. {
  5947. vDataRef = GetClassVDataPtr(typeInstance);
  5948. }
  5949. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5950. auto ptrType = CreatePointerType(i8Type);
  5951. auto ptrPtrType = CreatePointerType(ptrType);
  5952. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5953. PopulateType(ptrType, BfPopulateType_Declaration);
  5954. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5955. if (!isAutocomplete)
  5956. {
  5957. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5958. {
  5959. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5960. SizedArray<BfIRValue, 4> llvmArgs;
  5961. llvmArgs.push_back(objectPtr);
  5962. llvmArgs.push_back(vDataRef);
  5963. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5964. if (objectStackInitMethod)
  5965. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5966. }
  5967. else
  5968. {
  5969. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  5970. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  5971. mBfIRBuilder->CreateStore(srcVal, destAddr);
  5972. }
  5973. }
  5974. }
  5975. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  5976. {
  5977. BfIRValue result;
  5978. BfType* ptrType;
  5979. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  5980. ptrType = type;
  5981. else
  5982. ptrType = CreatePointerType(type);
  5983. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  5984. {
  5985. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  5986. SizedArray<BfExpression*, 2> argExprs;
  5987. BfTypedValueExpression typedValueExpr;
  5988. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  5989. typedValueExpr.mRefNode = refNode;
  5990. argExprs.push_back(&typedValueExpr);
  5991. BfTypedValueExpression appendSizeValueExpr;
  5992. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  5993. appendSizeValueExpr.mRefNode = refNode;
  5994. argExprs.push_back(&appendSizeValueExpr);
  5995. BfExprEvaluator exprEvaluator(this);
  5996. BfTypedValue allocResult;
  5997. if (allocTarget.mScopedInvocationTarget != NULL)
  5998. {
  5999. SizedArray<BfTypeReference*, 2> genericArgs;
  6000. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6001. allocResult = LoadValue(exprEvaluator.mResult);
  6002. }
  6003. else if (allocTarget.mCustomAllocator)
  6004. {
  6005. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6006. if (customTypeInst != NULL)
  6007. {
  6008. BfTypedValueExpression typeValueExpr;
  6009. String allocMethodName = "Alloc";
  6010. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6011. {
  6012. allocMethodName = "AllocTyped";
  6013. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6014. auto typeRefVal = CreateTypeDataRef(type);
  6015. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6016. typeValueExpr.mRefNode = refNode;
  6017. argExprs.Insert(0, &typeValueExpr);
  6018. }
  6019. if (HasMixin(customTypeInst, allocMethodName, 2))
  6020. {
  6021. BfSizedArray<BfExpression*> argExprArr;
  6022. argExprArr.mSize = (int)argExprs.size();
  6023. argExprArr.mVals = &argExprs[0];
  6024. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6025. allocResult = exprEvaluator.GetResult();
  6026. }
  6027. else
  6028. {
  6029. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6030. BfResolvedArgs argValues(&sizedArgExprs);
  6031. exprEvaluator.ResolveArgValues(argValues);
  6032. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6033. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6034. }
  6035. }
  6036. }
  6037. if (allocResult)
  6038. {
  6039. if (allocResult.mType->IsVoidPtr())
  6040. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6041. else
  6042. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6043. return result;
  6044. }
  6045. }
  6046. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6047. return result;
  6048. if (mCompiler->mOptions.mDebugAlloc)
  6049. {
  6050. BfIRValue allocData = GetDbgRawAllocData(type);
  6051. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6052. SizedArray<BfIRValue, 2> llvmArgs;
  6053. llvmArgs.push_back(sizeValue);
  6054. llvmArgs.push_back(allocData);
  6055. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6056. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6057. }
  6058. BfModuleMethodInstance moduleMethodInstance;
  6059. moduleMethodInstance = GetInternalMethod("Malloc");
  6060. SizedArray<BfIRValue, 1> llvmArgs;
  6061. llvmArgs.push_back(sizeValue);
  6062. auto func = moduleMethodInstance.mFunc;
  6063. if ((!func) || (func.IsFake()))
  6064. {
  6065. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6066. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6067. }
  6068. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6069. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6070. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6071. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6072. return result;
  6073. }
  6074. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6075. {
  6076. if (type->IsStruct())
  6077. {
  6078. auto typeInstance = type->ToTypeInstance();
  6079. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6080. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6081. }
  6082. else if (type->IsObjectOrInterface())
  6083. {
  6084. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6085. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6086. BF_ASSERT(moduleMethodInst.mFunc);
  6087. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6088. }
  6089. else
  6090. {
  6091. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6092. BfExprEvaluator exprEvaluator(this);
  6093. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6094. BfResolvedArg resolvedArg;
  6095. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6096. resolvedArgs.Add(resolvedArg);
  6097. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6098. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6099. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6100. BF_ASSERT(moduleMethodInst.mFunc);
  6101. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6102. }
  6103. return BfIRValue();
  6104. }
  6105. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6106. {
  6107. BfIRValue allocDataValue;
  6108. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6109. return allocDataValue;
  6110. BfIRValue markFuncPtr;
  6111. if (type->WantsGCMarking())
  6112. markFuncPtr = GetMarkFuncPtr(type);
  6113. else
  6114. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6115. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6116. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6117. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6118. if (typeInstance == NULL)
  6119. {
  6120. typeInstance = GetWrappedStructType(type);
  6121. if (typeInstance != NULL)
  6122. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6123. }
  6124. if (typeInstance != NULL)
  6125. PopulateType(typeInstance);
  6126. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6127. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6128. {
  6129. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6130. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6131. }
  6132. SizedArray<BfIRValue, 2> dataValues;
  6133. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6134. dataValues.Add(typeDataRef);
  6135. dataValues.Add(markFuncPtr);
  6136. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6137. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6138. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6139. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6140. return allocDataValue;
  6141. }
  6142. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6143. {
  6144. BP_ZONE("AllocFromType");
  6145. BfScopeData* scopeData = allocTarget.mScopeData;
  6146. auto typeInstance = type->ToTypeInstance();
  6147. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6148. typeInstance = mContext->mBfObjectType;
  6149. bool isHeapAlloc = scopeData == NULL;
  6150. bool isScopeAlloc = scopeData != NULL;
  6151. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6152. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6153. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6154. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6155. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6156. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6157. {
  6158. BfPointerType* ptrType = CreatePointerType(type);
  6159. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6160. return val;
  6161. }
  6162. if (typeInstance != NULL)
  6163. mBfIRBuilder->PopulateType(typeInstance);
  6164. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6165. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6166. {
  6167. if (arraySize)
  6168. {
  6169. if (isRawArrayAlloc)
  6170. {
  6171. BfPointerType* ptrType = CreatePointerType(type);
  6172. return GetDefaultValue(ptrType);
  6173. }
  6174. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6175. return GetDefaultValue(arrayType);
  6176. }
  6177. if (type->IsValueType())
  6178. {
  6179. BfPointerType* ptrType = CreatePointerType(type);
  6180. return GetDefaultValue(ptrType);
  6181. }
  6182. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6183. }
  6184. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6185. BfIRValue sizeValue;
  6186. BfIRType allocType = mBfIRBuilder->MapType(type);
  6187. int allocSize = type->mSize;
  6188. int allocAlign = type->mAlign;
  6189. if (typeInstance != NULL)
  6190. {
  6191. if (!mBfIRBuilder->mIgnoreWrites)
  6192. typeInstance->mHasBeenInstantiated = true;
  6193. allocSize = typeInstance->mInstSize;
  6194. allocAlign = typeInstance->mInstAlign;
  6195. //if (typeInstance->IsEnum())
  6196. //allocType = typeInstance->mIRType;
  6197. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6198. }
  6199. if (alignOverride != -1)
  6200. allocAlign = alignOverride;
  6201. // The "dynSize" cases:
  6202. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6203. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6204. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6205. // though we'd expect their stack space to be released
  6206. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6207. {
  6208. MarkDynStack(scopeData);
  6209. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6210. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6211. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6212. BfType* voidPtrType = CreatePointerType(voidType);
  6213. if (!mCurMethodState->mDynStackRevIdx)
  6214. {
  6215. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6216. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6217. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6218. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6219. mBfIRBuilder->ClearDebugLocation(storeInst);
  6220. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6221. }
  6222. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6223. auto bytePtrType = CreatePointerType(byteType);
  6224. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6225. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6226. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6227. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6228. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6229. mBfIRBuilder->ClearDebugLocation(storeInst);
  6230. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6231. mBfIRBuilder->ClearDebugLocation(storeInst);
  6232. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6233. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6234. if (IsTargetingBeefBackend())
  6235. {
  6236. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6237. // to ensure there isn't any register collision during looping is just to not allow it to
  6238. // bind to a register at all
  6239. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6240. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6241. }
  6242. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6243. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6244. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6245. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6246. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6247. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6248. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6249. mBfIRBuilder->AddBlock(verCheckBB);
  6250. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6251. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6252. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6253. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6254. mBfIRBuilder->AddBlock(resizeBB);
  6255. mBfIRBuilder->SetInsertPoint(resizeBB);
  6256. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6257. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6258. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6259. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6260. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6261. mBfIRBuilder->CreateBr(endBB);
  6262. mBfIRBuilder->AddBlock(endBB);
  6263. mBfIRBuilder->SetInsertPoint(endBB);
  6264. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6265. };
  6266. if (isScopeAlloc)
  6267. {
  6268. if (arraySize)
  6269. {
  6270. bool isConstantArraySize = arraySize.IsConst();
  6271. if (isRawArrayAlloc)
  6272. {
  6273. BfPointerType* ptrType = CreatePointerType(type);
  6274. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6275. {
  6276. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6277. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6278. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6279. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6280. }
  6281. else
  6282. {
  6283. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6284. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6285. if (!isDynAlloc)
  6286. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6287. else
  6288. {
  6289. MarkDynStack(scopeData);
  6290. SaveStackState(scopeData);
  6291. }
  6292. int typeSize = type->GetStride();
  6293. BfIRValue allocaInst;
  6294. BfIRValue result;
  6295. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6296. {
  6297. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6298. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6299. result = allocaInst;
  6300. }
  6301. else
  6302. {
  6303. if (typeInstance->IsStruct())
  6304. typeSize = typeInstance->GetInstStride();
  6305. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6306. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6307. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6308. auto ptrType = CreatePointerType(typeInstance);
  6309. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6310. if (!isDynAlloc)
  6311. mBfIRBuilder->ClearDebugLocation(result);
  6312. }
  6313. if (!isDynAlloc)
  6314. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6315. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6316. if (!isDynAlloc)
  6317. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6318. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6319. if (arraySize.IsConst())
  6320. {
  6321. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6322. if (constant->mInt64 == 0)
  6323. noDtorCall = true;
  6324. }
  6325. if (!noDtorCall)
  6326. {
  6327. bool isConstSize = arraySize.IsConst();
  6328. BfIRBlock clearBlock;
  6329. BfIRBlock contBlock;
  6330. if (!isConstSize)
  6331. {
  6332. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6333. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6334. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6335. mBfIRBuilder->AddBlock(clearBlock);
  6336. mBfIRBuilder->SetInsertPoint(clearBlock);
  6337. }
  6338. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6339. if (!isConstSize)
  6340. {
  6341. mBfIRBuilder->CreateBr(contBlock);
  6342. mBfIRBuilder->AddBlock(contBlock);
  6343. mBfIRBuilder->SetInsertPoint(contBlock);
  6344. }
  6345. }
  6346. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6347. return result;
  6348. }
  6349. }
  6350. else
  6351. {
  6352. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6353. {
  6354. // Generate and check new size
  6355. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6356. auto firstElementField = &arrayType->mFieldInstances.back();
  6357. int arrayClassSize = firstElementField->mDataOffset;
  6358. sizeValue = GetConstValue(arrayClassSize);
  6359. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6360. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6361. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6362. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6363. if (!noDtorCall)
  6364. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6365. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6366. return typedVal.mValue;
  6367. }
  6368. else
  6369. {
  6370. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6371. auto firstElementField = &arrayType->mFieldInstances.back();
  6372. int arrayClassSize = firstElementField->mDataOffset;
  6373. sizeValue = GetConstValue(arrayClassSize);
  6374. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6375. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6376. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6377. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6378. if (!isDynAlloc)
  6379. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6380. else
  6381. {
  6382. MarkDynStack(scopeData);
  6383. SaveStackState(scopeData);
  6384. }
  6385. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6386. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6387. if (!isDynAlloc)
  6388. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6389. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6390. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6391. mBfIRBuilder->ClearDebugLocation_Last();
  6392. if (!isDynAlloc)
  6393. mBfIRBuilder->SetInsertPoint(prevBlock);
  6394. if (!noDtorCall)
  6395. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6396. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6397. return typedVal.mValue;
  6398. }
  6399. }
  6400. }
  6401. else if (appendSizeValue)
  6402. {
  6403. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6404. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6405. // use the "dynSize" version conservatively
  6406. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6407. {
  6408. // Generate and check new size
  6409. sizeValue = GetConstValue(typeInstance->mInstSize);
  6410. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6411. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6412. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6413. if (!noDtorCall)
  6414. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6415. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6416. return typedVal.mValue;
  6417. }
  6418. else // stack alloc, unlooped, with append
  6419. {
  6420. sizeValue = GetConstValue(typeInstance->mInstSize);
  6421. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6422. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6423. bool wasDynAlloc = isDynAlloc;
  6424. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6425. if (!isDynAlloc)
  6426. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6427. else
  6428. {
  6429. MarkDynStack(scopeData);
  6430. SaveStackState(scopeData);
  6431. }
  6432. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6433. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6434. if (!isDynAlloc)
  6435. {
  6436. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6437. }
  6438. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6439. bool mayBeLarge = false;
  6440. if (sizeValue.IsConst())
  6441. {
  6442. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6443. if (constantInt->mInt64 >= 4096)
  6444. mayBeLarge = true;
  6445. }
  6446. else
  6447. mayBeLarge = true;
  6448. if (((type->IsObject() && (!mayBeLarge))) ||
  6449. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6450. ((zeroMemory) && (!mayBeLarge)))
  6451. {
  6452. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6453. }
  6454. BfIRValue castedVal;
  6455. if (!isDynAlloc)
  6456. {
  6457. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6458. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6459. mBfIRBuilder->ClearDebugLocation(castedVal);
  6460. mBfIRBuilder->SetInsertPoint(prevBlock);
  6461. if (WantsLifetimes())
  6462. {
  6463. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6464. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6465. }
  6466. }
  6467. else
  6468. {
  6469. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6470. }
  6471. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6472. if (!noDtorCall)
  6473. {
  6474. bool doCondAlloca = false;
  6475. if (!IsTargetingBeefBackend())
  6476. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6477. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6478. }
  6479. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6480. return typedVal.mValue;
  6481. }
  6482. }
  6483. else // "Normal" stack alloc
  6484. {
  6485. BF_ASSERT(!sizeValue);
  6486. //TODO: If sizeValue is a constant then do this in the head IR builder
  6487. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6488. if (!isLoopedAlloc)
  6489. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6490. else
  6491. {
  6492. MarkDynStack(scopeData);
  6493. SaveStackState(scopeData);
  6494. }
  6495. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6496. if (!isLoopedAlloc)
  6497. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6498. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6499. bool mayBeLarge = allocSize >= 4096;
  6500. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6501. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6502. ((zeroMemory) && (!mayBeLarge)))
  6503. {
  6504. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6505. // and memset is always safe
  6506. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6507. }
  6508. auto typedVal = BfTypedValue(allocaInst, type);
  6509. if (!isLoopedAlloc)
  6510. {
  6511. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6512. mBfIRBuilder->SetInsertPoint(prevBlock);
  6513. if (WantsLifetimes())
  6514. {
  6515. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6516. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6517. }
  6518. }
  6519. if (!noDtorCall)
  6520. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6521. if (typeInstance != NULL)
  6522. {
  6523. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6524. }
  6525. else
  6526. {
  6527. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6528. }
  6529. return allocaInst;
  6530. }
  6531. }
  6532. else if (arraySize)
  6533. {
  6534. if (isRawArrayAlloc)
  6535. {
  6536. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6537. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6538. }
  6539. else
  6540. {
  6541. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6542. typeInstance = arrayType;
  6543. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6544. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6545. appendSizeValue = elementDataSize;
  6546. if (!type->IsSizeAligned())
  6547. {
  6548. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6549. }
  6550. }
  6551. }
  6552. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6553. {
  6554. auto vDataRef = GetClassVDataPtr(typeInstance);
  6555. BfIRValue result;
  6556. bool isResultInitialized = false;
  6557. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6558. if (typeInstance->mTypeOptionsIdx != -1)
  6559. {
  6560. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6561. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6562. }
  6563. if (!sizeValue)
  6564. sizeValue = GetConstValue(typeInstance->mInstSize);
  6565. if (appendSizeValue)
  6566. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6567. BfIRValue origSizeValue = sizeValue;
  6568. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6569. if (isAllocEx)
  6570. {
  6571. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6572. if (prepareStackTraceMethod)
  6573. {
  6574. SizedArray<BfIRValue, 2> irArgs;
  6575. irArgs.Add(sizeValue);
  6576. irArgs.Add(GetConstValue(stackCount));
  6577. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6578. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6579. }
  6580. }
  6581. if (allocTarget.mCustomAllocator)
  6582. {
  6583. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6584. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6585. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6586. {
  6587. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6588. mBfIRBuilder->PopulateType(classVDataType);
  6589. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6590. mBfIRBuilder->PopulateType(typeInstType);
  6591. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6592. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6593. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6594. BfTypedValueExpression typedValueExpr;
  6595. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6596. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6597. BfExprEvaluator exprEvaluator(this);
  6598. SizedArray<BfExpression*, 2> argExprs;
  6599. argExprs.push_back(&typedValueExpr);
  6600. BfTypedValueExpression sizeValueExpr;
  6601. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6602. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6603. argExprs.push_back(&sizeValueExpr);
  6604. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6605. BfResolvedArgs argValues(&sizedArgExprs);
  6606. exprEvaluator.ResolveArgValues(argValues);
  6607. exprEvaluator.mNoBind = true;
  6608. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6609. if (allocResult)
  6610. {
  6611. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6612. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6613. else
  6614. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6615. isResultInitialized = true;
  6616. }
  6617. }
  6618. }
  6619. if (!result)
  6620. {
  6621. if (hasCustomAllocator)
  6622. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6623. }
  6624. if (result)
  6625. {
  6626. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6627. {
  6628. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6629. SizedArray<BfIRValue, 4> llvmArgs;
  6630. llvmArgs.push_back(objectPtr);
  6631. llvmArgs.push_back(origSizeValue);
  6632. llvmArgs.push_back(vDataRef);
  6633. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6634. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6635. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6636. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6637. }
  6638. else
  6639. {
  6640. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6641. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6642. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6643. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6644. }
  6645. }
  6646. else
  6647. {
  6648. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6649. return GetDefaultValue(typeInstance);
  6650. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6651. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6652. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6653. {
  6654. SizedArray<BfIRValue, 4> llvmArgs;
  6655. llvmArgs.push_back(vData);
  6656. llvmArgs.push_back(sizeValue);
  6657. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6658. llvmArgs.push_back(GetConstValue(stackCount));
  6659. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6660. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6661. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6662. }
  6663. else
  6664. {
  6665. SizedArray<BfIRValue, 4> llvmArgs;
  6666. llvmArgs.push_back(sizeValue);
  6667. BfIRFunction irFunc;
  6668. if (mCompiler->mOptions.mDebugAlloc)
  6669. {
  6670. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6671. irFunc = moduleMethodInstance.mFunc;
  6672. }
  6673. if (!irFunc)
  6674. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6675. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6676. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6677. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6678. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6679. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6680. }
  6681. }
  6682. if ((zeroMemory) && (arraySize))
  6683. {
  6684. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6685. typeInstance = arrayType;
  6686. auto firstElementField = &arrayType->mFieldInstances.back();
  6687. int arrayClassSize = firstElementField->mDataOffset;
  6688. BfIRValue elementDataSize;
  6689. bool skipZero = false;
  6690. if (arraySize.IsConst())
  6691. {
  6692. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6693. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6694. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6695. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6696. if (constVal->mInt64 <= 0)
  6697. skipZero = true;
  6698. }
  6699. else
  6700. {
  6701. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6702. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6703. }
  6704. if (!skipZero)
  6705. {
  6706. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6707. auto ptrType = CreatePointerType(i8Type);
  6708. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6709. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6710. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6711. appendSizeValue = elementDataSize;
  6712. }
  6713. }
  6714. return result;
  6715. }
  6716. else
  6717. {
  6718. if (!sizeValue)
  6719. sizeValue = GetConstValue(allocSize);
  6720. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6721. }
  6722. }
  6723. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6724. {
  6725. if ((type == NULL) || (refNode == NULL))
  6726. return;
  6727. auto typeInstance = type->ToTypeInstance();
  6728. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6729. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6730. }
  6731. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6732. {
  6733. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6734. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6735. }
  6736. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6737. {
  6738. if (sizeMultiple == 0)
  6739. sizeMultiple = align;
  6740. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6741. {
  6742. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6743. {
  6744. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6745. BF_ASSERT(localVar->mName == "appendIdx");
  6746. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6747. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6748. if (align > 1)
  6749. {
  6750. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6751. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6752. }
  6753. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6754. }
  6755. else
  6756. {
  6757. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6758. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6759. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6760. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6761. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6762. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6763. }
  6764. }
  6765. if (mCurMethodState->mCurAppendAlign == 0)
  6766. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6767. else
  6768. {
  6769. if (sizeMultiple % align == 0)
  6770. mCurMethodState->mCurAppendAlign = align;
  6771. else
  6772. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6773. }
  6774. }
  6775. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6776. {
  6777. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6778. BF_ASSERT(localVar->mName == "appendIdx");
  6779. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6780. BfIRValue retValue;
  6781. BfTypeInstance* retTypeInstance = NULL;
  6782. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6783. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6784. if (arraySize)
  6785. {
  6786. if (isRawArrayAlloc)
  6787. {
  6788. EmitAppendAlign(type->mAlign);
  6789. BfPointerType* ptrType = CreatePointerType(type);
  6790. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6791. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6792. if (mSystem->mPtrSize != 4)
  6793. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6794. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6795. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6796. if (zeroMemory)
  6797. {
  6798. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6799. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6800. }
  6801. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6802. }
  6803. else
  6804. {
  6805. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6806. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6807. auto firstElementField = &arrayType->mFieldInstances.back();
  6808. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6809. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6810. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6811. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6812. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6813. if (mSystem->mPtrSize != 4)
  6814. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6815. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6816. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6817. if (zeroMemory)
  6818. {
  6819. // Only zero out the actual elements
  6820. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6821. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6822. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6823. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6824. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6825. }
  6826. retTypeInstance = arrayType;
  6827. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6828. }
  6829. }
  6830. else
  6831. {
  6832. auto typeInst = type->ToTypeInstance();
  6833. BfIRValue sizeValue;
  6834. BfIRType toType;
  6835. if (typeInst != NULL)
  6836. {
  6837. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6838. sizeValue = GetConstValue(typeInst->mInstSize);
  6839. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6840. }
  6841. else
  6842. {
  6843. EmitAppendAlign(type->mAlign, type->mSize);
  6844. sizeValue = GetConstValue(type->mSize);
  6845. auto toPtrType = CreatePointerType(type);
  6846. toType = mBfIRBuilder->MapType(toPtrType);
  6847. }
  6848. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6849. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6850. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6851. retTypeInstance = typeInst;
  6852. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6853. }
  6854. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6855. {
  6856. mBfIRBuilder->PopulateType(retTypeInstance);
  6857. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6858. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6859. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6860. auto curThis = GetThis();
  6861. BfIRValue newFlags;
  6862. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6863. {
  6864. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6865. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6866. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6867. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6868. }
  6869. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6870. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6871. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6872. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6873. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6874. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6875. {
  6876. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6877. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6878. }
  6879. }
  6880. if (appendSizeValue)
  6881. {
  6882. EmitAppendAlign(appendAllocAlign);
  6883. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6884. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6885. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6886. }
  6887. return retValue;
  6888. }
  6889. bool BfModule::IsOptimized()
  6890. {
  6891. if (mProject == NULL)
  6892. return false;
  6893. int optLevel = GetModuleOptions().mOptLevel;
  6894. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6895. }
  6896. bool BfModule::IsTargetingBeefBackend()
  6897. {
  6898. if (mProject == NULL)
  6899. return false;
  6900. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6901. }
  6902. bool BfModule::WantsLifetimes()
  6903. {
  6904. if (mProject == NULL)
  6905. return false;
  6906. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6907. }
  6908. bool BfModule::HasCompiledOutput()
  6909. {
  6910. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6911. }
  6912. // We will skip the object access check for any occurances of this value
  6913. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6914. {
  6915. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6916. return;
  6917. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6918. return;
  6919. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6920. return;
  6921. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6922. }
  6923. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6924. {
  6925. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6926. return;
  6927. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6928. return;
  6929. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6930. auto typeOptions = GetTypeOptions();
  6931. if (typeOptions != NULL)
  6932. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6933. if (!emitObjectAccessCheck)
  6934. return;
  6935. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6936. {
  6937. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6938. return;
  6939. }
  6940. if (typedVal.IsAddr())
  6941. typedVal = LoadValue(typedVal);
  6942. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6943. }
  6944. void BfModule::EmitEnsureInstructionAt()
  6945. {
  6946. if (mProject == NULL)
  6947. return;
  6948. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  6949. return;
  6950. mBfIRBuilder->CreateEnsureInstructionAt();
  6951. }
  6952. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6953. {
  6954. if (mBfIRBuilder->mIgnoreWrites)
  6955. return; // Nothing needed here
  6956. auto irb = mBfIRBuilder;
  6957. auto checkBB = irb->CreateBlock("as.check");
  6958. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6959. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6960. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6961. auto intPtrType = CreatePointerType(intType);
  6962. auto intPtrPtrType = CreatePointerType(intPtrType);
  6963. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6964. auto int32PtrType = CreatePointerType(int32Type);
  6965. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6966. if (mCompiler->mOptions.mAllowHotSwapping)
  6967. {
  6968. BfExprEvaluator exprEvaluator(this);
  6969. AddBasicBlock(checkBB);
  6970. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6971. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  6972. SizedArray<BfIRValue, 4> irArgs;
  6973. irArgs.push_back(objectParam);
  6974. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  6975. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  6976. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  6977. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  6978. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  6979. }
  6980. else
  6981. {
  6982. AddBasicBlock(checkBB);
  6983. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  6984. vDataPtr = irb->CreateLoad(vDataPtr);
  6985. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6986. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6987. if (targetType->IsInterface())
  6988. {
  6989. auto targetTypeInst = targetType->ToTypeInstance();
  6990. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6991. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  6992. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  6993. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  6994. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  6995. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  6996. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  6997. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  6998. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  6999. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7000. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7001. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7002. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7003. }
  7004. else
  7005. {
  7006. if (!targetType->IsTypeInstance())
  7007. targetType = GetWrappedStructType(targetType);
  7008. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7009. int inheritanceIdOfs = mSystem->mPtrSize;
  7010. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7011. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7012. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7013. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7014. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7015. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7016. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7017. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7018. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7019. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7020. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7021. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7022. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7023. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7024. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7025. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7026. }
  7027. }
  7028. }
  7029. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7030. {
  7031. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7032. auto typeOptions = GetTypeOptions();
  7033. if (typeOptions != NULL)
  7034. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7035. if (emitDynamicCastCheck)
  7036. {
  7037. int wantTypeId = 0;
  7038. if (!type->IsGenericParam())
  7039. wantTypeId = type->mTypeId;
  7040. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7041. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7042. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7043. AddBasicBlock(failBlock);
  7044. SizedArray<BfIRValue, 8> llvmArgs;
  7045. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7046. llvmArgs.push_back(bitAddr);
  7047. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7048. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7049. BF_ASSERT(objDynCheck);
  7050. if (objDynCheck)
  7051. {
  7052. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7053. }
  7054. mBfIRBuilder->CreateBr(endBlock);
  7055. AddBasicBlock(endBlock);
  7056. }
  7057. }
  7058. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7059. {
  7060. BP_ZONE("BoxValue");
  7061. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7062. if (typedVal.mType->IsNullable())
  7063. {
  7064. typedVal = MakeAddressable(typedVal);
  7065. auto innerType = typedVal.mType->GetUnderlyingType();
  7066. if (!innerType->IsValueType())
  7067. {
  7068. Fail("Only value types can be boxed", srcNode);
  7069. return BfTypedValue();
  7070. }
  7071. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7072. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7073. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7074. mBfIRBuilder->PopulateType(typedVal.mType);
  7075. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7076. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7077. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7078. auto boxedType = CreateBoxedType(innerType);
  7079. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7080. auto resultType = toType;
  7081. if (resultType == NULL)
  7082. resultType = boxedType;
  7083. mBfIRBuilder->AddBlock(boxBB);
  7084. mBfIRBuilder->SetInsertPoint(boxBB);
  7085. BfScopeData newScope;
  7086. newScope.mOuterIsConditional = true;
  7087. mCurMethodState->AddScope(&newScope);
  7088. NewScopeState();
  7089. BfIRValue nullableValueAddr;
  7090. BfIRValue loadedVal;
  7091. if (innerType->IsValuelessType())
  7092. {
  7093. loadedVal = mBfIRBuilder->GetFakeVal();
  7094. }
  7095. else
  7096. {
  7097. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7098. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7099. }
  7100. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7101. RestoreScopeState();
  7102. if (!boxedVal)
  7103. return BfTypedValue();
  7104. mBfIRBuilder->CreateBr(endBB);
  7105. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7106. mBfIRBuilder->AddBlock(endBB);
  7107. mBfIRBuilder->SetInsertPoint(endBB);
  7108. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7109. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7110. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7111. return BfTypedValue(phi, resultType);
  7112. }
  7113. bool alreadyCheckedCast = false;
  7114. BfTypeInstance* toTypeInstance = NULL;
  7115. if (toType != NULL)
  7116. toTypeInstance = toType->ToTypeInstance();
  7117. bool isStructPtr = typedVal.mType->IsStructPtr();
  7118. if (fromStructTypeInstance == NULL)
  7119. {
  7120. auto primType = (BfPrimitiveType*)typedVal.mType;
  7121. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7122. if (isStructPtr)
  7123. {
  7124. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7125. alreadyCheckedCast = true;
  7126. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7127. }
  7128. }
  7129. if (fromStructTypeInstance == NULL)
  7130. return BfTypedValue();
  7131. // Need to box it
  7132. auto boxedType = CreateBoxedType(typedVal.mType);
  7133. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (boxedType == toType);
  7134. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7135. {
  7136. if (typedVal.mType->IsPointer())
  7137. {
  7138. NOP;
  7139. }
  7140. mBfIRBuilder->PopulateType(boxedType);
  7141. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7142. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7143. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7144. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7145. if (boxedType->IsUnspecializedType())
  7146. {
  7147. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7148. }
  7149. else
  7150. {
  7151. PopulateType(fromStructTypeInstance);
  7152. if (!fromStructTypeInstance->IsValuelessType())
  7153. {
  7154. typedVal = LoadValue(typedVal);
  7155. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7156. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7157. {
  7158. auto ptrType = CreatePointerType(typedVal.mType);
  7159. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7160. }
  7161. if (typedVal.IsSplat())
  7162. {
  7163. AggregateSplatIntoAddr(typedVal, valPtr);
  7164. }
  7165. else
  7166. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7167. }
  7168. }
  7169. if (toType == NULL)
  7170. {
  7171. return BfTypedValue(allocaInst, boxedType);
  7172. }
  7173. else
  7174. {
  7175. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7176. return BfTypedValue(castedValue, toType);
  7177. }
  7178. }
  7179. return BfTypedValue();
  7180. }
  7181. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7182. {
  7183. BfTypeInstance* checkTypeInst = typeInst;
  7184. while (checkTypeInst != NULL)
  7185. {
  7186. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7187. {
  7188. if (checkProp->mName == propDef->mName)
  7189. {
  7190. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7191. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7192. {
  7193. propDef = checkProp;
  7194. typeInst = checkTypeInst;
  7195. return true;
  7196. }
  7197. }
  7198. }
  7199. checkTypeInst = checkTypeInst->mBaseType;
  7200. }
  7201. return false;
  7202. }
  7203. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7204. {
  7205. if (!typeInstance->mResolvingVarField)
  7206. {
  7207. if (typeInstance->IsIncomplete())
  7208. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7209. }
  7210. else
  7211. {
  7212. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7213. {
  7214. AssertErrorState();
  7215. return NULL;
  7216. }
  7217. }
  7218. if (assertName != NULL)
  7219. {
  7220. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7221. }
  7222. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7223. if (methodGroup.mDefault == NULL)
  7224. {
  7225. if (!mCompiler->mIsResolveOnly)
  7226. {
  7227. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7228. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7229. // Get it from the owning module so we don't create a reference prematurely...
  7230. auto declModule = typeInstance->mModule;
  7231. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7232. }
  7233. else
  7234. {
  7235. auto declModule = typeInstance->mModule;
  7236. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7237. }
  7238. }
  7239. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7240. //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
  7241. // be from a call to the NON-raw version
  7242. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7243. // {
  7244. // methodInstance->mIsReified = mIsReified;
  7245. // if (methodInstance->mMethodProcessRequest == NULL)
  7246. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7247. // }
  7248. return methodInstance;
  7249. }
  7250. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7251. {
  7252. if (methodDef->mIsLocalMethod)
  7253. {
  7254. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7255. }
  7256. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7257. }
  7258. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7259. {
  7260. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7261. while (typeInstance != NULL)
  7262. {
  7263. typeInstance->mTypeDef->PopulateMemberSets();
  7264. BfMemberSetEntry* entry = NULL;
  7265. BfMethodDef* methodDef = NULL;
  7266. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7267. methodDef = (BfMethodDef*)entry->mMemberDef;
  7268. while (methodDef != NULL)
  7269. {
  7270. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7271. (methodDef->mGenericParams.size() == 0) &&
  7272. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7273. return GetRawMethodInstance(typeInstance, methodDef);
  7274. methodDef = methodDef->mNextWithSameName;
  7275. }
  7276. if (!checkBase)
  7277. break;
  7278. typeInstance = typeInstance->mBaseType;
  7279. }
  7280. return NULL;
  7281. }
  7282. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7283. {
  7284. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7285. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7286. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7287. if (!owner->IsGenericTypeInstance())
  7288. return methodInstance;
  7289. auto genericType = (BfGenericTypeInstance*)owner;
  7290. if (genericType->IsUnspecializedType())
  7291. return methodInstance;
  7292. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7293. if (unspecializedType == NULL)
  7294. {
  7295. AssertErrorState();
  7296. return methodInstance;
  7297. }
  7298. if (unspecializedType == NULL)
  7299. return methodInstance;
  7300. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7301. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7302. }
  7303. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7304. {
  7305. int genericCount = 0;
  7306. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7307. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7308. {
  7309. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7310. if (param->IsGenericParam())
  7311. genericCount++;
  7312. }
  7313. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7314. genericCount++;
  7315. return genericCount;
  7316. }
  7317. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7318. {
  7319. BF_ASSERT(!mIsScratchModule);
  7320. BF_ASSERT(mIsReified);
  7321. BfModule* mainModule = this;
  7322. if (mParentModule != NULL)
  7323. mainModule = mParentModule;
  7324. BfModule* specModule = NULL;
  7325. BfModule** specModulePtr = NULL;
  7326. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7327. {
  7328. return *specModulePtr;
  7329. }
  7330. else
  7331. {
  7332. String specModuleName = mModuleName;
  7333. for (auto bfProject : projectList)
  7334. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7335. specModule = new BfModule(mContext, specModuleName);
  7336. specModule->mProject = mainModule->mProject;
  7337. specModule->mParentModule = mainModule;
  7338. specModule->mIsSpecializedMethodModuleRoot = true;
  7339. specModule->Init();
  7340. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7341. }
  7342. return specModule;
  7343. }
  7344. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7345. {
  7346. if (mCompiler->IsSkippingExtraResolveChecks())
  7347. return BfIRValue();
  7348. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7349. {
  7350. //BF_ASSERT(!methodInstance->mIRFunction);
  7351. return BfIRValue();
  7352. }
  7353. auto methodDef = methodInstance->mMethodDef;
  7354. StringT<128> methodName;
  7355. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7356. if (isInlined != methodInstance->mAlwaysInline)
  7357. {
  7358. if (isInlined)
  7359. methodName += "__INLINE";
  7360. else
  7361. methodName += "__NOINLINE";
  7362. }
  7363. if (tryExisting)
  7364. {
  7365. auto func = mBfIRBuilder->GetFunction(methodName);
  7366. if (func)
  7367. return func;
  7368. }
  7369. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7370. {
  7371. if (methodDeclaration->mExternSpecifier != NULL)
  7372. {
  7373. auto intrinsic = GetIntrinsic(methodInstance);
  7374. if (intrinsic)
  7375. return intrinsic;
  7376. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7377. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7378. if (func)
  7379. return func;*/
  7380. }
  7381. }
  7382. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7383. {
  7384. return CreateDllImportGlobalVar(methodInstance, false);
  7385. }
  7386. BfIRType returnType;
  7387. SizedArray<BfIRType, 8> paramTypes;
  7388. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7389. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7390. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7391. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7392. if (callingConv != BfIRCallingConv_CDecl)
  7393. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7394. SetupIRMethod(methodInstance, func, isInlined);
  7395. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7396. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7397. // {
  7398. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7399. // {
  7400. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7401. // }
  7402. // }
  7403. return func;
  7404. }
  7405. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7406. {
  7407. if (assertName != NULL)
  7408. {
  7409. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7410. }
  7411. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7412. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7413. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7414. {
  7415. // Can't use it, not reified
  7416. methodInstance = NULL;
  7417. }
  7418. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7419. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7420. {
  7421. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7422. return BfModuleMethodInstance(methodInstance, func);
  7423. }
  7424. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7425. }
  7426. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7427. {
  7428. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7429. while (typeInstance != NULL)
  7430. {
  7431. typeInstance->mTypeDef->PopulateMemberSets();
  7432. BfMemberSetEntry* entry = NULL;
  7433. BfMethodDef* methodDef = NULL;
  7434. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7435. methodDef = (BfMethodDef*)entry->mMemberDef;
  7436. while (methodDef != NULL)
  7437. {
  7438. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7439. (methodDef->mGenericParams.size() == 0) &&
  7440. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7441. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7442. methodDef = methodDef->mNextWithSameName;
  7443. }
  7444. if (!checkBase)
  7445. break;
  7446. typeInstance = typeInstance->mBaseType;
  7447. }
  7448. return BfModuleMethodInstance();
  7449. }
  7450. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7451. {
  7452. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7453. while (typeInstance != NULL)
  7454. {
  7455. typeInstance->mTypeDef->PopulateMemberSets();
  7456. BfMemberSetEntry* entry = NULL;
  7457. BfMethodDef* methodDef = NULL;
  7458. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7459. methodDef = (BfMethodDef*)entry->mMemberDef;
  7460. while (methodDef != NULL)
  7461. {
  7462. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7463. (methodDef->mGenericParams.size() == 0) &&
  7464. (paramTypes.size() == methodDef->mParams.size()))
  7465. {
  7466. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7467. if (moduleMethodInstance.mMethodInstance != NULL)
  7468. {
  7469. bool matches = true;
  7470. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7471. {
  7472. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7473. matches = false;
  7474. }
  7475. if (matches)
  7476. return moduleMethodInstance;
  7477. }
  7478. }
  7479. methodDef = methodDef->mNextWithSameName;
  7480. }
  7481. if (!checkBase)
  7482. break;
  7483. typeInstance = typeInstance->mBaseType;
  7484. }
  7485. return BfModuleMethodInstance();
  7486. }
  7487. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7488. {
  7489. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7490. PopulateType(internalType);
  7491. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7492. if (!moduleMethodInstance)
  7493. {
  7494. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7495. }
  7496. return moduleMethodInstance;
  7497. }
  7498. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7499. {
  7500. while (typeInstance != NULL)
  7501. {
  7502. typeInstance->mTypeDef->PopulateMemberSets();
  7503. BfMemberSetEntry* entry = NULL;
  7504. BfMethodDef* methodDef = NULL;
  7505. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7506. methodDef = (BfMethodDef*)entry->mMemberDef;
  7507. while (methodDef != NULL)
  7508. {
  7509. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7510. (methodDef->mGenericParams.size() == 0) &&
  7511. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7512. {
  7513. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7514. if (!methodInstanceGroup.IsImplemented())
  7515. return false;
  7516. if (methodInstanceGroup.mDefault == NULL)
  7517. return false;
  7518. return methodInstanceGroup.mDefault->mIsReified;
  7519. }
  7520. methodDef = methodDef->mNextWithSameName;
  7521. }
  7522. if (!checkBase)
  7523. break;
  7524. typeInstance = typeInstance->mBaseType;
  7525. }
  7526. return false;
  7527. }
  7528. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7529. {
  7530. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7531. while (typeInstance != NULL)
  7532. {
  7533. typeInstance->mTypeDef->PopulateMemberSets();
  7534. BfMemberSetEntry* entry = NULL;
  7535. BfMethodDef* methodDef = NULL;
  7536. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7537. methodDef = (BfMethodDef*)entry->mMemberDef;
  7538. while (methodDef != NULL)
  7539. {
  7540. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7541. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7542. return true;
  7543. methodDef = methodDef->mNextWithSameName;
  7544. }
  7545. if (!checkBase)
  7546. break;
  7547. typeInstance = typeInstance->mBaseType;
  7548. }
  7549. return BfModuleMethodInstance();
  7550. }
  7551. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7552. {
  7553. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7554. typeInstance->mTypeDef->PopulateMemberSets();
  7555. BfMemberSetEntry* entry = NULL;
  7556. BfFieldDef* fieldDef = NULL;
  7557. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7558. {
  7559. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7560. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7561. }
  7562. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7563. // {
  7564. // auto fieldDef = fieldInst.GetFieldDef();
  7565. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7566. // return &fieldInst;
  7567. // }
  7568. return NULL;
  7569. }
  7570. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7571. {
  7572. auto methodDef = methodInst->mMethodDef;
  7573. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7574. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7575. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7576. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7577. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7578. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7579. type = ResolveGenericType(type, *methodGenericArgs);
  7580. String methodName;
  7581. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7582. {
  7583. methodName = TypeToString(type, typeNameFlags);
  7584. if (methodName == "$")
  7585. methodName = "";
  7586. else
  7587. methodName += ".";
  7588. }
  7589. String accessorString;
  7590. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7591. if (methodInst->mMethodDef->mIsLocalMethod)
  7592. {
  7593. int atPos = (int)methodDefName.IndexOf('$');
  7594. methodDefName.RemoveToEnd(atPos);
  7595. methodDefName.Replace("@", ".");
  7596. }
  7597. else
  7598. {
  7599. int atPos = (int)methodDefName.IndexOf('$');
  7600. if (atPos != -1)
  7601. {
  7602. accessorString = methodDefName.Substring(0, atPos);
  7603. if ((accessorString == "get") || (accessorString == "set"))
  7604. {
  7605. methodDefName = methodDefName.Substring(atPos + 1);
  7606. }
  7607. else
  7608. accessorString = "";
  7609. }
  7610. }
  7611. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7612. {
  7613. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7614. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7615. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7616. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7617. methodName += ".";
  7618. }
  7619. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7620. {
  7621. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7622. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7623. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7624. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7625. methodName += ".";
  7626. }
  7627. if (methodDef->mMethodType == BfMethodType_Operator)
  7628. {
  7629. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7630. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7631. {
  7632. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7633. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7634. {
  7635. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7636. methodName += "explicit ";
  7637. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7638. methodName += "explicit ";
  7639. }*/
  7640. methodName += "operator ";
  7641. if (methodInst->mReturnType != NULL)
  7642. methodName += TypeToString(methodInst->mReturnType);
  7643. }
  7644. else
  7645. {
  7646. methodName += "operator";
  7647. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7648. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7649. }
  7650. }
  7651. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7652. {
  7653. if (methodDef->mIsStatic)
  7654. methodName += "__BfStaticCtor";
  7655. else
  7656. methodName += "this";
  7657. accessorString = "";
  7658. }
  7659. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7660. {
  7661. methodDef->GetRefNode()->ToString(methodName);
  7662. methodName += " get accessor";
  7663. return methodName;
  7664. }
  7665. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7666. {
  7667. methodDef->GetRefNode()->ToString(methodName);
  7668. methodName += " set accessor";
  7669. return methodName;
  7670. }
  7671. else
  7672. methodName += methodDefName;
  7673. BfTypeVector newMethodGenericArgs;
  7674. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7675. {
  7676. methodName += "<";
  7677. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7678. {
  7679. if (i > 0)
  7680. methodName += ", ";
  7681. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7682. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7683. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7684. if (allowResolveGenericParamNames)
  7685. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7686. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7687. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7688. {
  7689. bool hasEmpty = false;
  7690. for (auto arg : *methodGenericArgs)
  7691. {
  7692. if (arg == NULL)
  7693. hasEmpty = true;
  7694. }
  7695. if (hasEmpty)
  7696. {
  7697. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7698. {
  7699. auto arg = (*methodGenericArgs)[genericIdx];
  7700. if (arg != NULL)
  7701. newMethodGenericArgs.push_back(arg);
  7702. else
  7703. {
  7704. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7705. if (genericParamInst->mTypeConstraint != NULL)
  7706. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7707. else
  7708. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7709. }
  7710. }
  7711. methodGenericArgs = &newMethodGenericArgs;
  7712. }
  7713. if (type->IsUnspecializedType())
  7714. type = ResolveGenericType(type, *methodGenericArgs);
  7715. }
  7716. methodName += TypeToString(type, typeNameFlags);
  7717. }
  7718. methodName += ">";
  7719. }
  7720. if (accessorString.length() == 0)
  7721. {
  7722. int dispParamIdx = 0;
  7723. methodName += "(";
  7724. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7725. {
  7726. int paramKind = methodInst->GetParamKind(paramIdx);
  7727. if (paramKind == BfParamKind_ImplicitCapture)
  7728. continue;
  7729. if (dispParamIdx > 0)
  7730. methodName += ", ";
  7731. if (paramKind == BfParamKind_Params)
  7732. methodName += "params ";
  7733. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7734. BfType* type = methodInst->GetParamType(paramIdx);
  7735. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7736. type = ResolveGenericType(type, *methodGenericArgs);
  7737. methodName += TypeToString(type, typeNameFlags);
  7738. methodName += " ";
  7739. methodName += methodInst->GetParamName(paramIdx);
  7740. dispParamIdx++;
  7741. }
  7742. methodName += ")";
  7743. }
  7744. if (accessorString.length() != 0)
  7745. {
  7746. methodName += " " + accessorString;
  7747. }
  7748. return methodName;
  7749. }
  7750. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7751. {
  7752. if ((flagsLeft & checkFlag) == 0)
  7753. return;
  7754. if (!str.empty())
  7755. {
  7756. if (flagsLeft == checkFlag)
  7757. {
  7758. if ((int)str.IndexOf(',') != -1)
  7759. str += ", and ";
  7760. else
  7761. str += " and ";
  7762. }
  7763. else
  7764. str += ", ";
  7765. }
  7766. str += addString;
  7767. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7768. }
  7769. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7770. {
  7771. String resultStr;
  7772. auto flagsLeft = attrTarget;
  7773. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7774. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7775. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7776. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7777. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7778. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7779. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7780. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7781. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7782. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7783. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7784. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7785. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7786. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7787. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7788. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7789. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7790. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7791. if (resultStr.IsEmpty())
  7792. return "<nothing>";
  7793. return resultStr;
  7794. }
  7795. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7796. {
  7797. auto constant = mBfIRBuilder->GetConstant(irVal);
  7798. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7799. if (stringPoolIdx != -1)
  7800. {
  7801. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7802. return;
  7803. }
  7804. if (constant->mConstType == BfConstType_Array)
  7805. {
  7806. auto constArray = (BfConstantArray*)constant;
  7807. SizedArray<BfIRValue, 8> newVals;
  7808. for (auto val : constArray->mValues)
  7809. {
  7810. auto newVal = val;
  7811. CurrentAddToConstHolder(newVal);
  7812. newVals.push_back(newVal);
  7813. }
  7814. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7815. return;
  7816. }
  7817. auto origConst = irVal;
  7818. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7819. {
  7820. auto bitcast = (BfConstantBitCast*)constant;
  7821. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7822. }
  7823. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7824. }
  7825. void BfModule::ClearConstData()
  7826. {
  7827. mBfIRBuilder->ClearConstData();
  7828. mStringObjectPool.Clear();
  7829. mStringCharPtrPool.Clear();
  7830. mStringPoolRefs.Clear();
  7831. }
  7832. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7833. {
  7834. bool isString = false;
  7835. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7836. if (wantType->IsPointer())
  7837. isString = true;
  7838. if (!isString)
  7839. {
  7840. switch (constant->mTypeCode)
  7841. {
  7842. case BfTypeCode_Boolean:
  7843. case BfTypeCode_Int8:
  7844. case BfTypeCode_UInt8:
  7845. case BfTypeCode_Int16:
  7846. case BfTypeCode_UInt16:
  7847. case BfTypeCode_Int32:
  7848. case BfTypeCode_UInt32:
  7849. case BfTypeCode_Int64:
  7850. case BfTypeCode_UInt64:
  7851. case BfTypeCode_IntPtr:
  7852. case BfTypeCode_UIntPtr:
  7853. case BfTypeCode_IntUnknown:
  7854. case BfTypeCode_UIntUnknown:
  7855. case BfTypeCode_Char8:
  7856. case BfTypeCode_Char16:
  7857. case BfTypeCode_Char32:
  7858. case BfTypeCode_Single:
  7859. case BfTypeCode_Double:
  7860. {
  7861. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7862. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7863. if (typedValue.mType == wantType)
  7864. return typedValue;
  7865. if (wantType->IsTypedPrimitive())
  7866. {
  7867. if (typedValue.mType == wantType->GetUnderlyingType())
  7868. {
  7869. typedValue.mType = wantType;
  7870. return typedValue;
  7871. }
  7872. }
  7873. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7874. BF_ASSERT(castedTypedValue);
  7875. return castedTypedValue;
  7876. }
  7877. break;
  7878. default: break;
  7879. }
  7880. }
  7881. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7882. BF_ASSERT(irValue);
  7883. if (!irValue)
  7884. return BfTypedValue();
  7885. return BfTypedValue(irValue, wantType, false);
  7886. }
  7887. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7888. {
  7889. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7890. {
  7891. return GetDefaultValue(wantType);
  7892. }
  7893. bool isString = false;
  7894. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7895. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7896. {
  7897. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7898. BfIRValue stringObjConst = GetStringObjectValue(str);
  7899. if (wantType->IsObject())
  7900. return stringObjConst;
  7901. return GetStringCharPtr(stringObjConst);
  7902. }
  7903. if (constant->mConstType == BfConstType_Array)
  7904. {
  7905. auto elementType = wantType->GetUnderlyingType();
  7906. auto constArray = (BfConstantArray*)constant;
  7907. SizedArray<BfIRValue, 8> newVals;
  7908. for (auto val : constArray->mValues)
  7909. {
  7910. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7911. }
  7912. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7913. }
  7914. return mBfIRBuilder->CreateConst(constant, constHolder);
  7915. }
  7916. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7917. {
  7918. if (attrTarget == BfAttributeTargets_SkipValidate)
  7919. return;
  7920. for (auto& customAttribute : customAttributes->mAttributes)
  7921. {
  7922. if (!customAttribute.mAwaitingValidation)
  7923. continue;
  7924. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7925. {
  7926. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7927. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7928. }
  7929. customAttribute.mAwaitingValidation = false;
  7930. }
  7931. }
  7932. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7933. {
  7934. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7935. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7936. {
  7937. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7938. }
  7939. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7940. if (mCompiler->IsAutocomplete())
  7941. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7942. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7943. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7944. BfAutoComplete* autoComplete = NULL;
  7945. if (mCompiler->mResolvePassData != NULL)
  7946. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7947. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7948. {
  7949. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7950. BfCustomAttribute customAttribute;
  7951. customAttribute.mAwaitingValidation = true;
  7952. customAttribute.mRef = attributesDirective;
  7953. if (attributesDirective->mAttrOpenToken != NULL)
  7954. targetOverride = (BfAttributeTargets)0;
  7955. if (attributesDirective->mAttributeTypeRef == NULL)
  7956. {
  7957. AssertErrorState();
  7958. continue;
  7959. }
  7960. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7961. BfType* attrType = NULL;
  7962. BfAtomComposite nameComposite;
  7963. BfTypeDef* attrTypeDef = NULL;
  7964. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7965. {
  7966. BfTypeLookupError error;
  7967. error.mRefNode = attributesDirective->mAttributeTypeRef;
  7968. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  7969. }
  7970. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  7971. {
  7972. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  7973. if (attrTypeDef != NULL)
  7974. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  7975. }
  7976. if (attrTypeDef == NULL)
  7977. {
  7978. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  7979. continue;
  7980. }
  7981. bool isBypassedAttr = false;
  7982. if (attrTypeDef != NULL)
  7983. {
  7984. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  7985. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  7986. // We solve it by having a 'bypass' for known attributes that Object depends on
  7987. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  7988. {
  7989. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  7990. {
  7991. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  7992. for (auto methodDef : attrTypeDef->mMethods)
  7993. {
  7994. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  7995. {
  7996. customAttribute.mType = attrType->ToTypeInstance();
  7997. customAttribute.mCtor = methodDef;
  7998. isBypassedAttr = true;
  7999. break;
  8000. }
  8001. }
  8002. }
  8003. }
  8004. if (isBypassedAttr)
  8005. {
  8006. customAttribute.mAwaitingValidation = false;
  8007. customAttributes->mAttributes.push_back(customAttribute);
  8008. continue;
  8009. }
  8010. if (mContext->mCurTypeState != NULL)
  8011. {
  8012. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8013. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8014. }
  8015. else
  8016. {
  8017. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8018. }
  8019. }
  8020. // Don't allow this
  8021. /*else if (mContext->mCurTypeState != NULL)
  8022. {
  8023. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8024. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8025. }
  8026. else
  8027. {
  8028. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8029. }*/
  8030. BfTypeInstance* attrTypeInst = NULL;
  8031. if (attrType == NULL)
  8032. continue;
  8033. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8034. attrTypeInst = attrType->ToTypeInstance();
  8035. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8036. {
  8037. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8038. continue;
  8039. }
  8040. if (mCurTypeInstance != NULL)
  8041. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8042. customAttribute.mType = attrTypeInst;
  8043. BfConstResolver constResolver(this);
  8044. bool inPropSet = false;
  8045. SizedArray<BfResolvedArg, 2> argValues;
  8046. for (BfExpression* arg : attributesDirective->mArguments)
  8047. {
  8048. if (arg == NULL)
  8049. {
  8050. continue;
  8051. }
  8052. if (autoComplete != NULL)
  8053. autoComplete->mShowAttributeProperties = attrTypeInst;
  8054. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8055. {
  8056. inPropSet = true;
  8057. if (autoComplete != NULL)
  8058. autoComplete->CheckNode(assignExpr->mLeft);
  8059. String findName = assignExpr->mLeft->ToString();
  8060. BfPropertyDef* bestProp = NULL;
  8061. BfTypeInstance* bestPropTypeInst = NULL;
  8062. BfFieldDef* bestField = NULL;
  8063. BfTypeInstance* bestFieldTypeInst = NULL;
  8064. auto checkTypeInst = attrTypeInst;
  8065. while (checkTypeInst != NULL)
  8066. {
  8067. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8068. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8069. {
  8070. if (prop->mName == findName)
  8071. {
  8072. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8073. {
  8074. bestProp = prop;
  8075. bestPropTypeInst = checkTypeInst;
  8076. }
  8077. }
  8078. }
  8079. for (auto field : checkTypeInst->mTypeDef->mFields)
  8080. {
  8081. if (field->mName == findName)
  8082. {
  8083. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8084. {
  8085. bestField = field;
  8086. bestFieldTypeInst = checkTypeInst;
  8087. }
  8088. }
  8089. }
  8090. if ((bestProp != NULL) || (bestField != NULL))
  8091. break;
  8092. checkTypeInst = checkTypeInst->mBaseType;
  8093. }
  8094. bool handledExpr = false;
  8095. if (bestField != NULL)
  8096. {
  8097. handledExpr = true;
  8098. if (mCompiler->mResolvePassData != NULL)
  8099. {
  8100. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8101. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8102. {
  8103. autoComplete->mDefField = bestField;
  8104. autoComplete->mDefType = attrTypeDef;
  8105. }
  8106. }
  8107. if (bestField->mProtection != BfProtection_Public)
  8108. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8109. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8110. BfCustomAttributeSetField setField;
  8111. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8112. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8113. if (assignExpr->mRight != NULL)
  8114. {
  8115. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8116. if (result)
  8117. {
  8118. CurrentAddToConstHolder(result.mValue);
  8119. setField.mParam = result;
  8120. customAttribute.mSetField.push_back(setField);
  8121. }
  8122. }
  8123. }
  8124. else if (bestProp == NULL)
  8125. {
  8126. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8127. }
  8128. else
  8129. {
  8130. BfMethodDef* setMethod = NULL;
  8131. for (auto methodDef : bestProp->mMethods)
  8132. {
  8133. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8134. {
  8135. setMethod = methodDef;
  8136. break;
  8137. }
  8138. }
  8139. if (setMethod == NULL)
  8140. {
  8141. Fail("Property has no setter", assignExpr->mLeft);
  8142. }
  8143. else
  8144. {
  8145. if (mCompiler->mResolvePassData != NULL)
  8146. {
  8147. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8148. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8149. {
  8150. autoComplete->mDefProp = bestProp;
  8151. autoComplete->mDefType = attrTypeDef;
  8152. }
  8153. }
  8154. handledExpr = true;
  8155. if (bestProp->mProtection != BfProtection_Public)
  8156. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8157. BfResolvedArg resolvedArg;
  8158. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8159. BfCustomAttributeSetProperty setProperty;
  8160. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8161. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8162. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8163. if (methodInstance.mMethodInstance != NULL)
  8164. {
  8165. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8166. if (assignExpr->mRight != NULL)
  8167. {
  8168. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8169. if (result)
  8170. {
  8171. BF_ASSERT(result.mType == propType);
  8172. CurrentAddToConstHolder(result.mValue);
  8173. setProperty.mParam = result;
  8174. customAttribute.mSetProperties.push_back(setProperty);
  8175. }
  8176. }
  8177. }
  8178. }
  8179. }
  8180. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8181. constResolver.Resolve(assignExpr->mRight);
  8182. }
  8183. else
  8184. {
  8185. if (inPropSet)
  8186. {
  8187. Fail("Named attribute argument expected", arg); // CS1016
  8188. }
  8189. BfDeferEvalChecker deferEvalChecker;
  8190. arg->Accept(&deferEvalChecker);
  8191. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8192. BfResolvedArg resolvedArg;
  8193. resolvedArg.mExpression = arg;
  8194. if (deferParamEval)
  8195. {
  8196. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8197. }
  8198. else
  8199. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8200. if (!inPropSet)
  8201. argValues.push_back(resolvedArg);
  8202. }
  8203. if (autoComplete != NULL)
  8204. autoComplete->mShowAttributeProperties = NULL;
  8205. }
  8206. auto wasCapturingMethodInfo = false;
  8207. if (autoComplete != NULL)
  8208. {
  8209. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8210. if (attributesDirective->mCtorOpenParen != NULL)
  8211. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8212. }
  8213. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8214. attrTypeDef = attrTypeInst->mTypeDef;
  8215. bool success = true;
  8216. bool isFailurePass = false;
  8217. for (int pass = 0; pass < 2; pass++)
  8218. {
  8219. bool isFailurePass = pass == 1;
  8220. for (auto checkMethod : attrTypeDef->mMethods)
  8221. {
  8222. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8223. continue; // Don't match private default ctor if there's a user-defined one
  8224. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8225. continue;
  8226. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8227. continue;
  8228. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8229. }
  8230. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8231. break;
  8232. }
  8233. if (autoComplete != NULL)
  8234. {
  8235. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8236. {
  8237. autoComplete->mIsCapturingMethodMatchInfo = true;
  8238. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8239. }
  8240. else
  8241. autoComplete->mIsCapturingMethodMatchInfo = false;
  8242. }
  8243. if (methodMatcher.mBestMethodDef == NULL)
  8244. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8245. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8246. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8247. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8248. {
  8249. Fail("Custom attribute circular reference", attributesDirective);
  8250. }
  8251. if (mCurTypeInstance != NULL)
  8252. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8253. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8254. success = false;
  8255. for (auto& arg : argValues)
  8256. {
  8257. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8258. {
  8259. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8260. constResolver.Resolve(expr);
  8261. }
  8262. }
  8263. // Move all those to the constHolder
  8264. for (auto& ctorArg : customAttribute.mCtorArgs)
  8265. {
  8266. CurrentAddToConstHolder(ctorArg);
  8267. }
  8268. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8269. {
  8270. targetOverride = BfAttributeTargets_ReturnValue;
  8271. if (attrTarget != BfAttributeTargets_Method)
  8272. {
  8273. 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.",
  8274. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8275. }
  8276. success = false;
  8277. }
  8278. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8279. {
  8280. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8281. {
  8282. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8283. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8284. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8285. if (success)
  8286. {
  8287. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8288. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8289. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8290. }
  8291. }
  8292. else
  8293. {
  8294. // Failed - ignore
  8295. success = false;
  8296. }
  8297. }
  8298. if (success)
  8299. {
  8300. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8301. {
  8302. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8303. {
  8304. if (prevCustomAttribute.mType == attrTypeInst)
  8305. {
  8306. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8307. }
  8308. }
  8309. }
  8310. }
  8311. if (success)
  8312. {
  8313. customAttributes->mAttributes.push_back(customAttribute);
  8314. }
  8315. }
  8316. ValidateCustomAttributes(customAttributes, attrTarget);
  8317. }
  8318. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8319. {
  8320. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8321. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8322. return customAttributes;
  8323. }
  8324. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8325. {
  8326. if (mCurTypeInstance->mCustomAttributes != NULL)
  8327. {
  8328. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8329. {
  8330. String typeName = TypeToString(customAttribute.mType);
  8331. if (typeName == "System.PackedAttribute")
  8332. {
  8333. isPacked = true;
  8334. }
  8335. else if (typeName == "System.UnionAttribute")
  8336. {
  8337. isUnion = true;
  8338. }
  8339. else if (typeName == "System.CReprAttribute")
  8340. {
  8341. isCRepr = true;
  8342. isOrdered = true;
  8343. }
  8344. else if (typeName == "System.OrderedAttribute")
  8345. {
  8346. isOrdered = true;
  8347. }
  8348. else if (typeName == "System.AlwaysIncludeAttribute")
  8349. {
  8350. for (auto setProp : customAttribute.mSetProperties)
  8351. {
  8352. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8353. if (propertyDef->mName == "AssumeInstantiated")
  8354. {
  8355. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8356. if ((constant != NULL) && (constant->mBool))
  8357. mCurTypeInstance->mHasBeenInstantiated = true;
  8358. }
  8359. }
  8360. }
  8361. }
  8362. }
  8363. }
  8364. // Checking to see if we're an attribute or not
  8365. void BfModule::ProcessCustomAttributeData()
  8366. {
  8367. bool isAttribute = false;
  8368. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8369. while (checkTypeInst != NULL)
  8370. {
  8371. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8372. isAttribute = true;
  8373. checkTypeInst = checkTypeInst->mBaseType;
  8374. }
  8375. if (!isAttribute)
  8376. return;
  8377. auto attributeData = new BfAttributeData();
  8378. bool hasCustomAttribute = false;
  8379. if (mCurTypeInstance->mCustomAttributes != NULL)
  8380. {
  8381. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8382. {
  8383. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8384. {
  8385. if (customAttribute.mCtorArgs.size() > 0)
  8386. {
  8387. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8388. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8389. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8390. }
  8391. for (auto& setProp : customAttribute.mSetProperties)
  8392. {
  8393. BfPropertyDef* propDef = setProp.mPropertyRef;
  8394. if (propDef->mName == "AllowMultiple")
  8395. {
  8396. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8397. if (constant != NULL)
  8398. attributeData->mAllowMultiple = constant->mBool;
  8399. }
  8400. else if (propDef->mName == "Inherited")
  8401. {
  8402. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8403. if (constant != NULL)
  8404. attributeData->mInherited = constant->mBool;
  8405. }
  8406. else if (propDef->mName == "ValidOn")
  8407. {
  8408. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8409. if (constant != NULL)
  8410. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8411. }
  8412. }
  8413. hasCustomAttribute = true;
  8414. }
  8415. }
  8416. }
  8417. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8418. {
  8419. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8420. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8421. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8422. }
  8423. mCurTypeInstance->mAttributeData = attributeData;
  8424. }
  8425. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8426. {
  8427. auto constant = constHolder->GetConstant(irValue);
  8428. if (constant == NULL)
  8429. return false;
  8430. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8431. return false;
  8432. int stringId = constant->mInt32;
  8433. BfStringPoolEntry* entry = NULL;
  8434. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8435. {
  8436. str = entry->mString;
  8437. }
  8438. else
  8439. {
  8440. BF_DBG_FATAL("Failed to find string by id");
  8441. }
  8442. return true;
  8443. }
  8444. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8445. {
  8446. BfVariant variant;
  8447. variant.mTypeCode = BfTypeCode_None;
  8448. BfType* primType = NULL;
  8449. if (value.mType->IsPrimitiveType())
  8450. primType = (BfPrimitiveType*)value.mType;
  8451. else if (value.mType->IsTypedPrimitive())
  8452. primType = value.mType->GetUnderlyingType();
  8453. if (primType)
  8454. {
  8455. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8456. if (constant != NULL)
  8457. {
  8458. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8459. {
  8460. variant.mTypeCode = BfTypeCode_Let;
  8461. return variant;
  8462. }
  8463. switch (constant->mTypeCode)
  8464. {
  8465. case BfTypeCode_Int8:
  8466. case BfTypeCode_UInt8:
  8467. case BfTypeCode_Int16:
  8468. case BfTypeCode_UInt16:
  8469. case BfTypeCode_Int32:
  8470. case BfTypeCode_UInt32:
  8471. case BfTypeCode_Int64:
  8472. case BfTypeCode_UInt64:
  8473. case BfTypeCode_IntPtr:
  8474. case BfTypeCode_UIntPtr:
  8475. case BfTypeCode_IntUnknown:
  8476. case BfTypeCode_UIntUnknown:
  8477. case BfTypeCode_Single:
  8478. case BfTypeCode_Double:
  8479. case BfTypeCode_Char8:
  8480. case BfTypeCode_Char16:
  8481. case BfTypeCode_Char32:
  8482. variant.mTypeCode = constant->mTypeCode;
  8483. variant.mInt64 = constant->mInt64;
  8484. break;
  8485. default:
  8486. if (refNode != NULL)
  8487. Fail("Invalid const expression type", refNode);
  8488. break;
  8489. }
  8490. }
  8491. }
  8492. return variant;
  8493. }
  8494. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8495. {
  8496. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8497. {
  8498. auto elementType = typedValue.mType->GetUnderlyingType();
  8499. if (typedValue.IsAddr())
  8500. {
  8501. if (elementType->IsValuelessType())
  8502. {
  8503. BF_ASSERT(!typedValue.mValue);
  8504. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8505. }
  8506. else
  8507. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8508. }
  8509. else
  8510. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8511. if (typedValue.mType->IsValuelessType())
  8512. {
  8513. BF_ASSERT(typedValue.mValue.IsFake());
  8514. }
  8515. }
  8516. return typedValue;
  8517. }
  8518. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8519. {
  8520. if (!typedValue.IsAddr())
  8521. return typedValue;
  8522. if (typedValue.mType->IsValuelessType())
  8523. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8524. BfIRValue loadedVal = typedValue.mValue;
  8525. if (loadedVal)
  8526. {
  8527. /*if (isVolatile)
  8528. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8529. PopulateType(typedValue.mType, BfPopulateType_Data);
  8530. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8531. }
  8532. return BfTypedValue(loadedVal, typedValue.mType, false);
  8533. }
  8534. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8535. {
  8536. if (typedValue.IsSplat())
  8537. return AggregateSplat(typedValue);
  8538. if (typedValue.IsAddr())
  8539. return LoadValue(typedValue);
  8540. return typedValue;
  8541. }
  8542. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8543. {
  8544. if (!typedValue.IsSplat())
  8545. return typedValue;
  8546. if (typedValue.mType->IsValuelessType())
  8547. return typedValue;
  8548. int elementIdx = 0;
  8549. auto _ExtractValue = [&](BfType* checkType)
  8550. {
  8551. if (valueArrPtr != NULL)
  8552. return valueArrPtr[elementIdx++];
  8553. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8554. };
  8555. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8556. {
  8557. if (checkType->IsStruct())
  8558. {
  8559. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8560. auto checkTypeInstance = checkType->ToTypeInstance();
  8561. if (checkTypeInstance->mBaseType != NULL)
  8562. {
  8563. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8564. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8565. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8566. }
  8567. if (checkTypeInstance->mIsUnion)
  8568. {
  8569. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8570. if (!unionInnerType->IsValuelessType())
  8571. {
  8572. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8573. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8574. }
  8575. if (checkTypeInstance->IsEnum())
  8576. {
  8577. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8578. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8579. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8580. }
  8581. }
  8582. else
  8583. {
  8584. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8585. {
  8586. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8587. if (fieldInstance->mDataIdx >= 0)
  8588. {
  8589. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8590. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8591. }
  8592. }
  8593. }
  8594. return curValue;
  8595. }
  8596. else if (checkType->IsMethodRef())
  8597. {
  8598. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8599. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8600. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8601. {
  8602. BfIRValue fieldValue;
  8603. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8604. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8605. {
  8606. fieldValue = checkTypeLambda(checkType);
  8607. }
  8608. else
  8609. {
  8610. fieldValue = _ExtractValue(checkType);
  8611. }
  8612. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8613. }
  8614. return curValue;
  8615. }
  8616. else if (!checkType->IsValuelessType())
  8617. {
  8618. return _ExtractValue(checkType);
  8619. }
  8620. return BfIRValue();
  8621. };
  8622. BfIRValue value = checkTypeLambda(typedValue.mType);
  8623. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8624. }
  8625. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8626. {
  8627. if (!typedValue.IsSplat())
  8628. return;
  8629. if (typedValue.mType->IsValuelessType())
  8630. return;
  8631. /*static int sCallIdx = 0;
  8632. if (!mCompiler->mIsResolveOnly)
  8633. sCallIdx++;
  8634. int callIdx = sCallIdx;*/
  8635. int elementIdx = 0;
  8636. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8637. {
  8638. if (checkType->IsStruct())
  8639. {
  8640. auto checkTypeInstance = checkType->ToTypeInstance();
  8641. if (checkTypeInstance->mBaseType != NULL)
  8642. {
  8643. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8644. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8645. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8646. }
  8647. if (checkTypeInstance->mIsUnion)
  8648. {
  8649. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8650. if (!unionInnerType->IsValuelessType())
  8651. {
  8652. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8653. checkTypeLambda(unionInnerType, fieldAddrVal);
  8654. }
  8655. if (checkTypeInstance->IsEnum())
  8656. {
  8657. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8658. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8659. checkTypeLambda(dscrType, fieldAddrVal);
  8660. }
  8661. }
  8662. else
  8663. {
  8664. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8665. {
  8666. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8667. if (fieldInstance->mDataIdx >= 0)
  8668. {
  8669. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8670. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8671. }
  8672. }
  8673. }
  8674. }
  8675. else if (checkType->IsMethodRef())
  8676. {
  8677. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8678. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8679. {
  8680. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8681. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8682. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8683. {
  8684. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8685. }
  8686. else
  8687. {
  8688. // static int sItrCount = 0;
  8689. // sItrCount++;
  8690. // int curItr = sItrCount;
  8691. // if (curItr == 1)
  8692. // {
  8693. // NOP;
  8694. // }
  8695. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8696. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8697. }
  8698. }
  8699. }
  8700. else if (!checkType->IsValuelessType())
  8701. {
  8702. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8703. mBfIRBuilder->CreateStore(val, curAddrVal);
  8704. }
  8705. };
  8706. checkTypeLambda(typedValue.mType, addrVal);
  8707. }
  8708. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8709. {
  8710. bool wasReadOnly = typedVal.IsReadOnly();
  8711. if ((typedVal.mType->IsValueType()) &&
  8712. (!typedVal.mType->IsValuelessType()))
  8713. {
  8714. wasReadOnly = true; // Any non-addr is implicitly read-only
  8715. //static int gCallIdx = 0;
  8716. if (typedVal.IsAddr())
  8717. return typedVal;
  8718. BfType* type = typedVal.mType;
  8719. PopulateType(type);
  8720. auto tempVar = CreateAlloca(type);
  8721. if (typedVal.IsSplat())
  8722. AggregateSplatIntoAddr(typedVal, tempVar);
  8723. else
  8724. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8725. return BfTypedValue(tempVar, type,
  8726. typedVal.IsThis() ?
  8727. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8728. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8729. }
  8730. return LoadValue(typedVal);
  8731. }
  8732. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8733. {
  8734. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8735. typedValue.mKind = BfTypedValueKind_Addr;
  8736. return typedValue;
  8737. }
  8738. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8739. {
  8740. BfIRValue val;
  8741. if (typedValue.mValue.IsArg())
  8742. {
  8743. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8744. if (isAddr != NULL)
  8745. {
  8746. if (wantType != NULL)
  8747. *isAddr = wantType->IsComposite();
  8748. else
  8749. *isAddr = false;
  8750. }
  8751. else if (wantType->IsComposite())
  8752. val = mBfIRBuilder->CreateLoad(val);
  8753. }
  8754. if (!val)
  8755. {
  8756. auto checkMethodState = mCurMethodState;
  8757. while (checkMethodState != NULL)
  8758. {
  8759. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8760. {
  8761. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8762. if (decompAddr == typedValue.mValue)
  8763. {
  8764. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8765. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8766. {
  8767. // This is really backing for a POINTER to a composite inside a methodRef
  8768. val = mBfIRBuilder->CreateLoad(val);
  8769. }
  8770. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8771. {
  8772. *isAddr = true;
  8773. return val;
  8774. }
  8775. else
  8776. {
  8777. val = mBfIRBuilder->CreateLoad(val);
  8778. break;
  8779. }
  8780. }
  8781. }
  8782. if (val)
  8783. break;
  8784. checkMethodState = checkMethodState->mPrevMethodState;
  8785. }
  8786. }
  8787. if (val)
  8788. {
  8789. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8790. {
  8791. BF_ASSERT(wantType != NULL);
  8792. if (wantType != NULL)
  8793. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8794. }
  8795. return val;
  8796. }
  8797. BF_FATAL("Splat not found");
  8798. return BfIRValue();
  8799. }
  8800. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8801. {
  8802. int useFieldIdx = fieldIdx;
  8803. BfType* fieldType = NULL;
  8804. if (fieldInstance != NULL)
  8805. {
  8806. fieldType = fieldInstance->mResolvedType;
  8807. if (typedValue.mType->IsUnion())
  8808. {
  8809. if (fieldIdx == 1)
  8810. {
  8811. if (typedValue.IsSplat())
  8812. {
  8813. BfTypedValue innerVal = typedValue;
  8814. innerVal.mType = fieldType;
  8815. return innerVal;
  8816. }
  8817. }
  8818. }
  8819. }
  8820. else
  8821. {
  8822. if (typedValue.mType->IsPayloadEnum())
  8823. {
  8824. auto typeInst = typedValue.mType->ToTypeInstance();
  8825. if (fieldIdx == 1)
  8826. fieldType = typeInst->GetUnionInnerType();
  8827. else if (fieldIdx == 2)
  8828. {
  8829. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8830. }
  8831. }
  8832. else if (typedValue.mType->IsUnion())
  8833. {
  8834. if (fieldIdx == 1)
  8835. {
  8836. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8837. if (typedValue.IsSplat())
  8838. {
  8839. BfTypedValue innerVal = typedValue;
  8840. innerVal.mType = fieldType;
  8841. return innerVal;
  8842. }
  8843. }
  8844. }
  8845. }
  8846. BF_ASSERT(typedValue.mType->IsStruct());
  8847. if (typedValue.IsSplat())
  8848. {
  8849. if (typedValue.mType->IsPayloadEnum())
  8850. {
  8851. if (fieldIdx == 1)
  8852. {
  8853. // Payload
  8854. auto typeInst = typedValue.mType->ToTypeInstance();
  8855. auto unionInnerType = typeInst->GetUnionInnerType();
  8856. bool isAddr = false;
  8857. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8858. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8859. }
  8860. if (fieldIdx == 2)
  8861. {
  8862. // Discriminator
  8863. auto typeInst = typedValue.mType->ToTypeInstance();
  8864. auto unionInnerType = typeInst->GetUnionInnerType();
  8865. auto dscrType = typeInst->GetDiscriminatorType();
  8866. int argIdx = typedValue.mValue.mId;
  8867. int componentIdx = 0;
  8868. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8869. bool isAddr;
  8870. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8871. return BfTypedValue(irVal, dscrType, isAddr);
  8872. }
  8873. }
  8874. int componentIdx = 0;
  8875. BfTypedValue retVal;
  8876. BfFieldInstance* wantFieldInstance = fieldInstance;
  8877. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8878. {
  8879. if (checkType->IsStruct())
  8880. {
  8881. auto checkTypeInstance = checkType->ToTypeInstance();
  8882. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8883. {
  8884. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8885. fieldType = checkTypeInstance->GetUnionInnerType();
  8886. checkTypeLambda(fieldType);
  8887. if (checkType->IsEnum())
  8888. {
  8889. // Past discriminator...
  8890. componentIdx++;
  8891. }
  8892. return;
  8893. }
  8894. if (checkTypeInstance->mBaseType != NULL)
  8895. checkTypeLambda(checkTypeInstance->mBaseType);
  8896. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8897. {
  8898. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8899. if (fieldInstance == wantFieldInstance)
  8900. {
  8901. bool isAddr = false;
  8902. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8903. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8904. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8905. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8906. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8907. {
  8908. retVal = LoadValue(retVal);
  8909. }
  8910. break;
  8911. }
  8912. if (fieldInstance->mDataIdx >= 0)
  8913. checkTypeLambda(fieldInstance->GetResolvedType());
  8914. }
  8915. }
  8916. else if (!checkType->IsValuelessType())
  8917. {
  8918. componentIdx++;
  8919. //argIdx++;
  8920. }
  8921. };
  8922. checkTypeLambda(typedValue.mType);
  8923. BF_ASSERT(retVal);
  8924. return retVal;
  8925. }
  8926. if (typedValue.IsAddr())
  8927. {
  8928. BF_ASSERT(fieldType != NULL);
  8929. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8930. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8931. }
  8932. else
  8933. {
  8934. BF_ASSERT(fieldType != NULL);
  8935. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8936. }
  8937. }
  8938. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8939. {
  8940. if (typedValue.IsAddr())
  8941. {
  8942. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8943. return mBfIRBuilder->CreateLoad(addrVal);
  8944. }
  8945. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8946. }
  8947. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8948. {
  8949. if (elementType->IsSizeAligned())
  8950. {
  8951. if (isElementIndex)
  8952. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8953. else
  8954. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8955. }
  8956. auto ptrType = CreatePointerType(elementType);
  8957. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8958. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8959. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8960. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8961. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8962. }
  8963. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8964. {
  8965. if (elementType->IsSizeAligned())
  8966. {
  8967. if (isElementIndex)
  8968. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  8969. else
  8970. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8971. }
  8972. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  8973. }
  8974. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  8975. {
  8976. if (modifyType == NULL)
  8977. modifyType = "modify";
  8978. if (typedValue.mType->IsVar())
  8979. return true;
  8980. if (typedValue.IsReadOnly())
  8981. {
  8982. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  8983. return false;
  8984. }
  8985. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  8986. {
  8987. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8988. return false;
  8989. }
  8990. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  8991. {
  8992. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  8993. return false;
  8994. }
  8995. return true;
  8996. }
  8997. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  8998. {
  8999. if (methodA->mMethodDef->mIsLocalMethod)
  9000. {
  9001. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9002. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9003. if (sepPosA != sepPosB)
  9004. return false;
  9005. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9006. return false;
  9007. }
  9008. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9009. return false;
  9010. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9011. return false;
  9012. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9013. {
  9014. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9015. return false;
  9016. }
  9017. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9018. {
  9019. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9020. return false;
  9021. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9022. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9023. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9024. return false;
  9025. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9026. return false;
  9027. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9028. {
  9029. if (methodA->mReturnType != methodB->mReturnType)
  9030. return false;
  9031. }
  9032. }
  9033. int implicitParamCountA = methodA->GetImplicitParamCount();
  9034. int implicitParamCountB = methodB->GetImplicitParamCount();
  9035. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9036. return false;
  9037. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9038. return false;
  9039. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9040. {
  9041. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  9042. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9043. return false;
  9044. }
  9045. // Compare generic params. Generic params are part of the method signature here
  9046. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9047. return false;
  9048. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9049. {
  9050. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9051. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9052. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9053. return false;
  9054. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9055. return false;
  9056. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9057. return false;
  9058. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9059. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9060. return false;
  9061. }
  9062. return true;
  9063. }
  9064. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9065. {
  9066. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9067. return false;
  9068. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9069. return false;
  9070. if (iMethodInst->mMethodDef->mIsOperator)
  9071. {
  9072. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9073. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9074. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9075. return false;
  9076. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9077. return false;
  9078. }
  9079. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9080. return false;
  9081. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9082. {
  9083. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9084. return false;
  9085. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9086. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9087. if (iParamType->IsSelf())
  9088. {
  9089. if (methodParamType != methodInstance->GetOwner())
  9090. return false;
  9091. }
  9092. else if (!iParamType->IsGenericParam())
  9093. {
  9094. if (methodParamType != iParamType)
  9095. return false;
  9096. }
  9097. else
  9098. {
  9099. if (!methodParamType->IsGenericParam())
  9100. return false;
  9101. auto genericParamType = (BfGenericParamType*)methodParamType;
  9102. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9103. return false;
  9104. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9105. bool hadInterface = false;
  9106. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9107. if (interfaceConstraint == iParamType)
  9108. hadInterface = true;
  9109. if (!hadInterface)
  9110. return false;
  9111. }
  9112. }
  9113. return true;
  9114. }
  9115. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9116. {
  9117. BfMethodInstance* methodInstance = methodRef;
  9118. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9119. {
  9120. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9121. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9122. {
  9123. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9124. BfMethodRef methodRef = methodInstance;
  9125. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9126. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9127. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9128. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9129. (mIsReified))
  9130. {
  9131. specializedMethodRefInfo->mHasReifiedRef = true;
  9132. }
  9133. }
  9134. }
  9135. }
  9136. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9137. {
  9138. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9139. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9140. if (mBfIRBuilder == NULL)
  9141. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9142. if (methodInstance->GetOwner()->IsFunction())
  9143. {
  9144. // No actual ref needed- not an actual generated function
  9145. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9146. }
  9147. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9148. if (!isGenFunction)
  9149. AddMethodReference(methodInstance, flags);
  9150. if (mBfIRBuilder->mIgnoreWrites)
  9151. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9152. if (mCompiler->IsSkippingExtraResolveChecks())
  9153. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9154. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9155. {
  9156. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9157. }
  9158. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9159. BfMethodRef methodRef = methodInstance;
  9160. if (isInlined)
  9161. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9162. else
  9163. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9164. if (!isGenFunction)
  9165. {
  9166. BfIRValue* irFuncPtr = NULL;
  9167. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9168. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9169. }
  9170. if (mAwaitingInitFinish)
  9171. FinishInit();
  9172. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9173. if (!isGenFunction)
  9174. mFuncReferences[methodRef] = func;
  9175. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9176. if ((isInlined) && (!mIsScratchModule))
  9177. {
  9178. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9179. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9180. // type instance
  9181. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9182. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9183. for (auto ownedTypeInst : mOwnedTypeInstances)
  9184. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9185. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9186. {
  9187. mIncompleteMethodCount++;
  9188. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9189. inlineMethodRequest->mType = methodInstance->GetOwner();
  9190. inlineMethodRequest->mFromModule = this;
  9191. inlineMethodRequest->mFunc = func;
  9192. inlineMethodRequest->mFromModuleRevision = mRevision;
  9193. inlineMethodRequest->mMethodInstance = methodInstance;
  9194. BF_ASSERT(mIsModuleMutable);
  9195. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9196. }
  9197. }
  9198. return BfModuleMethodInstance(methodInstance, func);
  9199. }
  9200. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9201. {
  9202. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9203. if (mBfIRBuilder == NULL)
  9204. {
  9205. // To allow for custom attribute data
  9206. PrepareForIRWriting(typeInst);
  9207. }
  9208. BfModule* declareModule = this;
  9209. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9210. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9211. declareModule = declareModule->mParentModule;
  9212. // Check for attributes
  9213. if (typeInst == mContext->mBfObjectType)
  9214. {
  9215. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9216. if (methodDecl != NULL)
  9217. {
  9218. auto attributesDirective = methodDecl->mAttributes;
  9219. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9220. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9221. {
  9222. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9223. }
  9224. }
  9225. }
  9226. else
  9227. {
  9228. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9229. GetMethodCustomAttributes(methodInstance);
  9230. }
  9231. BF_ASSERT(mModuleOptions == NULL);
  9232. if (methodInstance->GetCustomAttributes() != NULL)
  9233. {
  9234. auto project = typeInst->mTypeDef->mProject;
  9235. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9236. BfModuleOptions wantOptions = moduleOptions;
  9237. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9238. if (typeOptions != NULL)
  9239. {
  9240. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9241. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9242. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9243. }
  9244. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9245. {
  9246. StringT<128> attrName;
  9247. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9248. {
  9249. attrName.Clear();
  9250. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9251. Array<int>* arrPtr;
  9252. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9253. {
  9254. for (auto optionsIdx : *arrPtr)
  9255. {
  9256. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9257. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9258. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9259. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9260. }
  9261. }
  9262. }
  9263. }
  9264. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9265. {
  9266. auto lastCheckModule = this;
  9267. auto checkModule = this->mNextAltModule;
  9268. while (checkModule != NULL)
  9269. {
  9270. if (*checkModule->mModuleOptions == wantOptions)
  9271. {
  9272. declareModule = checkModule;
  9273. break;
  9274. }
  9275. lastCheckModule = checkModule;
  9276. checkModule = checkModule->mNextAltModule;
  9277. }
  9278. // Not found?
  9279. if (declareModule == this)
  9280. {
  9281. String specModuleName = mModuleName + "@@";
  9282. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9283. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9284. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9285. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9286. declareModule = new BfModule(mContext, specModuleName);
  9287. declareModule->mProject = project;
  9288. declareModule->mModuleOptions = new BfModuleOptions();
  9289. *declareModule->mModuleOptions = wantOptions;
  9290. declareModule->mParentModule = lastCheckModule;
  9291. declareModule->Init();
  9292. lastCheckModule->mNextAltModule = declareModule;
  9293. }
  9294. }
  9295. }
  9296. declareModule->PrepareForIRWriting(typeInst);
  9297. return declareModule;
  9298. }
  9299. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9300. {
  9301. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9302. {
  9303. // Don't bother inlining for resolve-only
  9304. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9305. }
  9306. bool processNow = false;
  9307. bool keepInCurrentModule = false;
  9308. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9309. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9310. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9311. {
  9312. return BfModuleMethodInstance();
  9313. }
  9314. if (methodDef->mIsLocalMethod)
  9315. {
  9316. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9317. BfLocalMethod* localMethod;
  9318. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9319. {
  9320. // Handle the def in the correct method state
  9321. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9322. }
  9323. BF_FATAL("Cannot find local method");
  9324. return BfModuleMethodInstance();
  9325. }
  9326. #ifdef _DEBUG
  9327. for (auto arg : methodGenericArguments)
  9328. BF_ASSERT(!arg->IsVar());
  9329. #endif
  9330. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9331. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9332. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9333. // a FinishInit
  9334. if ((typeInst->IsIncomplete()) &&
  9335. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9336. {
  9337. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9338. // for resolve-only because we don't differentiate between reified/unreified there
  9339. PopulateType(typeInst, BfPopulateType_Full);
  9340. }
  9341. bool tryModuleMethodLookup = false;
  9342. BfModuleMethodInstance moduleMethodInst;
  9343. BfModule* instModule = typeInst->mModule;
  9344. if (keepInCurrentModule)
  9345. {
  9346. // Stay here
  9347. instModule = this;
  9348. }
  9349. if (this == mContext->mUnreifiedModule)
  9350. {
  9351. // Stay in this 'resolve only' module here
  9352. }
  9353. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9354. {
  9355. BF_ASSERT(this == mContext->mUnreifiedModule);
  9356. }
  9357. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9358. {
  9359. BF_ASSERT(instModule == mParentModule);
  9360. }
  9361. else if (instModule != this)
  9362. {
  9363. if ((!mIsReified) && (instModule->mIsReified))
  9364. {
  9365. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9366. // A resolve-only module is specializing a method from a type in a reified module,
  9367. // we need to take care that this doesn't cause anything new to become reified
  9368. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9369. }
  9370. else
  9371. {
  9372. if ((mIsReified) && (!instModule->mIsReified))
  9373. {
  9374. if (!instModule->mReifyQueued)
  9375. {
  9376. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9377. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9378. mContext->mReifyModuleWorkList.Add(instModule);
  9379. instModule->mReifyQueued = true;
  9380. }
  9381. // This ensures that the method will actually be created when it gets reified
  9382. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9383. specializationRequest->mFromModule = typeInst->mModule;
  9384. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9385. specializationRequest->mMethodDef = methodDef;
  9386. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9387. specializationRequest->mType = typeInst;
  9388. }
  9389. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9390. // Not extern
  9391. // Create the instance in the proper module and then create a reference in this one
  9392. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9393. tryModuleMethodLookup = true;
  9394. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9395. {
  9396. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9397. }
  9398. }
  9399. }
  9400. if (tryModuleMethodLookup)
  9401. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9402. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9403. {
  9404. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9405. if (moduleMethodInstance)
  9406. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9407. return moduleMethodInst;
  9408. }
  9409. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9410. bool hadConcreteInterfaceGenericArgument = false;
  9411. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9412. isReified = false;
  9413. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9414. {
  9415. isReified = false;
  9416. }
  9417. BfTypeVector sanitizedMethodGenericArguments;
  9418. Array<BfProject*> projectList;
  9419. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9420. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9421. isUnspecializedPass = false;
  9422. // 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
  9423. bool isExternalExtensionMethod = false;
  9424. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9425. {
  9426. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9427. {
  9428. auto specProject = methodDef->mDeclaringType->mProject;
  9429. isExternalExtensionMethod = true;
  9430. if (typeInst->IsGenericTypeInstance())
  9431. {
  9432. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9433. if (genericTypeInst->mProjectsReferenced.empty())
  9434. genericTypeInst->GenerateProjectsReferenced();
  9435. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9436. {
  9437. // This is a generic type where a generic param is already confined to the project in question
  9438. isExternalExtensionMethod = false;
  9439. }
  9440. }
  9441. if (isExternalExtensionMethod)
  9442. {
  9443. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9444. projectList.push_back(methodDef->mDeclaringType->mProject);
  9445. }
  9446. }
  9447. }
  9448. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9449. {
  9450. int typeProjectsCounts = 0;
  9451. if (typeInst->IsGenericTypeInstance())
  9452. {
  9453. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9454. if (genericTypeInst->mProjectsReferenced.empty())
  9455. genericTypeInst->GenerateProjectsReferenced();
  9456. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9457. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9458. }
  9459. else
  9460. {
  9461. typeProjectsCounts = 1;
  9462. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9463. }
  9464. isUnspecializedPass = true;
  9465. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9466. {
  9467. auto genericArgType = methodGenericArguments[genericArgIdx];
  9468. //BF_ASSERT(!genericArgType->IsRef());
  9469. if (genericArgType->IsConcreteInterfaceType())
  9470. {
  9471. hadConcreteInterfaceGenericArgument = true;
  9472. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9473. genericArgType = concreteInterfaceType->mInterface;
  9474. }
  9475. if (genericArgType->IsGenericParam())
  9476. {
  9477. auto genericParam = (BfGenericParamType*) genericArgType;
  9478. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9479. isUnspecializedPass = false;
  9480. }
  9481. else
  9482. {
  9483. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9484. isUnspecializedPass = false;
  9485. }
  9486. sanitizedMethodGenericArguments.push_back(genericArgType);
  9487. }
  9488. if ((int)projectList.size() > typeProjectsCounts)
  9489. {
  9490. // Just leave the new items
  9491. projectList.RemoveRange(0, typeProjectsCounts);
  9492. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9493. {
  9494. return lhs->mName < rhs->mName;
  9495. });
  9496. }
  9497. else
  9498. {
  9499. projectList.Clear();
  9500. }
  9501. }
  9502. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9503. BfMethodInstanceGroup* methodInstGroup = NULL;
  9504. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9505. {
  9506. BF_ASSERT(!typeInst->IsInterface());
  9507. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9508. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9509. {
  9510. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9511. // if (checkGroup.mDefault == NULL)
  9512. // {
  9513. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9514. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9515. // methodInstGroup = &checkGroup;
  9516. // break;
  9517. // }
  9518. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9519. {
  9520. methodInstGroup = &checkGroup;
  9521. break;
  9522. }
  9523. }
  9524. if (methodInstGroup == NULL)
  9525. {
  9526. // Allocate a new entry
  9527. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9528. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9529. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9530. methodInstGroup->mOwner = typeInst;
  9531. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9532. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9533. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9534. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9535. else
  9536. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9537. }
  9538. }
  9539. else
  9540. {
  9541. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9542. }
  9543. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9544. {
  9545. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9546. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9547. }
  9548. BfIRFunction prevIRFunc;
  9549. bool doingRedeclare = false;
  9550. BfMethodInstance* methodInstance = NULL;
  9551. auto _SetReified = [&]()
  9552. {
  9553. methodInstance->mIsReified = true;
  9554. };
  9555. if (lookupMethodGenericArguments.size() == 0)
  9556. {
  9557. methodInstance = methodInstGroup->mDefault;
  9558. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9559. {
  9560. MarkDerivedDirty(typeInst);
  9561. if (mIsScratchModule)
  9562. {
  9563. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9564. _SetReified();
  9565. CheckHotMethod(methodInstance, "");
  9566. }
  9567. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9568. {
  9569. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9570. // the specializations to handle that for us
  9571. return BfModuleMethodInstance(methodInstance);
  9572. }
  9573. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9574. {
  9575. if (methodDef->mIsAbstract)
  9576. {
  9577. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9578. _SetReified();
  9579. }
  9580. else
  9581. {
  9582. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9583. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9584. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9585. doingRedeclare = true;
  9586. mOnDemandMethodCount++;
  9587. }
  9588. }
  9589. else
  9590. {
  9591. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9592. // We haven't processed it yet
  9593. _SetReified();
  9594. CheckHotMethod(methodInstance, "");
  9595. if (methodInstance->mDeclModule == this)
  9596. {
  9597. if (methodInstance->mMethodProcessRequest != NULL)
  9598. {
  9599. // Disconnect method process request
  9600. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9601. }
  9602. }
  9603. else
  9604. {
  9605. if (methodInstance->mMethodProcessRequest != NULL)
  9606. {
  9607. // Disconnect method process request
  9608. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9609. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9610. methodInstance->mMethodProcessRequest = NULL;
  9611. }
  9612. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9613. {
  9614. // Add new request in proper module
  9615. methodInstance->mDeclModule = this;
  9616. }
  9617. else
  9618. {
  9619. if (methodInstance->mDeclModule == NULL)
  9620. {
  9621. //
  9622. }
  9623. else if (methodInstance->mDeclModule != this)
  9624. {
  9625. // Is from specialized module?
  9626. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9627. }
  9628. }
  9629. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9630. {
  9631. methodInstance->mIRFunction = BfIRFunction();
  9632. if (!mIsModuleMutable)
  9633. StartExtension();
  9634. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9635. {
  9636. StringT<128> mangledName;
  9637. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9638. bool isIntrinsic = false;
  9639. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9640. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9641. }
  9642. }
  9643. AddMethodToWorkList(methodInstance);
  9644. }
  9645. }
  9646. }
  9647. }
  9648. else
  9649. {
  9650. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9651. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9652. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9653. BfMethodInstance** methodInstancePtr = NULL;
  9654. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9655. {
  9656. methodInstance = *methodInstancePtr;
  9657. if ((isReified) && (!methodInstance->mIsReified))
  9658. {
  9659. MarkDerivedDirty(typeInst);
  9660. if (methodInstance->mHasBeenProcessed)
  9661. {
  9662. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9663. delete methodInstance;
  9664. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9665. methodInstance = NULL;
  9666. }
  9667. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9668. {
  9669. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9670. delete methodInstance;
  9671. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9672. methodInstance = NULL;
  9673. }
  9674. else
  9675. {
  9676. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9677. // We haven't processed it yet
  9678. _SetReified();
  9679. CheckHotMethod(methodInstance, "");
  9680. }
  9681. }
  9682. }
  9683. }
  9684. if ((methodInstance != NULL) && (!doingRedeclare))
  9685. {
  9686. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9687. {
  9688. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9689. BF_ASSERT(!methodInstance->mIsReified);*/
  9690. if (methodInstance->mIsReified != isReified)
  9691. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9692. if ((!isReified) &&
  9693. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9694. {
  9695. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9696. methodInstance->mIRFunction = BfIRFunction();
  9697. }
  9698. methodInstance->mIsReified = isReified;
  9699. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9700. {
  9701. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9702. }
  9703. if (!methodInstance->mMethodDef->mIsAbstract)
  9704. {
  9705. AddMethodToWorkList(methodInstance);
  9706. }
  9707. else
  9708. {
  9709. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9710. }
  9711. }
  9712. if (mExtensionCount > 0)
  9713. {
  9714. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9715. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9716. {
  9717. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9718. if (mAwaitingInitFinish)
  9719. FinishInit();
  9720. // We need to refer to a function that was defined in a prior module
  9721. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9722. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9723. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9724. methodInstance->mDeclModule = this;
  9725. // Add this inlined def to ourselves
  9726. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9727. {
  9728. mIncompleteMethodCount++;
  9729. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9730. inlineMethodRequest->mType = typeInst;
  9731. inlineMethodRequest->mFromModule = this;
  9732. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9733. inlineMethodRequest->mFromModuleRevision = mRevision;
  9734. inlineMethodRequest->mMethodInstance = methodInstance;
  9735. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9736. BF_ASSERT(mIsModuleMutable);
  9737. }
  9738. }
  9739. }
  9740. if (mCompiler->IsSkippingExtraResolveChecks())
  9741. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9742. else
  9743. {
  9744. if (methodInstance->mDeclModule != this)
  9745. return ReferenceExternalMethodInstance(methodInstance, flags);
  9746. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9747. {
  9748. auto importKind = methodInstance->GetImportCallKind();
  9749. if (importKind != BfImportCallKind_None)
  9750. {
  9751. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9752. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9753. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9754. }
  9755. }
  9756. return BfModuleMethodInstance(methodInstance);
  9757. }
  9758. }
  9759. if (!doingRedeclare)
  9760. {
  9761. BfModule* specModule = NULL;
  9762. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9763. {
  9764. specModule = GetSpecializedMethodModule(projectList);
  9765. }
  9766. if ((specModule != NULL) && (specModule != this))
  9767. {
  9768. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9769. if (mAwaitingInitFinish)
  9770. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9771. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9772. }
  9773. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9774. {
  9775. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9776. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9777. }
  9778. }
  9779. if (methodInstance == NULL)
  9780. {
  9781. if (lookupMethodGenericArguments.size() == 0)
  9782. {
  9783. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9784. methodInstance = new BfMethodInstance();
  9785. methodInstGroup->mDefault = methodInstance;
  9786. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9787. }
  9788. else
  9789. {
  9790. BfMethodInstance** methodInstancePtr = NULL;
  9791. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9792. BF_ASSERT(added);
  9793. methodInstance = new BfMethodInstance();
  9794. *methodInstancePtr = methodInstance;
  9795. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9796. }
  9797. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9798. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9799. }
  9800. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9801. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9802. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9803. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9804. methodInstance->mMethodDef = methodDef;
  9805. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9806. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9807. methodInstance->mIsReified = isReified;
  9808. SetupMethodIdHash(methodInstance);
  9809. if (hadConcreteInterfaceGenericArgument)
  9810. methodInstance->mIgnoreBody = true;
  9811. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9812. {
  9813. methodInstance->mIsForeignMethodDef = true;
  9814. BF_ASSERT(foreignType != NULL);
  9815. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9816. }
  9817. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9818. {
  9819. if (!lookupMethodGenericArguments.empty())
  9820. {
  9821. auto compareType = lookupMethodGenericArguments[0];
  9822. PopulateType(compareType, BfPopulateType_Data);
  9823. if (compareType->IsSplattable())
  9824. methodInstance->mAlwaysInline = true;
  9825. }
  9826. }
  9827. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9828. {
  9829. // With extensions we can have multiple definitions of the same method
  9830. //methodInstance->mMangleWithIdx = true;
  9831. }
  9832. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9833. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9834. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9835. if (isUnspecializedPass)
  9836. {
  9837. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9838. {
  9839. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9840. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9841. }
  9842. }
  9843. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9844. {
  9845. if (!sanitizedMethodGenericArguments.IsEmpty())
  9846. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9847. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9848. {
  9849. Fail("Internal error");
  9850. BF_FATAL("Generic method argument counts mismatch");
  9851. return NULL;
  9852. }
  9853. for (auto genericArg : sanitizedMethodGenericArguments)
  9854. {
  9855. if (genericArg->IsPrimitiveType())
  9856. genericArg = GetWrappedStructType(genericArg);
  9857. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9858. if (genericArg->IsMethodRef())
  9859. {
  9860. auto methodRefType = (BfMethodRefType*)genericArg;
  9861. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9862. }
  9863. }
  9864. }
  9865. // Generic constraints
  9866. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9867. {
  9868. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9869. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9870. }
  9871. bool addToWorkList = !processNow;
  9872. if (mCompiler->GetAutoComplete() != NULL)
  9873. {
  9874. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9875. addToWorkList = false;
  9876. }
  9877. BF_ASSERT(declareModule != NULL);
  9878. methodInstance->mDeclModule = declareModule;
  9879. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9880. {
  9881. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9882. // of a reified module -
  9883. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9884. // BUT if we don't reify it then we have to remove the body after processing.
  9885. // 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
  9886. // the proper reified module.
  9887. declareModule = mContext->mUnreifiedModule;
  9888. }
  9889. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9890. {
  9891. BF_ASSERT(!methodInstance->mIsReified);
  9892. declareModule = mContext->mUnreifiedModule;
  9893. }
  9894. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9895. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9896. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9897. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9898. if (processNow)
  9899. {
  9900. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9901. ProcessMethod(methodInstance);
  9902. }
  9903. if (mCompiler->IsSkippingExtraResolveChecks())
  9904. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9905. return BfModuleMethodInstance(methodInstance);
  9906. }
  9907. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9908. {
  9909. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9910. if (methodInstance->mIsForeignMethodDef)
  9911. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9912. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9913. }
  9914. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9915. {
  9916. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9917. return NULL;
  9918. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9919. if (outerLocal == NULL)
  9920. return NULL;
  9921. BfTypeVector genericArgs;
  9922. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9923. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9924. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9925. }
  9926. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9927. {
  9928. HashContext hashCtx;
  9929. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9930. {
  9931. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9932. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9933. if (methodInstance->GetNumGenericArguments() != 0)
  9934. {
  9935. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9936. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9937. hashCtx.Mixin(methodGenericArg->mTypeId);
  9938. }
  9939. };
  9940. _MixinMethodInstance(methodInstance);
  9941. if (methodInstance->mMethodDef->mIsLocalMethod)
  9942. {
  9943. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9944. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9945. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9946. }
  9947. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9948. }
  9949. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9950. {
  9951. BfIRValue globalValue;
  9952. BfIRValue* globalValuePtr = NULL;
  9953. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9954. {
  9955. globalValue = *globalValuePtr;
  9956. }
  9957. if (!globalValue)
  9958. {
  9959. // This is necessary to reify the interface type
  9960. PopulateType(ifaceType);
  9961. StringT<128> slotVarName;
  9962. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9963. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9964. BfIRValue value;
  9965. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9966. {
  9967. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  9968. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  9969. int virtSlotIdx = ifaceType->mSlotNum + 1;
  9970. value = GetConstValue32(virtSlotIdx);*/
  9971. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  9972. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  9973. }
  9974. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  9975. mInterfaceSlotRefs[ifaceType] = globalValue;
  9976. }
  9977. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  9978. }
  9979. void BfModule::HadSlotCountDependency()
  9980. {
  9981. if (mCompiler->mIsResolveOnly)
  9982. return;
  9983. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  9984. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  9985. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  9986. }
  9987. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  9988. {
  9989. if (mIsScratchModule)
  9990. {
  9991. // Just fake it for the extern and unspecialized modules
  9992. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  9993. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  9994. }
  9995. BfIRValue globalValue;
  9996. auto fieldDef = fieldInstance->GetFieldDef();
  9997. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  9998. {
  9999. if (fieldInstance->mConstIdx != -1)
  10000. {
  10001. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10002. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10003. }
  10004. else
  10005. {
  10006. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10007. }
  10008. }
  10009. BfIRValue* globalValuePtr = NULL;
  10010. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10011. {
  10012. globalValue = *globalValuePtr;
  10013. BF_ASSERT(globalValue);
  10014. }
  10015. else
  10016. {
  10017. StringT<128> staticVarName;
  10018. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10019. auto typeType = fieldInstance->GetResolvedType();
  10020. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10021. {
  10022. typeType = typeType->GetUnderlyingType();
  10023. }
  10024. PopulateType(typeType);
  10025. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10026. {
  10027. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10028. mBfIRBuilder->MapType(typeType),
  10029. false,
  10030. BfIRLinkageType_External,
  10031. BfIRValue(),
  10032. staticVarName,
  10033. IsThreadLocal(fieldInstance));
  10034. if (!mBfIRBuilder->mIgnoreWrites)
  10035. {
  10036. // Only store this if we actually did the creation
  10037. BF_ASSERT(globalValue);
  10038. mStaticFieldRefs[fieldInstance] = globalValue;
  10039. }
  10040. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10041. }
  10042. }
  10043. auto type = fieldInstance->GetResolvedType();
  10044. if (type->IsValuelessType())
  10045. return BfTypedValue(globalValue, type);
  10046. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10047. }
  10048. BfTypedValue BfModule::GetThis()
  10049. {
  10050. auto useMethodState = mCurMethodState;
  10051. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10052. {
  10053. useMethodState = useMethodState->mPrevMethodState;
  10054. }
  10055. if (useMethodState != NULL)
  10056. {
  10057. // Fake a 'this' for var field resolution
  10058. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10059. {
  10060. auto thisType = mCurTypeInstance;
  10061. if (thisType->IsValueType())
  10062. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10063. else
  10064. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10065. }
  10066. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10067. {
  10068. return BfTypedValue();
  10069. }
  10070. }
  10071. else
  10072. {
  10073. //TODO: Do we allow useMethodState to be NULL anymore?
  10074. return BfTypedValue();
  10075. }
  10076. // if (useMethodState->HasNonStaticMixin())
  10077. // {
  10078. // auto checkMethodState = useMethodState;
  10079. // while (checkMethodState != NULL)
  10080. // {
  10081. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10082. // {
  10083. // auto varDecl = checkMethodState->mLocals[localIdx];
  10084. // if (varDecl->mName == "this")
  10085. // {
  10086. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10087. // if (varDecl->mIsSplat)
  10088. // {
  10089. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10090. // }
  10091. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10092. // {
  10093. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10094. // }
  10095. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10096. // }
  10097. // }
  10098. //
  10099. // checkMethodState = checkMethodState->mPrevMethodState;
  10100. // }
  10101. // }
  10102. // Check mixin state for 'this'
  10103. {
  10104. auto checkMethodState = useMethodState;
  10105. while (checkMethodState != NULL)
  10106. {
  10107. if (checkMethodState->mMixinState != NULL)
  10108. {
  10109. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10110. if (thisValue)
  10111. {
  10112. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10113. if (!thisValue.mType->IsValueType())
  10114. thisValue = LoadValue(thisValue);
  10115. return thisValue;
  10116. }
  10117. }
  10118. checkMethodState = checkMethodState->mPrevMethodState;
  10119. }
  10120. }
  10121. auto curMethodInstance = mCurMethodInstance;
  10122. if (useMethodState->mMethodInstance != NULL)
  10123. curMethodInstance = useMethodState->mMethodInstance;
  10124. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10125. {
  10126. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10127. {
  10128. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10129. if (constLocal.mIsThis)
  10130. {
  10131. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10132. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10133. }
  10134. }
  10135. return BfTypedValue();
  10136. }
  10137. bool preferValue = !IsTargetingBeefBackend();
  10138. if (useMethodState->mLocals.IsEmpty())
  10139. {
  10140. // 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
  10141. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10142. return BfTypedValue();
  10143. }
  10144. auto thisLocal = useMethodState->mLocals[0];
  10145. BF_ASSERT(thisLocal->mIsThis);
  10146. BfIRValue thisValue;
  10147. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10148. thisValue = thisLocal->mValue;
  10149. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10150. thisValue = thisLocal->mAddr;
  10151. else
  10152. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10153. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10154. if (useMethodState->mClosureState != NULL)
  10155. {
  10156. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10157. if (closureTypeInst != NULL)
  10158. {
  10159. if (closureTypeInst->mFieldInstances.size() > 0)
  10160. {
  10161. auto& field = closureTypeInst->mFieldInstances[0];
  10162. auto fieldDef = field.GetFieldDef();
  10163. if (fieldDef->mName == "__this")
  10164. {
  10165. if (mCurMethodState->mClosureState->mCapturing)
  10166. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10167. // This is a captured 'this'
  10168. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10169. if (field.mResolvedType->IsRef())
  10170. {
  10171. auto refType = (BfRefType*)field.mResolvedType;
  10172. auto underlyingType = refType->GetUnderlyingType();
  10173. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10174. }
  10175. if (field.mResolvedType->IsObject())
  10176. {
  10177. result = LoadValue(result);
  10178. result.mKind = BfTypedValueKind_ThisValue;
  10179. }
  10180. else
  10181. {
  10182. if (fieldDef->mIsReadOnly)
  10183. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10184. else
  10185. result.mKind = BfTypedValueKind_ThisAddr;
  10186. }
  10187. return result;
  10188. }
  10189. }
  10190. return BfTypedValue();
  10191. }
  10192. if (useMethodState->mClosureState->mCapturing)
  10193. {
  10194. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10195. if (thisType->IsValueType())
  10196. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10197. else
  10198. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10199. }
  10200. }
  10201. auto localDef = useMethodState->mLocals[0];
  10202. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10203. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10204. {
  10205. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10206. {
  10207. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10208. }
  10209. if (localDef->mIsSplat)
  10210. {
  10211. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10212. }
  10213. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10214. }
  10215. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10216. }
  10217. BfLocalVariable* BfModule::GetThisVariable()
  10218. {
  10219. if (mCurMethodState == NULL)
  10220. return NULL;
  10221. auto methodState = mCurMethodState->GetNonCaptureState();
  10222. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10223. return methodState->mLocals[0];
  10224. return NULL;
  10225. }
  10226. bool BfModule::IsInGeneric()
  10227. {
  10228. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10229. }
  10230. bool BfModule::IsInSpecializedGeneric()
  10231. {
  10232. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10233. return false;
  10234. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10235. }
  10236. bool BfModule::IsInSpecializedSection()
  10237. {
  10238. return IsInSpecializedGeneric() ||
  10239. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10240. }
  10241. bool BfModule::IsInUnspecializedGeneric()
  10242. {
  10243. if (mCurMethodInstance != NULL)
  10244. return mCurMethodInstance->mIsUnspecialized;
  10245. return false;
  10246. }
  10247. //////////////////////////////////////////////////////////////////////////
  10248. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10249. {
  10250. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10251. if (type->IsValuelessType())
  10252. return mBfIRBuilder->GetFakeVal();
  10253. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10254. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10255. {
  10256. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10257. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10258. }
  10259. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10260. auto typeOptions = GetTypeOptions();
  10261. if (typeOptions != NULL)
  10262. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10263. // Local variable inits are implicitly handled in the Beef Backend
  10264. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10265. {
  10266. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10267. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10268. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10269. mBfIRBuilder->ClearDebugLocation(storeInst);
  10270. mBfIRBuilder->SetInsertPoint(prevBlock);
  10271. }
  10272. return allocaInst;
  10273. }
  10274. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10275. {
  10276. if (localVar->mResolvedType->IsVar())
  10277. {
  10278. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL) || (mHadVarUsage));
  10279. }
  10280. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10281. mCurMethodState->mLocals.push_back(localVar);
  10282. BfLocalVarEntry* localVarEntryPtr;
  10283. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10284. {
  10285. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10286. localVarEntryPtr->mLocalVar = localVar;
  10287. }
  10288. }
  10289. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10290. {
  10291. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10292. {
  10293. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10294. {
  10295. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10296. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10297. }
  10298. }
  10299. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10300. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10301. (mHasFullDebugInfo) &&
  10302. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10303. {
  10304. auto varType = localVarDef->mResolvedType;
  10305. if (localVarDef->mResolvedType->IsValuelessType())
  10306. {
  10307. }
  10308. else
  10309. {
  10310. bool isByAddr = false;
  10311. auto diValue = localVarDef->mValue;
  10312. if (localVarDef->mConstValue)
  10313. diValue = localVarDef->mConstValue;
  10314. else if (localVarDef->mAddr)
  10315. {
  10316. diValue = localVarDef->mAddr;
  10317. isByAddr = true;
  10318. }
  10319. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10320. bool didConstToMem = false;
  10321. bool isConstant = false;
  10322. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10323. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10324. else if (localVarDef->mConstValue)
  10325. {
  10326. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10327. isConstant =
  10328. (constant->mConstType < BfConstType_GlobalVar) ||
  10329. (constant->mConstType == BfConstType_AggZero) ||
  10330. (constant->mConstType == BfConstType_Array);
  10331. if (isConstant)
  10332. {
  10333. if (localVarDef->mResolvedType->IsComposite())
  10334. {
  10335. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10336. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10337. if (IsTargetingBeefBackend())
  10338. {
  10339. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10340. didConstToMem = true;
  10341. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10342. }
  10343. else
  10344. {
  10345. isByAddr = true;
  10346. mBfIRBuilder->SaveDebugLocation();
  10347. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10348. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10349. mBfIRBuilder->ClearDebugLocation();
  10350. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10351. auto addrVal = CreateAlloca(ptrType);
  10352. mBfIRBuilder->CreateStore(constMem, addrVal);
  10353. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10354. diValue = addrVal;
  10355. didConstToMem = true;
  10356. mBfIRBuilder->SetInsertPoint(prevBlock);
  10357. mBfIRBuilder->RestoreDebugLocation();
  10358. }
  10359. }
  10360. if (mCompiler->mOptions.IsCodeView())
  10361. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10362. }
  10363. }
  10364. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10365. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10366. localVarDef->mDbgVarInst = diVariable;
  10367. if (mBfIRBuilder->HasDebugLocation())
  10368. {
  10369. if ((isConstant) && (!didConstToMem))
  10370. {
  10371. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10372. }
  10373. else
  10374. {
  10375. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10376. {
  10377. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10378. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10379. }
  10380. if (isByAddr)
  10381. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10382. else if (diValue)
  10383. {
  10384. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10385. }
  10386. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10387. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10388. }
  10389. }
  10390. }
  10391. }
  10392. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10393. DoAddLocalVariable(localVarDef);
  10394. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10395. if (localVarDef->mLocalVarId == -1)
  10396. {
  10397. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10398. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10399. }
  10400. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10401. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10402. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10403. {
  10404. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10405. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10406. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10407. }
  10408. return localVarDef;
  10409. }
  10410. void BfModule::CreateDIRetVal()
  10411. {
  10412. if (!WantsDebugInfo())
  10413. return;
  10414. /*if (!mCurMethodState->mRetVal)
  10415. {
  10416. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10417. return;
  10418. }*/
  10419. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10420. {
  10421. BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mHadVarUsage));
  10422. BfType* dbgType = mCurMethodInstance->mReturnType;
  10423. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10424. if (mCurMethodInstance->HasStructRet())
  10425. {
  10426. BF_ASSERT(mCurMethodState->mRetValAddr);
  10427. dbgType = CreatePointerType(dbgType);
  10428. dbgValue = mCurMethodState->mRetValAddr;
  10429. }
  10430. else
  10431. {
  10432. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10433. }
  10434. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10435. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10436. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10437. }
  10438. }
  10439. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10440. {
  10441. BfLocalVarEntry* localVarEntryPtr = NULL;
  10442. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10443. {
  10444. auto checkLocal = localVarEntryPtr->mLocalVar;
  10445. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10446. {
  10447. BfError* error;
  10448. if (checkLocal->mIsImplicitParam)
  10449. return; // Ignore 'redefinition'
  10450. if (checkLocal->IsParam())
  10451. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10452. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10453. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10454. else
  10455. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10456. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10457. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10458. return;
  10459. }
  10460. }
  10461. }
  10462. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10463. {
  10464. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10465. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10466. {
  10467. if (tokenNode->GetToken() == BfToken_Colon)
  10468. {
  10469. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10470. {
  10471. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10472. return NULL;
  10473. }
  10474. return &mCurMethodState->mHeadScope;
  10475. }
  10476. else if (tokenNode->GetToken() == BfToken_Mixin)
  10477. {
  10478. if (fromMixinState == NULL)
  10479. {
  10480. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10481. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10482. return mCurMethodState->mCurScope;
  10483. }
  10484. fromMixinState->mUsedInvocationScope = true;
  10485. return fromMixinState->mTargetScope;
  10486. }
  10487. else if (tokenNode->GetToken() == BfToken_New)
  10488. return NULL;
  10489. }
  10490. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10491. {
  10492. auto findLabel = scopeName->ToString();
  10493. bool crossedDeferredBlock = false;
  10494. auto checkScope = mCurMethodState->mCurScope;
  10495. while (checkScope != NULL)
  10496. {
  10497. if (checkScope->mIsDeferredBlock)
  10498. crossedDeferredBlock = true;
  10499. if (checkScope->mLabel == findLabel)
  10500. {
  10501. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10502. {
  10503. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10504. return NULL;
  10505. }
  10506. return checkScope;
  10507. }
  10508. checkScope = checkScope->mPrevScope;
  10509. }
  10510. if (!inMixinDecl)
  10511. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10512. }
  10513. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10514. {
  10515. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10516. }
  10517. return mCurMethodState->mCurScope;
  10518. }
  10519. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10520. {
  10521. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10522. }
  10523. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10524. {
  10525. auto scopeData = FindScope(scopeName, false);
  10526. if (scopeData == NULL)
  10527. return NULL;
  10528. int scopeDepth = scopeData->GetDepth();
  10529. // Find the first break data that is at or below the depth of our requested scope
  10530. auto breakData = mCurMethodState->mBreakData;
  10531. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10532. {
  10533. if (breakData->mScope->mIsConditional)
  10534. return NULL;
  10535. breakData = breakData->mPrevBreakData;
  10536. }
  10537. return breakData;
  10538. }
  10539. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10540. {
  10541. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10542. if (!IsTargetingBeefBackend())
  10543. return;
  10544. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10545. {
  10546. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10547. }
  10548. }
  10549. void BfModule::ClearLifetimeEnds()
  10550. {
  10551. auto scopeData = mCurMethodState->mCurScope;
  10552. while (scopeData != NULL)
  10553. {
  10554. scopeData->mDeferredLifetimeEnds.Clear();
  10555. scopeData = scopeData->mPrevScope;
  10556. }
  10557. }
  10558. bool BfModule::WantsDebugInfo()
  10559. {
  10560. if ((mCurMethodInstance != NULL) &&
  10561. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10562. return false;
  10563. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10564. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10565. }
  10566. BfTypeOptions* BfModule::GetTypeOptions()
  10567. {
  10568. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10569. return mCurMethodState->mMethodTypeOptions;
  10570. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10571. }
  10572. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10573. {
  10574. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10575. while (checkScope != NULL)
  10576. {
  10577. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10578. return true;
  10579. if (checkScope == scope)
  10580. break;
  10581. checkScope = checkScope->mPrevScope;
  10582. }
  10583. return false;
  10584. }
  10585. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10586. {
  10587. // Is there anything we need to do here?
  10588. if (mBfIRBuilder->mIgnoreWrites)
  10589. {
  10590. // Just visit deferred blocks
  10591. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10592. while (checkScope != NULL)
  10593. {
  10594. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10595. while (deferredCallEntry != NULL)
  10596. {
  10597. if (deferredCallEntry->mDeferredBlock != NULL)
  10598. {
  10599. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10600. }
  10601. deferredCallEntry = deferredCallEntry->mNext;
  10602. }
  10603. if (checkScope == scopeData)
  10604. break;
  10605. checkScope = checkScope->mPrevScope;
  10606. }
  10607. return;
  10608. }
  10609. // Why did we want to do SetIllegalSrcPos here?
  10610. // Don't we always want to step onto these instances?
  10611. // Find a case where we don't and perhaps only do it there.
  10612. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10613. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10614. //SetIllegalSrcPos();
  10615. bool setSrcPos = false;
  10616. bool wantsNop = true;
  10617. BfAstNode* deferCloseNode = NULL;
  10618. if (mCurMethodState->mInPostReturn)
  10619. {
  10620. // These won't get used, they are post-return
  10621. return;
  10622. }
  10623. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10624. BfScopeData* scopeJumpBlock = NULL;
  10625. bool hadExtraDeferredLifetimeEnds = false;
  10626. auto _FlushLifetimeEnds = [&]()
  10627. {
  10628. for (auto lifetimeEnd : deferredLifetimeEnds)
  10629. {
  10630. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10631. mBfIRBuilder->ClearDebugLocation_Last();
  10632. }
  10633. deferredLifetimeEnds.clear();
  10634. };
  10635. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10636. while (checkScope != NULL)
  10637. {
  10638. if (checkScope->mCloseNode != NULL)
  10639. deferCloseNode = checkScope->mCloseNode;
  10640. if (doneBlock)
  10641. {
  10642. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10643. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10644. {
  10645. if (checkHandler.mDoneBlock == doneBlock)
  10646. {
  10647. scopeJumpBlock = checkScope;
  10648. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10649. mBfIRBuilder->ClearDebugLocation_Last();
  10650. _FlushLifetimeEnds();
  10651. break;
  10652. }
  10653. }
  10654. if (scopeJumpBlock != NULL)
  10655. break;
  10656. }
  10657. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10658. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10659. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10660. if (hasWork)
  10661. {
  10662. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10663. if (deferCloseNode != NULL)
  10664. {
  10665. UpdateSrcPos(deferCloseNode);
  10666. }
  10667. if (doneBlock)
  10668. {
  10669. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10670. String blockName = "deferredCalls";
  10671. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10672. BfDeferredHandler deferredHandler;
  10673. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10674. {
  10675. mBfIRBuilder->SaveDebugLocation();
  10676. mBfIRBuilder->ClearDebugLocation();
  10677. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10678. mBfIRBuilder->RestoreDebugLocation();
  10679. }
  10680. else
  10681. {
  10682. // Definitely chain
  10683. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10684. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10685. mBfIRBuilder->ClearDebugLocation_Last();
  10686. _FlushLifetimeEnds();
  10687. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10688. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10689. }
  10690. deferredHandler.mDoneBlock = doneBlock;
  10691. if (!mBfIRBuilder->mIgnoreWrites)
  10692. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10693. if (checkScope == &mCurMethodState->mHeadScope)
  10694. {
  10695. if (!mCurMethodState->mDIRetVal)
  10696. {
  10697. // 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
  10698. // be scoped to the physical method
  10699. /*if (deferCloseNode != NULL)
  10700. {
  10701. UpdateSrcPos(deferCloseNode);
  10702. }*/
  10703. CreateDIRetVal();
  10704. }
  10705. }
  10706. if (checkScope != mCurMethodState->mTailScope)
  10707. {
  10708. if (deferredHandler.mHandlerBlock.IsFake())
  10709. {
  10710. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10711. }
  10712. if (!mBfIRBuilder->mIgnoreWrites)
  10713. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10714. }
  10715. }
  10716. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10717. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10718. while (deferredCallEntry != NULL)
  10719. {
  10720. BfDeferredCallEmitState deferredCallEmitState;
  10721. deferredCallEmitState.mCloseNode = deferCloseNode;
  10722. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10723. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10724. if (deferCloseNode != NULL)
  10725. {
  10726. UpdateSrcPos(deferCloseNode);
  10727. }
  10728. if (wantsNop)
  10729. EmitEnsureInstructionAt();
  10730. wantsNop = false;
  10731. if (deferredCallEntry->mDeferredBlock != NULL)
  10732. {
  10733. auto itr = handledSet.insert(deferredCallEntry);
  10734. if (!itr.second)
  10735. {
  10736. // Already handled, can happen if we defer again within the block
  10737. deferredCallEntry = deferredCallEntry->mNext;
  10738. continue;
  10739. }
  10740. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10741. EmitDeferredCall(*deferredCallEntry);
  10742. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10743. {
  10744. // The list changed, start over and ignore anything we've already handled
  10745. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10746. }
  10747. else
  10748. deferredCallEntry = deferredCallEntry->mNext;
  10749. }
  10750. else
  10751. {
  10752. EmitDeferredCall(*deferredCallEntry);
  10753. deferredCallEntry = deferredCallEntry->mNext;
  10754. }
  10755. }
  10756. if (checkScope->mSavedStack)
  10757. {
  10758. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10759. if (mCurMethodState->mDynStackRevIdx)
  10760. {
  10761. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10762. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10763. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10764. }
  10765. }
  10766. }
  10767. if (!checkScope->mIsScopeHead)
  10768. {
  10769. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10770. if (!IsTargetingBeefBackend())
  10771. {
  10772. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10773. {
  10774. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10775. }
  10776. }
  10777. else
  10778. {
  10779. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10780. {
  10781. deferredLifetimeEnds.Add(lifetimeEnd);
  10782. }
  10783. }
  10784. }
  10785. if (checkScope == scopeData)
  10786. break;
  10787. checkScope = checkScope->mPrevScope;
  10788. }
  10789. if ((doneBlock) && (scopeJumpBlock == NULL))
  10790. {
  10791. mBfIRBuilder->CreateBr(doneBlock);
  10792. mBfIRBuilder->ClearDebugLocation_Last();
  10793. }
  10794. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10795. // may have been created when other scope lifetimes were available
  10796. _FlushLifetimeEnds();
  10797. // Emit lifetimeEnds after the branch for Beef
  10798. /*if (IsTargetingBeefBackend())
  10799. {
  10800. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10801. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10802. while (checkScope != NULL)
  10803. {
  10804. if (checkScope == scopeJumpBlock)
  10805. break;
  10806. if (!checkScope->mIsScopeHead)
  10807. {
  10808. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10809. {
  10810. if (needsEnsureInst)
  10811. {
  10812. needsEnsureInst = false;
  10813. }
  10814. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10815. }
  10816. }
  10817. if (checkScope == scopeData)
  10818. break;
  10819. checkScope = checkScope->mPrevScope;
  10820. }
  10821. }*/
  10822. }
  10823. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10824. {
  10825. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10826. {
  10827. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10828. while (deferredLocalAssignData != NULL)
  10829. {
  10830. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10831. break;
  10832. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10833. deferredLocalAssignData->mIsUnconditional = false;
  10834. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10835. }
  10836. }
  10837. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10838. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10839. // int b;
  10840. // if (cond) return;
  10841. // else b = 1;
  10842. // Use(b);
  10843. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10844. {
  10845. auto localDef = mCurMethodState->mLocals[localIdx];
  10846. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10847. mCurMethodState->LocalDefined(localDef);
  10848. }
  10849. }
  10850. void BfModule::CreateReturn(BfIRValue val)
  10851. {
  10852. if (mCurMethodInstance->mReturnType->IsComposite())
  10853. {
  10854. // Store to sret
  10855. BF_ASSERT(val);
  10856. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10857. mBfIRBuilder->CreateRetVoid();
  10858. }
  10859. else
  10860. {
  10861. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10862. {
  10863. mBfIRBuilder->CreateRetVoid();
  10864. }
  10865. else
  10866. {
  10867. BF_ASSERT(val);
  10868. mBfIRBuilder->CreateRet(val);
  10869. }
  10870. }
  10871. }
  10872. void BfModule::EmitReturn(BfIRValue val)
  10873. {
  10874. if (mCurMethodState->mIRExitBlock)
  10875. {
  10876. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10877. {
  10878. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10879. {
  10880. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10881. if (!mCurMethodState->mRetVal)
  10882. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10883. mBfIRBuilder->CreateStore(val, retVal);
  10884. }
  10885. }
  10886. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10887. }
  10888. else
  10889. {
  10890. EmitDeferredScopeCalls(false, NULL);
  10891. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10892. mBfIRBuilder->CreateRetVoid();
  10893. else
  10894. mBfIRBuilder->CreateRet(val);
  10895. }
  10896. mCurMethodState->SetHadReturn(true);
  10897. mCurMethodState->mLeftBlockUncond = true;
  10898. }
  10899. void BfModule::EmitDefaultReturn()
  10900. {
  10901. if (mCurMethodState->mInDeferredBlock)
  10902. return;
  10903. if (mCurMethodState->mIRExitBlock)
  10904. {
  10905. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10906. }
  10907. else
  10908. {
  10909. if (mCurMethodInstance->mReturnType->IsVoid())
  10910. mBfIRBuilder->CreateRetVoid();
  10911. else
  10912. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10913. }
  10914. mCurMethodState->SetHadReturn(true);
  10915. mCurMethodState->mLeftBlockUncond = true;
  10916. }
  10917. void BfModule::AssertErrorState()
  10918. {
  10919. if (mIgnoreErrors)
  10920. return;
  10921. if (mHadBuildError)
  10922. return;
  10923. if (mCurTypeInstance != NULL)
  10924. {
  10925. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10926. return;
  10927. }
  10928. if (mCurMethodInstance != NULL)
  10929. {
  10930. if (mCurMethodInstance->mIsUnspecializedVariation)
  10931. return;
  10932. }
  10933. // We want the module to be marked as failed even if it's just an error in the parser
  10934. if (mCurMethodInstance != NULL)
  10935. mCurMethodInstance->mHasFailed = true;
  10936. mHadBuildError = true;
  10937. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10938. if (mCurTypeInstance != NULL)
  10939. {
  10940. if (mCurTypeInstance->mTypeFailed)
  10941. return;
  10942. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10943. return;
  10944. }
  10945. if (mCurMethodInstance != NULL)
  10946. {
  10947. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10948. return;
  10949. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10950. return;
  10951. }
  10952. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10953. }
  10954. void BfModule::AssertParseErrorState()
  10955. {
  10956. if (mCompiler->mRevision == 1)
  10957. AssertErrorState();
  10958. }
  10959. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10960. {
  10961. BF_ASSERT(delegateType->IsDelegate());
  10962. auto typeInst = delegateType->ToTypeInstance();
  10963. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10964. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10965. return invokeMethodInstance->mReturnType;
  10966. }
  10967. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  10968. {
  10969. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  10970. }
  10971. void BfModule::CreateDelegateInvokeMethod()
  10972. {
  10973. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  10974. //mBfIRBuilder->ClearDebugLocation();
  10975. SetIllegalSrcPos();
  10976. auto typeInstance = mCurTypeInstance;
  10977. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  10978. SizedArray<BfIRType, 4> staticParamTypes;
  10979. SizedArray<BfIRValue, 4> staticFuncArgs;
  10980. SizedArray<BfIRValue, 4> memberFuncArgs;
  10981. auto multicastDelegateType = typeInstance->mBaseType;
  10982. if (multicastDelegateType->mFieldInstances.size() != 2)
  10983. {
  10984. AssertErrorState();
  10985. return;
  10986. }
  10987. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  10988. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  10989. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  10990. BfExprEvaluator exprEvaluator(this);
  10991. SizedArray<BfIRType, 8> origParamTypes;
  10992. BfIRType origReturnType;
  10993. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  10994. if (mCurMethodInstance->mReturnType->IsValueType())
  10995. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  10996. int thisIdx = 0;
  10997. if (mCurMethodInstance->HasStructRet())
  10998. {
  10999. thisIdx = 1;
  11000. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11001. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11002. }
  11003. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11004. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11005. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11006. {
  11007. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11008. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11009. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11010. }
  11011. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11012. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11013. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11014. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11015. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11016. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11017. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11018. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11019. BfIRValue nonStaticResult;
  11020. BfIRValue staticResult;
  11021. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11022. /// Non-static invocation
  11023. {
  11024. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11025. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11026. mBfIRBuilder->SetInsertPoint(trueBB);
  11027. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11028. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11029. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11030. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11031. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11032. if (callingConv != BfIRCallingConv_CDecl)
  11033. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11034. mCurMethodState->SetHadReturn(false);
  11035. mCurMethodState->mLeftBlockUncond = false;
  11036. mCurMethodState->mLeftBlockCond = false;
  11037. mBfIRBuilder->CreateBr(doneBB);
  11038. }
  11039. // Static invocation
  11040. {
  11041. mBfIRBuilder->AddBlock(falseBB);
  11042. mBfIRBuilder->SetInsertPoint(falseBB);
  11043. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11044. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11045. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11046. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11047. if (callingConv == BfIRCallingConv_ThisCall)
  11048. callingConv = BfIRCallingConv_CDecl;
  11049. if (callingConv != BfIRCallingConv_CDecl)
  11050. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11051. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11052. // {
  11053. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11054. //
  11055. // }
  11056. mCurMethodState->SetHadReturn(false);
  11057. mCurMethodState->mLeftBlockUncond = false;
  11058. mCurMethodState->mLeftBlockCond = false;
  11059. mBfIRBuilder->CreateBr(doneBB);
  11060. }
  11061. mBfIRBuilder->AddBlock(doneBB);
  11062. mBfIRBuilder->SetInsertPoint(doneBB);
  11063. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11064. {
  11065. mBfIRBuilder->CreateRetVoid();
  11066. }
  11067. else
  11068. {
  11069. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11070. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11071. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11072. mBfIRBuilder->CreateRet(phi);
  11073. }
  11074. }
  11075. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11076. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11077. {
  11078. auto typeDef = typeInstance->mTypeDef;
  11079. auto methodDeclaration = methodDef->mMethodDeclaration;
  11080. if (!mCompiler->mIsResolveOnly)
  11081. return true;
  11082. if (typeInstance->IsGenericTypeInstance())
  11083. {
  11084. // We only really want to process the unspecialized type for autocompletion
  11085. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11086. return false;
  11087. }
  11088. BfAstNode* checkNode = methodDeclaration;
  11089. if (methodDeclaration == NULL)
  11090. checkNode = methodDef->mBody;
  11091. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11092. {
  11093. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11094. return true;
  11095. }
  11096. return false;
  11097. }
  11098. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11099. {
  11100. methodInst->mAppendAllocAlign = 1;
  11101. }
  11102. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11103. {
  11104. BP_ZONE("BfModule::TryConstCalcAppend");
  11105. if (mCompiler->mIsResolveOnly)
  11106. return BfTypedValue();
  11107. // We want to regenerate all ctor calls when the method internals change
  11108. {
  11109. auto checkTypeInst = methodInst->GetOwner();
  11110. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11111. {
  11112. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11113. checkTypeInst = GetBaseType(checkTypeInst);
  11114. }
  11115. }
  11116. if (!methodInst->mMayBeConst)
  11117. return BfTypedValue();
  11118. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11119. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11120. bool wasAllConst = true;
  11121. int argIdx = 0;
  11122. int paramIdx = 0;
  11123. while (true)
  11124. {
  11125. if (argIdx >= (int)args.size())
  11126. break;
  11127. auto paramType = methodInst->GetParamType(paramIdx);
  11128. PopulateType(paramType);
  11129. int argCount = 0;
  11130. if (!paramType->IsValuelessType())
  11131. {
  11132. if (methodInst->GetParamIsSplat(paramIdx))
  11133. argCount = paramType->GetSplatCount();
  11134. else
  11135. argCount = 1;
  11136. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11137. {
  11138. auto arg = args[argIdx + argOfs];
  11139. if (!arg.IsConst())
  11140. {
  11141. wasAllConst = false;
  11142. if (!isFirstRun)
  11143. {
  11144. auto& param = methodInst->mParams[argIdx];
  11145. if (param.mReferencedInConstPass)
  11146. {
  11147. // If this param is required as part of the const calculation then
  11148. // we require that it be const...
  11149. return BfTypedValue();
  11150. }
  11151. }
  11152. }
  11153. }
  11154. }
  11155. paramIdx++;
  11156. argIdx += argCount;
  11157. }
  11158. auto methodDef = methodInst->mMethodDef;
  11159. auto methodDecl = methodDef->GetMethodDeclaration();
  11160. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11161. if (methodDeclBlock == NULL)
  11162. return BfTypedValue();
  11163. BfTypedValue constValue;
  11164. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11165. auto checkState = mCurMethodState->mConstResolveState;
  11166. while (checkState != NULL)
  11167. {
  11168. if (checkState->mMethodInstance == methodInst)
  11169. {
  11170. return BfTypedValue();
  11171. }
  11172. checkState = checkState->mPrevConstResolveState;
  11173. }
  11174. //auto accumValue = GetConstValue(0);
  11175. bool failed = false;
  11176. //
  11177. {
  11178. BfConstResolveState constResolveState;
  11179. constResolveState.mMethodInstance = methodInst;
  11180. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11181. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11182. BfMethodState methodState;
  11183. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11184. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11185. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11186. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11187. methodState.mConstResolveState = &constResolveState;
  11188. int argIdx = 0;
  11189. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11190. {
  11191. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11192. continue;
  11193. auto paramType = methodInst->GetParamType(paramIdx);
  11194. // Fix this after we allow structs to be consts
  11195. //BF_ASSERT(!paramType->IsSplattable());
  11196. BfLocalVariable* localVar = new BfLocalVariable();
  11197. localVar->mName = methodInst->GetParamName(paramIdx);
  11198. localVar->mResolvedType = paramType;
  11199. localVar->mConstValue = args[argIdx];
  11200. localVar->mParamIdx = paramIdx;
  11201. AddLocalVariableDef(localVar);
  11202. argIdx++;
  11203. }
  11204. AppendAllocVisitor appendAllocVisitor;
  11205. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11206. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11207. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11208. if (baseCtorAppendValue)
  11209. {
  11210. if (baseCtorAppendValue.mValue.IsFake())
  11211. appendAllocVisitor.mFailed = true;
  11212. else
  11213. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11214. }
  11215. appendAllocVisitor.mModule = this;
  11216. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11217. if (!appendAllocVisitor.mFailed)
  11218. constValue = appendAllocVisitor.mConstAccum;
  11219. if (isFirstRun)
  11220. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11221. if (isFirstRun)
  11222. {
  11223. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11224. {
  11225. auto localVar = mCurMethodState->mLocals[paramIdx];
  11226. if (localVar->mReadFromId != -1)
  11227. {
  11228. auto& param = methodInst->mParams[paramIdx];
  11229. param.mReferencedInConstPass = true;
  11230. }
  11231. }
  11232. }
  11233. }
  11234. mBfIRBuilder->SetInsertPoint(prevBlock);
  11235. if (!constValue)
  11236. {
  11237. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11238. // all-const args
  11239. if (wasAllConst)
  11240. {
  11241. methodInst->mMayBeConst = false;
  11242. }
  11243. }
  11244. return constValue;
  11245. }
  11246. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11247. {
  11248. // Any errors should only be shown in the actual CTOR call
  11249. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11250. auto methodDef = mCurMethodInstance->mMethodDef;
  11251. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11252. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11253. BfTypeInstance* targetType = NULL;
  11254. if (ctorDeclaration->mInitializer != NULL)
  11255. {
  11256. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11257. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11258. }
  11259. else
  11260. targetType = mCurTypeInstance->mBaseType;
  11261. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11262. return NULL;
  11263. auto targetRefNode = methodDef->GetRefNode();
  11264. BfType* targetThisType = targetType;
  11265. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11266. BfExprEvaluator exprEvaluator(this);
  11267. BfResolvedArgs argValues;
  11268. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11269. {
  11270. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11271. }
  11272. //
  11273. {
  11274. }
  11275. BfFunctionBindResult bindResult;
  11276. bindResult.mSkipThis = true;
  11277. bindResult.mWantsArgs = true;
  11278. {
  11279. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11280. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11281. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11282. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11283. }
  11284. if (bindResult.mMethodInstance == NULL)
  11285. {
  11286. AssertErrorState();
  11287. return BfTypedValue();
  11288. }
  11289. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11290. {
  11291. return BfTypedValue();
  11292. }
  11293. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11294. bindResult.mIRArgs.RemoveAt(0);
  11295. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11296. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11297. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11298. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11299. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11300. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11301. if (appendSizeTypedValue)
  11302. return appendSizeTypedValue;
  11303. if (constOnly)
  11304. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11305. bool needsRecalc = false;
  11306. for (auto irArg : bindResult.mIRArgs)
  11307. {
  11308. if (irArg.IsFake())
  11309. needsRecalc = true;
  11310. }
  11311. auto calcAppendArgs = bindResult.mIRArgs;
  11312. if (needsRecalc)
  11313. {
  11314. // Do it again, but without mIgnoreWrites set
  11315. BfResolvedArgs argValues;
  11316. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11317. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11318. BfFunctionBindResult bindResult;
  11319. bindResult.mSkipThis = true;
  11320. bindResult.mWantsArgs = true;
  11321. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11322. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11323. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11324. bindResult.mIRArgs.RemoveAt(0);
  11325. calcAppendArgs = bindResult.mIRArgs;
  11326. }
  11327. BF_ASSERT(calcAppendMethodModule.mFunc);
  11328. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11329. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11330. return appendSizeTypedValue;
  11331. }
  11332. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11333. void BfModule::EmitCtorCalcAppend()
  11334. {
  11335. if (mCompiler->mIsResolveOnly)
  11336. return;
  11337. auto methodDef = mCurMethodInstance->mMethodDef;
  11338. auto methodDecl = methodDef->GetMethodDeclaration();
  11339. Array<BfAstNode*> deferredNodeList;
  11340. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11341. if (methodDeclBlock == NULL)
  11342. return;
  11343. AppendAllocVisitor appendAllocVisitor;
  11344. auto baseCalcAppend = CallBaseCtorCalc(false);
  11345. if (baseCalcAppend)
  11346. {
  11347. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11348. }
  11349. appendAllocVisitor.mModule = this;
  11350. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11351. }
  11352. void BfModule::CreateStaticCtor()
  11353. {
  11354. auto typeDef = mCurTypeInstance->mTypeDef;
  11355. auto methodDef = mCurMethodInstance->mMethodDef;
  11356. BfIRBlock exitBB;
  11357. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11358. {
  11359. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11360. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11361. mBfIRBuilder->MapType(boolType),
  11362. false,
  11363. BfIRLinkageType_Internal,
  11364. GetDefaultValue(boolType),
  11365. "didStaticInit");
  11366. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11367. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11368. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11369. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11370. mBfIRBuilder->SetInsertPoint(initBB);
  11371. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11372. }
  11373. // Do DLL imports
  11374. if (!mDllImportEntries.empty())
  11375. {
  11376. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11377. PopulateType(internalType);
  11378. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11379. if (!getSharedProcAddressInstance)
  11380. {
  11381. if (!mCompiler->mPassInstance->HasFailed())
  11382. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11383. }
  11384. }
  11385. // Fill in initializer values
  11386. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11387. {
  11388. for (auto fieldDef : typeDef->mFields)
  11389. {
  11390. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11391. {
  11392. // For extensions, only handle these fields in the appropriate extension
  11393. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11394. continue;
  11395. UpdateSrcPos(fieldDef->mInitializer);
  11396. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11397. if (!fieldInst->mFieldIncluded)
  11398. continue;
  11399. if (fieldInst->mResolvedType->IsVar())
  11400. {
  11401. BF_ASSERT(mHadVarUsage);
  11402. continue;
  11403. }
  11404. auto assignValue = GetFieldInitializerValue(fieldInst);
  11405. if (assignValue)
  11406. {
  11407. assignValue = LoadValue(assignValue);
  11408. if (!assignValue.mType->IsValuelessType())
  11409. {
  11410. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11411. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11412. }
  11413. }
  11414. }
  11415. }
  11416. }
  11417. else
  11418. {
  11419. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11420. {
  11421. if (tempTypeDef->mFullName == typeDef->mFullName)
  11422. {
  11423. for (auto fieldDef : tempTypeDef->mFields)
  11424. {
  11425. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11426. {
  11427. if (fieldDef->mInitializer != NULL)
  11428. {
  11429. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11430. {
  11431. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11432. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11433. }
  11434. BfType* wantType = NULL;
  11435. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11436. {
  11437. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11438. }
  11439. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11440. }
  11441. }
  11442. }
  11443. }
  11444. }
  11445. }
  11446. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11447. CallChainedMethods(mCurMethodInstance, false);
  11448. }
  11449. void BfModule::EmitDtorBody()
  11450. {
  11451. if (mCurTypeInstance->IsClosure())
  11452. {
  11453. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11454. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11455. auto thisVal = GetThis();
  11456. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11457. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11458. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11459. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11460. SizedArray<BfIRValue, 1> args;
  11461. args.push_back(thisVal.mValue);
  11462. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11463. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11464. // Fall through to Object::~this call
  11465. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11466. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11467. SizedArray<BfIRValue, 1> vals = { basePtr };
  11468. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11469. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11470. mBfIRBuilder->SetTailCall(result);
  11471. return;
  11472. }
  11473. auto typeDef = mCurTypeInstance->mTypeDef;
  11474. auto methodDef = mCurMethodInstance->mMethodDef;
  11475. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11476. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11477. CallChainedMethods(mCurMethodInstance, true);
  11478. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11479. {
  11480. VisitCodeBlock(bodyBlock);
  11481. if (bodyBlock->mCloseBrace != NULL)
  11482. {
  11483. UpdateSrcPos(bodyBlock->mCloseBrace);
  11484. }
  11485. }
  11486. else
  11487. {
  11488. if (methodDeclaration != NULL)
  11489. UpdateSrcPos(methodDeclaration);
  11490. else if (typeDef->mTypeDeclaration != NULL)
  11491. UpdateSrcPos(typeDef->mTypeDeclaration);
  11492. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11493. {
  11494. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11495. }
  11496. }
  11497. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11498. {
  11499. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11500. {
  11501. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11502. auto fieldDef = fieldInst->GetFieldDef();
  11503. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11504. {
  11505. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11506. {
  11507. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11508. }
  11509. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11510. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11511. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11512. continue;
  11513. UpdateSrcPos(fieldDtor);
  11514. BfScopeData scopeData;
  11515. mCurMethodState->AddScope(&scopeData);
  11516. NewScopeState();
  11517. UpdateSrcPos(fieldDtor);
  11518. bool hasDbgInfo = (!fieldDef->mIsConst);
  11519. if (hasDbgInfo)
  11520. {
  11521. mBfIRBuilder->SaveDebugLocation();
  11522. mBfIRBuilder->ClearDebugLocation();
  11523. }
  11524. BfIRValue value;
  11525. if (fieldDef->mIsStatic)
  11526. {
  11527. value = ReferenceStaticField(fieldInst).mValue;
  11528. }
  11529. else
  11530. {
  11531. if (!mCurTypeInstance->IsValueType())
  11532. {
  11533. auto thisValue = GetThis();
  11534. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11535. }
  11536. else
  11537. {
  11538. AssertErrorState();
  11539. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11540. }
  11541. }
  11542. BfIRValue staticVal;
  11543. if (hasDbgInfo)
  11544. {
  11545. BfIRValue dbgShowValue = value;
  11546. BfLocalVariable* localDef = new BfLocalVariable();
  11547. localDef->mName = "_";
  11548. localDef->mResolvedType = fieldInst->mResolvedType;
  11549. localDef->mAddr = value;
  11550. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11551. {
  11552. // Create another pointer indirection, a ref to the gep
  11553. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11554. auto allocaInst = CreateAlloca(refFieldType);
  11555. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11556. localDef->mResolvedType = refFieldType;
  11557. localDef->mAddr = allocaInst;
  11558. }
  11559. mBfIRBuilder->RestoreDebugLocation();
  11560. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11561. // Put back so we actually modify the correct value*/
  11562. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11563. defLocalVar->mAddr = value;
  11564. }
  11565. while (fieldDtor != NULL)
  11566. {
  11567. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11568. {
  11569. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11570. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11571. }
  11572. UpdateSrcPos(fieldDtor);
  11573. VisitEmbeddedStatement(fieldDtor->mBody);
  11574. fieldDtor = fieldDtor->mNextFieldDtor;
  11575. }
  11576. RestoreScopeState();
  11577. }
  11578. }
  11579. if (!methodDef->mIsStatic)
  11580. {
  11581. auto checkBaseType = mCurTypeInstance->mBaseType;
  11582. while (checkBaseType != NULL)
  11583. {
  11584. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11585. {
  11586. if (bodyBlock->mCloseBrace != NULL)
  11587. UpdateSrcPos(bodyBlock->mCloseBrace);
  11588. }
  11589. else
  11590. {
  11591. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11592. }
  11593. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11594. {
  11595. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11596. if (mCompiler->IsSkippingExtraResolveChecks())
  11597. {
  11598. // Nothing
  11599. }
  11600. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11601. {
  11602. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11603. {
  11604. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11605. SizedArray<BfIRValue, 1> vals = { basePtr };
  11606. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11607. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11608. }
  11609. }
  11610. else
  11611. {
  11612. // Invalid base dtor declaration
  11613. AssertErrorState();
  11614. }
  11615. break;
  11616. }
  11617. checkBaseType = checkBaseType->mBaseType;
  11618. }
  11619. }
  11620. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11621. }
  11622. else
  11623. {
  11624. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11625. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11626. // resolve pass, NOT the autocomplete expression
  11627. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11628. {
  11629. if (tempTypeDef->mFullName == typeDef->mFullName)
  11630. {
  11631. for (auto fieldDef : tempTypeDef->mFields)
  11632. {
  11633. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11634. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11635. {
  11636. BfType* fieldType = NULL;
  11637. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11638. {
  11639. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11640. auto curFieldDef = curFieldInstance->GetFieldDef();
  11641. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11642. fieldType = curFieldInstance->GetResolvedType();
  11643. }
  11644. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11645. BfScopeData scopeData;
  11646. mCurMethodState->AddScope(&scopeData);
  11647. NewScopeState();
  11648. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11649. if (fieldType != NULL)
  11650. {
  11651. BfLocalVariable* localDef = new BfLocalVariable();
  11652. localDef->mName = "_";
  11653. localDef->mResolvedType = fieldType;
  11654. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11655. localDef->mIsAssigned = true;
  11656. AddLocalVariableDef(localDef);
  11657. }
  11658. while (fieldDtor != NULL)
  11659. {
  11660. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11661. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11662. UpdateSrcPos(fieldDtor);
  11663. VisitEmbeddedStatement(fieldDtor->mBody);
  11664. fieldDtor = fieldDtor->mNextFieldDtor;
  11665. }
  11666. RestoreScopeState();
  11667. }
  11668. }
  11669. }
  11670. }
  11671. }
  11672. }
  11673. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11674. {
  11675. auto typeInstance = methodInstance->GetOwner();
  11676. bool foundDllImportAttr = false;
  11677. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11678. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11679. {
  11680. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11681. {
  11682. foundDllImportAttr = true;
  11683. }
  11684. }
  11685. if (!foundDllImportAttr)
  11686. {
  11687. AssertErrorState();
  11688. return BfIRValue();
  11689. }
  11690. String name = "bf_hs_preserve@";
  11691. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11692. name += "__imp";
  11693. BfIRType returnType;
  11694. SizedArray<BfIRType, 8> paramTypes;
  11695. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11696. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11697. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11698. BfIRValue initVal;
  11699. if (define)
  11700. {
  11701. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11702. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11703. }
  11704. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11705. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11706. {
  11707. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11708. auto ptrType = CreatePointerType(voidType);
  11709. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11710. }
  11711. return globalVar;
  11712. }
  11713. void BfModule::CreateDllImportMethod()
  11714. {
  11715. if (mBfIRBuilder->mIgnoreWrites)
  11716. return;
  11717. auto globalVar = mFuncReferences[mCurMethodInstance];
  11718. if (!globalVar)
  11719. return;
  11720. bool allowTailCall = true;
  11721. mBfIRBuilder->ClearDebugLocation();
  11722. bool isHotCompile = mCompiler->IsHotCompile();
  11723. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11724. if (isHotCompile)
  11725. {
  11726. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11727. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11728. }
  11729. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11730. BfIRType returnType;
  11731. SizedArray<BfIRType, 8> paramTypes;
  11732. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11733. SizedArray<BfIRValue, 8> args;
  11734. for (int i = 0; i < (int)paramTypes.size(); i++)
  11735. args.push_back(mBfIRBuilder->GetArgument(i));
  11736. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11737. if (isHotCompile)
  11738. {
  11739. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11740. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11741. if (callingConvention == BfIRCallingConv_StdCall)
  11742. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11743. else
  11744. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11745. if (allowTailCall)
  11746. mBfIRBuilder->SetTailCall(result);
  11747. CreateReturn(result);
  11748. mCurMethodState->mHadReturn = true;
  11749. }
  11750. if (HasCompiledOutput())
  11751. {
  11752. BfDllImportEntry dllImportEntry;
  11753. dllImportEntry.mFuncVar = globalVar;
  11754. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11755. mDllImportEntries.push_back(dllImportEntry);
  11756. }
  11757. }
  11758. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11759. {
  11760. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  11761. return BfIRCallingConv_CDecl;
  11762. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11763. return BfIRCallingConv_StdCall;
  11764. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11765. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11766. return BfIRCallingConv_ThisCall;
  11767. return BfIRCallingConv_CDecl;
  11768. }
  11769. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11770. {
  11771. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11772. }
  11773. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11774. {
  11775. BfMethodDef* methodDef = NULL;
  11776. if (methodInstance != NULL)
  11777. methodDef = methodInstance->mMethodDef;
  11778. if (!func)
  11779. return;
  11780. if (mCompiler->mOptions.mNoFramePointerElim)
  11781. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11782. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11783. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11784. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11785. if (methodInstance == NULL)
  11786. return;
  11787. if (methodDef->mImportKind == BfImportKind_Export)
  11788. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11789. if (methodDef->mNoReturn)
  11790. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11791. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11792. if (callingConv != BfIRCallingConv_CDecl)
  11793. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11794. if (isInlined)
  11795. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11796. int argIdx = 0;
  11797. int paramIdx = 0;
  11798. if (methodInstance->HasThis())
  11799. {
  11800. paramIdx = -1;
  11801. }
  11802. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11803. if (methodInstance->HasStructRet())
  11804. {
  11805. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11806. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11807. argIdx++;
  11808. }
  11809. while (argIdx < argCount)
  11810. {
  11811. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11812. paramIdx++;
  11813. BfType* resolvedTypeRef = NULL;
  11814. String paramName;
  11815. bool isSplattable = false;
  11816. bool isThis = paramIdx == -1;
  11817. if (isThis)
  11818. {
  11819. paramName = "this";
  11820. if (methodInstance->mIsClosure)
  11821. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11822. else
  11823. resolvedTypeRef = methodInstance->GetOwner();
  11824. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11825. }
  11826. else if (!methodDef->mNoSplat)
  11827. {
  11828. paramName = methodInstance->GetParamName(paramIdx);
  11829. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11830. if (resolvedTypeRef->IsMethodRef())
  11831. isSplattable = true;
  11832. else if (resolvedTypeRef->IsSplattable())
  11833. {
  11834. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11835. isSplattable = true;
  11836. }
  11837. }
  11838. //
  11839. {
  11840. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11841. if (loweredTypeCode != BfTypeCode_None)
  11842. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11843. }
  11844. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11845. {
  11846. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11847. int addDeref = -1;
  11848. if (resolvedTypeRef->IsRef())
  11849. {
  11850. auto refType = (BfRefType*)resolvedTypeRef;
  11851. auto elementType = refType->mElementType;
  11852. PopulateType(elementType, BfPopulateType_Data);
  11853. addDeref = elementType->mSize;
  11854. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11855. AssertErrorState();
  11856. }
  11857. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11858. {
  11859. if (mCompiler->mOptions.mAllowStructByVal)
  11860. {
  11861. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11862. }
  11863. else
  11864. {
  11865. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11866. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11867. addDeref = resolvedTypeRef->mSize;
  11868. }
  11869. }
  11870. else if (resolvedTypeRef->IsPrimitiveType())
  11871. {
  11872. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11873. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11874. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11875. }
  11876. if (addDeref >= 0)
  11877. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11878. argIdx++;
  11879. };
  11880. if (isSplattable)
  11881. {
  11882. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11883. {
  11884. if (checkType->IsStruct())
  11885. {
  11886. auto checkTypeInstance = checkType->ToTypeInstance();
  11887. if (checkTypeInstance->mBaseType != NULL)
  11888. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11889. if (checkTypeInstance->mIsUnion)
  11890. {
  11891. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11892. checkTypeLambda(unionInnerType, curName + "_data");
  11893. }
  11894. else
  11895. {
  11896. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11897. {
  11898. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11899. auto fieldDef = fieldInstance->GetFieldDef();
  11900. if (fieldInstance->mDataIdx >= 0)
  11901. {
  11902. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11903. }
  11904. }
  11905. }
  11906. if (checkTypeInstance->IsEnum())
  11907. {
  11908. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11909. argIdx++;
  11910. }
  11911. }
  11912. else if (checkType->IsMethodRef())
  11913. {
  11914. auto methodRefType = (BfMethodRefType*)checkType;
  11915. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11916. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11917. {
  11918. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11919. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11920. {
  11921. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11922. }
  11923. else
  11924. {
  11925. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11926. }
  11927. }
  11928. }
  11929. else if (!checkType->IsValuelessType())
  11930. {
  11931. _SetupParam(curName, checkType);
  11932. }
  11933. };
  11934. checkTypeLambda(resolvedTypeRef, paramName);
  11935. paramIdx++;
  11936. continue;
  11937. }
  11938. _SetupParam(paramName, resolvedTypeRef);
  11939. //argIdx++;
  11940. paramIdx++;
  11941. }
  11942. }
  11943. void BfModule::EmitCtorBody(bool& skipBody)
  11944. {
  11945. auto methodInstance = mCurMethodInstance;
  11946. auto methodDef = methodInstance->mMethodDef;
  11947. auto methodDeclaration = methodDef->mMethodDeclaration;
  11948. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11949. auto typeDef = mCurTypeInstance->mTypeDef;
  11950. // Prologue
  11951. mBfIRBuilder->ClearDebugLocation();
  11952. bool hadThisInitializer = false;
  11953. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11954. {
  11955. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11956. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11957. if (targetToken->GetToken() == BfToken_This)
  11958. {
  11959. hadThisInitializer = true;
  11960. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11961. mCurMethodState->LocalDefined(GetThisVariable());
  11962. }
  11963. }
  11964. // Zero out memory for default ctor
  11965. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11966. {
  11967. if (mCurTypeInstance->IsTypedPrimitive())
  11968. {
  11969. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11970. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  11971. }
  11972. else if (mCurTypeInstance->mInstSize > 0)
  11973. {
  11974. BfIRValue fillValue = GetConstValue8(0);
  11975. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  11976. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11977. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11978. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  11979. }
  11980. }
  11981. BfAstNode* baseCtorNode = NULL;
  11982. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  11983. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  11984. else if (methodDef->mBody != NULL)
  11985. baseCtorNode = methodDef->mBody;
  11986. else if (ctorDeclaration != NULL)
  11987. baseCtorNode = ctorDeclaration;
  11988. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  11989. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  11990. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  11991. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  11992. else
  11993. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  11994. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  11995. {
  11996. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  11997. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  11998. {
  11999. BfMethodDef* defaultCtor = NULL;
  12000. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12001. {
  12002. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12003. {
  12004. defaultCtor = methodDef;
  12005. }
  12006. }
  12007. if (defaultCtor != NULL)
  12008. {
  12009. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12010. SetIllegalSrcPos();
  12011. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12012. BfExprEvaluator exprEvaluator(this);
  12013. SizedArray<BfIRValue, 1> irArgs;
  12014. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12015. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12016. }
  12017. }
  12018. }
  12019. // Initialize fields (if applicable)
  12020. if (mCurTypeInstance->IsBoxed())
  12021. {
  12022. skipBody = true;
  12023. }
  12024. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12025. {
  12026. // Field initializers occur in CtorNoBody methods for extensions
  12027. }
  12028. else if (!hadThisInitializer)
  12029. {
  12030. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12031. if ((!mCompiler->mIsResolveOnly) ||
  12032. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12033. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12034. {
  12035. bool hadInlineInitBlock = false;
  12036. BfScopeData scopeData;
  12037. for (auto fieldDef : typeDef->mFields)
  12038. {
  12039. // For extensions, only handle these fields in the appropriate extension
  12040. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12041. continue;
  12042. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12043. {
  12044. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12045. if (!fieldInst->mFieldIncluded)
  12046. continue;
  12047. if (fieldInst->mDataIdx < 0)
  12048. continue;
  12049. if (fieldDef->mInitializer == NULL)
  12050. {
  12051. if (fieldDef->mProtection != BfProtection_Hidden)
  12052. continue;
  12053. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12054. continue;
  12055. }
  12056. if (fieldInst->mResolvedType == NULL)
  12057. {
  12058. BF_ASSERT(mHadBuildError);
  12059. continue;
  12060. }
  12061. if (fieldDef->mInitializer != NULL)
  12062. {
  12063. if (!hadInlineInitBlock)
  12064. {
  12065. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12066. {
  12067. UpdateSrcPos(baseCtorNode);
  12068. // 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
  12069. EmitEnsureInstructionAt();
  12070. BfType* thisType = mCurTypeInstance;
  12071. if (thisType->IsValueType())
  12072. thisType = CreateRefType(thisType);
  12073. SizedArray<BfIRMDNode, 1> diParamTypes;
  12074. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12075. mCurMethodState->AddScope(&scopeData);
  12076. NewScopeState();
  12077. int flags = 0;
  12078. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12079. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12080. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12081. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12082. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12083. UpdateSrcPos(fieldDef->mInitializer);
  12084. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12085. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12086. //
  12087. {
  12088. auto loadedThis = GetThis();
  12089. // LLVM can't handle two variables pointing to the same value
  12090. BfIRValue copiedThisPtr;
  12091. copiedThisPtr = CreateAlloca(thisType);
  12092. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12093. mBfIRBuilder->ClearDebugLocation(storeInst);
  12094. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12095. }
  12096. hadInlineInitBlock = true;
  12097. }
  12098. }
  12099. UpdateSrcPos(fieldDef->mInitializer);
  12100. }
  12101. BfIRValue fieldAddr;
  12102. if (!mCurTypeInstance->IsTypedPrimitive())
  12103. {
  12104. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12105. }
  12106. else
  12107. {
  12108. AssertErrorState();
  12109. }
  12110. auto assignValue = GetFieldInitializerValue(fieldInst);
  12111. if ((fieldAddr) && (assignValue))
  12112. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12113. }
  12114. }
  12115. if (hadInlineInitBlock)
  12116. {
  12117. RestoreScopeState();
  12118. // This gets set to false because of AddScope but we actually are still in the head block
  12119. mCurMethodState->mInHeadScope = true;
  12120. }
  12121. }
  12122. else // Autocomplete case
  12123. {
  12124. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12125. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12126. // resolve pass, NOT the autocomplete expression
  12127. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12128. {
  12129. if (tempTypeDef->mFullName == typeDef->mFullName)
  12130. {
  12131. for (auto fieldDef : tempTypeDef->mFields)
  12132. {
  12133. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12134. {
  12135. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12136. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12137. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12138. if ((wantType != NULL) &&
  12139. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12140. wantType = NULL;
  12141. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12142. }
  12143. }
  12144. }
  12145. }
  12146. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12147. for (auto fieldDef : typeDef->mFields)
  12148. {
  12149. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12150. {
  12151. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12152. if (fieldDef->mInitializer != NULL)
  12153. MarkFieldInitialized(fieldInst);
  12154. }
  12155. }
  12156. }
  12157. }
  12158. // Call base ctor (if applicable)
  12159. BfTypeInstance* targetType = NULL;
  12160. BfAstNode* targetRefNode = NULL;
  12161. if (ctorDeclaration != NULL)
  12162. targetRefNode = ctorDeclaration->mInitializer;
  12163. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12164. targetRefNode = invocationExpr->mTarget;
  12165. if (baseCtorNode != NULL)
  12166. {
  12167. UpdateSrcPos(baseCtorNode);
  12168. }
  12169. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12170. {
  12171. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12172. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12173. }
  12174. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12175. {
  12176. auto baseType = mCurTypeInstance->mBaseType;
  12177. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12178. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12179. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12180. {
  12181. // Try to find a ctor without any params first
  12182. bool foundBaseCtor = false;
  12183. bool hadCtorWithAllDefaults = false;
  12184. for (int pass = 0; pass < 2; pass++)
  12185. {
  12186. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12187. {
  12188. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12189. // Allow calling of the default base ctor if it is implicitly defined
  12190. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12191. allowPriv = true;
  12192. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12193. {
  12194. if (checkMethodDef->mParams.size() == 0)
  12195. {
  12196. foundBaseCtor = true;
  12197. if (HasCompiledOutput())
  12198. {
  12199. SizedArray<BfIRValue, 1> args;
  12200. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12201. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12202. {
  12203. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12204. args.push_back(basePtr);
  12205. }
  12206. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12207. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12208. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12209. if (callingConv != BfIRCallingConv_CDecl)
  12210. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12211. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12212. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12213. break;
  12214. }
  12215. }
  12216. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12217. hadCtorWithAllDefaults = true;
  12218. }
  12219. }
  12220. if (foundBaseCtor)
  12221. break;
  12222. }
  12223. if (!foundBaseCtor)
  12224. {
  12225. targetType = mCurTypeInstance->mBaseType;
  12226. if (ctorDeclaration != NULL)
  12227. targetRefNode = ctorDeclaration->mThisToken;
  12228. else if (typeDef->mTypeDeclaration != NULL)
  12229. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12230. }
  12231. }
  12232. }
  12233. if (methodDef->mHasAppend)
  12234. {
  12235. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12236. }
  12237. if (targetType != NULL)
  12238. {
  12239. auto autoComplete = mCompiler->GetAutoComplete();
  12240. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12241. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12242. {
  12243. auto invocationExpr = ctorDeclaration->mInitializer;
  12244. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12245. }
  12246. BfType* targetThisType = targetType;
  12247. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12248. BfExprEvaluator exprEvaluator(this);
  12249. BfResolvedArgs argValues;
  12250. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12251. {
  12252. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12253. if (gDebugStuff)
  12254. {
  12255. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12256. }
  12257. }
  12258. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12259. BfTypedValue appendIdxVal;
  12260. if (methodDef->mHasAppend)
  12261. {
  12262. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12263. BF_ASSERT(localVar->mName == "appendIdx");
  12264. auto intRefType = CreateRefType(localVar->mResolvedType);
  12265. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12266. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12267. }
  12268. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12269. if (autoComplete != NULL)
  12270. {
  12271. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12272. {
  12273. if (autoComplete->mMethodMatchInfo != NULL)
  12274. autoComplete->mIsCapturingMethodMatchInfo = true;
  12275. else
  12276. autoComplete->mIsCapturingMethodMatchInfo = false;
  12277. }
  12278. else
  12279. autoComplete->mIsCapturingMethodMatchInfo = false;
  12280. }
  12281. }
  12282. }
  12283. void BfModule::EmitEnumToStringBody()
  12284. {
  12285. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12286. auto strVal = CreateAlloca(stringType);
  12287. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12288. BfExprEvaluator exprEvaluator(this);
  12289. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12290. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12291. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12292. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12293. BfType* discriminatorType = NULL;
  12294. BfTypedValue rawPayload;
  12295. BfIRValue enumVal;
  12296. if (mCurTypeInstance->IsPayloadEnum())
  12297. {
  12298. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12299. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12300. enumTypedValue = LoadValue(enumTypedValue);
  12301. enumVal = enumTypedValue.mValue;
  12302. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12303. }
  12304. else
  12305. enumVal = mBfIRBuilder->GetArgument(0);
  12306. Array<BfType*> paramTypes;
  12307. paramTypes.Add(stringType);
  12308. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12309. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12310. HashSet<int64> handledCases;
  12311. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12312. {
  12313. if (fieldInstance.mIsEnumPayloadCase)
  12314. {
  12315. int tagId = -fieldInstance.mDataIdx - 1;
  12316. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12317. mBfIRBuilder->AddBlock(caseBlock);
  12318. mBfIRBuilder->SetInsertPoint(caseBlock);
  12319. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12320. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12321. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12322. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12323. auto stringDestVal = LoadValue(stringDestAddr);
  12324. SizedArray<BfIRValue, 2> args;
  12325. args.Add(stringDestVal.mValue);
  12326. args.Add(caseStr);
  12327. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12328. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12329. BF_ASSERT(payloadType->IsTuple());
  12330. if (payloadType->mFieldInstances.size() != 0)
  12331. {
  12332. auto payload = rawPayload;
  12333. if (payload.mType != payloadType)
  12334. {
  12335. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12336. }
  12337. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12338. SizedArray<BfIRValue, 2> irArgs;
  12339. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12340. stringDestVal = LoadValue(stringDestAddr);
  12341. irArgs.Add(stringDestVal.mValue);
  12342. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12343. }
  12344. mBfIRBuilder->CreateBr(endBlock);
  12345. continue;
  12346. }
  12347. if (fieldInstance.mConstIdx == -1)
  12348. continue;
  12349. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12350. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12351. {
  12352. // Duplicate
  12353. continue;
  12354. }
  12355. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12356. mBfIRBuilder->AddBlock(caseBlock);
  12357. mBfIRBuilder->SetInsertPoint(caseBlock);
  12358. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12359. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12360. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12361. mBfIRBuilder->CreateStore(caseStr, strVal);
  12362. mBfIRBuilder->CreateBr(appendBlock);
  12363. }
  12364. mBfIRBuilder->AddBlock(appendBlock);
  12365. mBfIRBuilder->SetInsertPoint(appendBlock);
  12366. SizedArray<BfIRValue, 2> args;
  12367. auto stringDestVal = LoadValue(stringDestAddr);
  12368. args.Add(stringDestVal.mValue);
  12369. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12370. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12371. mBfIRBuilder->CreateBr(endBlock);
  12372. mBfIRBuilder->AddBlock(noMatchBlock);
  12373. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12374. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12375. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12376. args.clear();
  12377. args.Add(int64Val);
  12378. stringDestVal = LoadValue(stringDestAddr);
  12379. args.Add(stringDestVal.mValue);
  12380. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12381. mBfIRBuilder->CreateBr(endBlock);
  12382. mBfIRBuilder->AddBlock(endBlock);
  12383. mBfIRBuilder->SetInsertPoint(endBlock);
  12384. }
  12385. void BfModule::EmitTupleToStringBody()
  12386. {
  12387. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12388. BfExprEvaluator exprEvaluator(this);
  12389. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12390. Array<BfType*> paramTypes;
  12391. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12392. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12393. paramTypes.Clear();
  12394. paramTypes.Add(stringType);
  12395. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12396. auto _AppendChar = [&](char c)
  12397. {
  12398. SizedArray<BfIRValue, 2> args;
  12399. auto stringDestVal = LoadValue(stringDestRef);
  12400. args.Add(stringDestVal.mValue);
  12401. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12402. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12403. };
  12404. int fieldIdx = 0;
  12405. auto thisValue = GetThis();
  12406. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12407. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12408. BfIRValue commaStr;
  12409. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12410. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12411. _AppendChar('(');
  12412. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12413. {
  12414. if (fieldInstance.mDataIdx == -1)
  12415. continue;
  12416. if (fieldIdx > 0)
  12417. {
  12418. if (!commaStr)
  12419. commaStr = GetStringObjectValue(", ");
  12420. SizedArray<BfIRValue, 2> args;
  12421. auto stringDestVal = LoadValue(stringDestRef);
  12422. args.Add(stringDestVal.mValue);
  12423. args.Add(commaStr);
  12424. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12425. }
  12426. fieldIdx++;
  12427. if (fieldInstance.mResolvedType->IsValuelessType())
  12428. continue;
  12429. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12430. if (fieldValue.mType->IsPrimitiveType())
  12431. {
  12432. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12433. }
  12434. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12435. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12436. {
  12437. BfExprEvaluator exprEvaluator(this);
  12438. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12439. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12440. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12441. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12442. methodMatcher.TryDevirtualizeCall(fieldValue);
  12443. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12444. BfResolvedArg resolvedArg;
  12445. auto stringDestVal = LoadValue(stringDestRef);
  12446. resolvedArg.mTypedValue = stringDestVal;
  12447. resolvedArg.mResolvedType = stringDestVal.mType;
  12448. resolvedArgs.Add(resolvedArg);
  12449. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12450. continue;
  12451. }
  12452. if (fieldValue.mType->IsObjectOrInterface())
  12453. {
  12454. BF_ASSERT(!fieldValue.IsAddr());
  12455. SizedArray<BfIRValue, 2> args;
  12456. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12457. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12458. stringDestVal = LoadValue(stringDestVal);
  12459. args.Add(stringDestVal.mValue);
  12460. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12461. continue;
  12462. }
  12463. BfExprEvaluator exprEvaluator(this);
  12464. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12465. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12466. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12467. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12468. methodMatcher.TryDevirtualizeCall(fieldValue);
  12469. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12470. {
  12471. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12472. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12473. // Just append the type name
  12474. String typeName = TypeToString(fieldInstance.mResolvedType);
  12475. auto strVal = GetStringObjectValue(typeName);
  12476. SizedArray<BfIRValue, 2> args;
  12477. auto stringDestVal = LoadValue(stringDestRef);
  12478. args.Add(stringDestVal.mValue);
  12479. args.Add(strVal);
  12480. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12481. continue;
  12482. }
  12483. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12484. BfResolvedArg resolvedArg;
  12485. auto stringDestVal = LoadValue(stringDestRef);
  12486. resolvedArg.mTypedValue = stringDestVal;
  12487. resolvedArg.mResolvedType = stringDestVal.mType;
  12488. resolvedArgs.Add(resolvedArg);
  12489. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12490. }
  12491. _AppendChar(')');
  12492. }
  12493. void BfModule::EmitIteratorBlock(bool& skipBody)
  12494. {
  12495. auto methodInstance = mCurMethodInstance;
  12496. auto methodDef = methodInstance->mMethodDef;
  12497. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12498. auto typeDef = mCurTypeInstance->mTypeDef;
  12499. BfType* innerRetType = NULL;
  12500. BfTypeInstance* usingInterface = NULL;
  12501. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12502. if (retTypeInst != NULL)
  12503. {
  12504. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12505. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12506. {
  12507. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12508. }
  12509. }
  12510. if (innerRetType == NULL)
  12511. {
  12512. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12513. return;
  12514. }
  12515. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12516. if (blockBody == NULL)
  12517. return;
  12518. }
  12519. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12520. {
  12521. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12522. if (fieldTypeInst == NULL)
  12523. return;
  12524. if (!markVal.mType->IsComposite())
  12525. markVal = LoadValue(markVal);
  12526. BfExprEvaluator exprEvaluator(this);
  12527. PopulateType(markVal.mType, BfPopulateType_Data);
  12528. if (markVal.mType->IsObjectOrInterface())
  12529. {
  12530. BfIRValue val = markVal.mValue;
  12531. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12532. SizedArray<BfIRValue, 1> args;
  12533. args.push_back(val);
  12534. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12535. }
  12536. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12537. {
  12538. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12539. if (markMemberMethodInstance)
  12540. {
  12541. SizedArray<BfIRValue, 1> args;
  12542. //(1, markVal.mValue);
  12543. //exprEvaluator.PushArg(markVal, args);
  12544. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12545. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12546. }
  12547. }
  12548. }
  12549. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12550. {
  12551. Array<BfMethodInstance*> methodInstances;
  12552. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12553. {
  12554. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12555. auto chainedMethodInst = methodInstGroup.mDefault;
  12556. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12557. {
  12558. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12559. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12560. {
  12561. methodInstances.push_back(chainedMethodInst);
  12562. }
  12563. }
  12564. }
  12565. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12566. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12567. {
  12568. bool isBetter;
  12569. bool isWorse;
  12570. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12571. if (isBetter == isWorse)
  12572. {
  12573. return false;
  12574. }
  12575. return isWorse;
  12576. });
  12577. if (reverse)
  12578. std::reverse(methodInstances.begin(), methodInstances.end());
  12579. for (auto chainedMethodInst : methodInstances)
  12580. {
  12581. auto declModule = this;
  12582. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12583. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12584. BfExprEvaluator exprEvaluator(this);
  12585. SizedArray<BfIRValue, 1> args;
  12586. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12587. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12588. }
  12589. }
  12590. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12591. {
  12592. BF_ASSERT(mCurMethodInstance->mIsReified);
  12593. if (mCurTypeInstance->mHotTypeData == NULL)
  12594. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12595. auto hotMethod = mCurMethodInstance->mHotMethod;
  12596. for (auto depData : hotMethod->mReferences)
  12597. {
  12598. // Only virtual decls are allowed to already be there
  12599. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12600. }
  12601. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12602. int prevSize = (int)hotMethod->mReferences.size();
  12603. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12604. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12605. refCount++;
  12606. hotMethod->mReferences.Reserve(refCount);
  12607. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12608. {
  12609. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12610. hotThis->mRefCount++;
  12611. hotMethod->mReferences.Insert(0, hotThis);
  12612. prevSize++;
  12613. }
  12614. for (auto val : builder->mAllocatedData)
  12615. {
  12616. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12617. hotMethod->mReferences.Add(hotAllocation);
  12618. }
  12619. for (auto val : builder->mUsedData)
  12620. hotMethod->mReferences.Add(val);
  12621. for (auto val : builder->mCalledMethods)
  12622. hotMethod->mReferences.Add(val);
  12623. for (auto val : builder->mDevirtualizedCalledMethods)
  12624. {
  12625. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12626. hotMethod->mReferences.Add(devirtualizedMethod);
  12627. }
  12628. for (auto val : builder->mFunctionPtrs)
  12629. {
  12630. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12631. hotMethod->mReferences.Add(funcRef);
  12632. }
  12633. for (auto val : builder->mInnerMethods)
  12634. {
  12635. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12636. hotMethod->mReferences.Add(innerMethod);
  12637. }
  12638. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12639. {
  12640. auto depData = hotMethod->mReferences[refIdx];
  12641. BF_ASSERT(depData != NULL);
  12642. depData->mRefCount++;
  12643. }
  12644. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12645. }
  12646. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12647. {
  12648. auto methodDef = methodInstance->mMethodDef;
  12649. auto methodDeclaration = methodDef->mMethodDeclaration;
  12650. bool isThisStruct = false;
  12651. if (thisType != NULL)
  12652. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12653. int argIdx = 0;
  12654. if (methodInstance->HasStructRet())
  12655. argIdx++;
  12656. if (!methodDef->mIsStatic)
  12657. {
  12658. BfLocalVariable* paramVar = new BfLocalVariable();
  12659. paramVar->mResolvedType = thisType;
  12660. paramVar->mName = "this";
  12661. if (!thisType->IsValuelessType())
  12662. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12663. else
  12664. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12665. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12666. {
  12667. if (thisType->IsSplattable())
  12668. paramVar->mIsSplat = true;
  12669. else
  12670. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12671. }
  12672. auto thisTypeInst = thisType->ToTypeInstance();
  12673. paramVar->mIsStruct = isThisStruct;
  12674. paramVar->mAddr = BfIRValue();
  12675. paramVar->mIsThis = true;
  12676. paramVar->mParamIdx = -1;
  12677. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12678. {
  12679. paramVar->mIsAssigned = false;
  12680. }
  12681. else
  12682. {
  12683. paramVar->mIsAssigned = true;
  12684. }
  12685. paramVar->mReadFromId = -1;
  12686. paramVar->Init();
  12687. if (methodDeclaration == NULL)
  12688. UseDefaultSrcPos();
  12689. AddLocalVariableDef(paramVar);
  12690. if (!thisType->IsValuelessType())
  12691. {
  12692. if (wantsDIData)
  12693. {
  12694. BfType* thisPtrType = thisType;
  12695. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12696. if (!thisType->IsValueType())
  12697. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12698. diParams->push_back(diType);
  12699. }
  12700. if (paramVar->mIsSplat)
  12701. {
  12702. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12703. }
  12704. else
  12705. {
  12706. argIdx++;
  12707. }
  12708. }
  12709. }
  12710. bool hadParams = false;
  12711. bool hasDefault = false;
  12712. int compositeVariableIdx = -1;
  12713. int paramIdx = 0;
  12714. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12715. {
  12716. // We already issues a type error for this param if we had one in declaration processing
  12717. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12718. BfLocalVariable* paramVar = new BfLocalVariable();
  12719. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12720. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12721. if (unresolvedType == NULL)
  12722. {
  12723. AssertErrorState();
  12724. unresolvedType = mContext->mBfObjectType;
  12725. paramVar->mParamFailed = true;
  12726. }
  12727. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12728. prevIgnoreErrors.Restore();
  12729. PopulateType(resolvedType, BfPopulateType_Declaration);
  12730. paramVar->mResolvedType = resolvedType;
  12731. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12732. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12733. if (!isParamSkipped)
  12734. {
  12735. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12736. if (resolvedType->IsMethodRef())
  12737. {
  12738. paramVar->mIsSplat = true;
  12739. }
  12740. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12741. {
  12742. int splatCount = resolvedType->GetSplatCount();
  12743. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12744. paramVar->mIsSplat = true;
  12745. }
  12746. }
  12747. else
  12748. {
  12749. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12750. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12751. }
  12752. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12753. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12754. paramVar->mParamIdx = paramIdx;
  12755. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12756. paramVar->mReadFromId = 0;
  12757. if (resolvedType->IsRef())
  12758. {
  12759. auto refType = (BfRefType*)resolvedType;
  12760. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12761. }
  12762. else
  12763. {
  12764. paramVar->mIsAssigned = true;
  12765. if (methodDef->mMethodType != BfMethodType_Mixin)
  12766. paramVar->mIsReadOnly = true;
  12767. }
  12768. if (paramVar->mResolvedType->IsGenericParam())
  12769. {
  12770. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12771. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12772. {
  12773. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12774. paramVar->mResolvedType = typedVal.mType;
  12775. paramVar->mConstValue = typedVal.mValue;
  12776. }
  12777. }
  12778. if (paramVar->mResolvedType->IsConstExprValue())
  12779. {
  12780. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12781. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12782. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12783. BF_ASSERT(unspecParamType->IsGenericParam());
  12784. if (unspecParamType->IsGenericParam())
  12785. {
  12786. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12787. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12788. {
  12789. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12790. if (genericParamInst->mTypeConstraint != NULL)
  12791. {
  12792. BfExprEvaluator exprEvaluator(this);
  12793. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12794. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12795. auto checkType = genericParamInst->mTypeConstraint;
  12796. if (checkType->IsTypedPrimitive())
  12797. checkType = checkType->GetUnderlyingType();
  12798. if (exprEvaluator.mResult.mType == checkType)
  12799. {
  12800. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12801. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12802. BF_ASSERT(paramVar->mConstValue.IsConst());
  12803. }
  12804. else
  12805. {
  12806. AssertErrorState();
  12807. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12808. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12809. }
  12810. }
  12811. }
  12812. }
  12813. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12814. if (paramVar->mResolvedType->IsConstExprValue())
  12815. {
  12816. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12817. //AssertErrorState();
  12818. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12819. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12820. }
  12821. }
  12822. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12823. {
  12824. if (compositeVariableIdx == -1)
  12825. {
  12826. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12827. BfLocalVariable* localVar = new BfLocalVariable();
  12828. auto paramInst = &methodInstance->mParams[paramIdx];
  12829. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12830. localVar->mName = paramDef->mName;
  12831. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12832. localVar->mCompositeCount = 0;
  12833. DoAddLocalVariable(localVar);
  12834. }
  12835. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12836. }
  12837. CheckVariableDef(paramVar);
  12838. paramVar->Init();
  12839. AddLocalVariableDef(paramVar);
  12840. if (!isParamSkipped)
  12841. {
  12842. if (wantsDIData)
  12843. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12844. if (paramVar->mIsSplat)
  12845. {
  12846. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12847. }
  12848. else
  12849. {
  12850. argIdx++;
  12851. }
  12852. }
  12853. }
  12854. // Try to find an ending delegate params composite
  12855. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12856. {
  12857. auto paramDef = methodDef->mParams.back();
  12858. if (paramDef->mParamKind == BfParamKind_Params)
  12859. {
  12860. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12861. if (paramsType == NULL)
  12862. {
  12863. AssertErrorState();
  12864. }
  12865. else if (paramsType->IsGenericParam())
  12866. {
  12867. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12868. if (genericParamInstance->mTypeConstraint != NULL)
  12869. {
  12870. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12871. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12872. ((typeInstConstraint != NULL) &&
  12873. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12874. {
  12875. BfLocalVariable* localVar = new BfLocalVariable();
  12876. localVar->mName = paramDef->mName;
  12877. localVar->mResolvedType = paramsType;
  12878. localVar->mCompositeCount = 0;
  12879. DoAddLocalVariable(localVar);
  12880. }
  12881. }
  12882. }
  12883. else if (paramsType->IsDelegate())
  12884. {
  12885. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12886. if (invokeMethodInstance != NULL)
  12887. {
  12888. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12889. // and wasn't cleared by the preceding loop
  12890. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12891. BfLocalVariable* localVar = new BfLocalVariable();
  12892. localVar->mName = paramDef->mName;
  12893. localVar->mResolvedType = paramsType;
  12894. localVar->mCompositeCount = 0;
  12895. DoAddLocalVariable(localVar);
  12896. }
  12897. }
  12898. }
  12899. }
  12900. }
  12901. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12902. {
  12903. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12904. // return;
  12905. auto _ClearState = [&]()
  12906. {
  12907. mCurMethodState->mLocalMethods.Clear();
  12908. for (auto& local : mCurMethodState->mLocals)
  12909. delete local;
  12910. mCurMethodState->mLocals.Clear();
  12911. mCurMethodState->mLocalVarSet.Clear();
  12912. };
  12913. // 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
  12914. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12915. // however (compiler bug), so this is the safest way
  12916. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12917. {
  12918. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12919. {
  12920. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12921. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12922. if (!mHadBuildError)
  12923. {
  12924. // Process as a closure - that allows us to look back and see the const locals and stuff
  12925. BfClosureState closureState;
  12926. mCurMethodState->mClosureState = &closureState;
  12927. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12928. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12929. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12930. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12931. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12932. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12933. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12934. _ClearState();
  12935. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12936. {
  12937. auto localVar = new BfLocalVariable();
  12938. *localVar = constLocal;
  12939. DoAddLocalVariable(localVar);
  12940. }
  12941. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12942. bool doProcess = !mCompiler->mCanceling;
  12943. if (doProcess)
  12944. {
  12945. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12946. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12947. }
  12948. }
  12949. delete deferredLocalMethod;
  12950. mSystem->CheckLockYield();
  12951. }
  12952. }
  12953. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12954. {
  12955. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12956. }
  12957. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12958. {
  12959. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12960. {
  12961. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12962. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12963. BfClosureState closureState;
  12964. mCurMethodState->mClosureState = &closureState;
  12965. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12966. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12967. if (lambdaInstance->mClosureTypeInstance != NULL)
  12968. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  12969. else
  12970. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  12971. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12972. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  12973. _ClearState();
  12974. for (auto& constLocal : lambdaInstance->mConstLocals)
  12975. {
  12976. //if (constLocal.mIsThis)
  12977. {
  12978. // Valueless 'this'
  12979. closureState.mConstLocals.Add(constLocal);
  12980. }
  12981. /*else
  12982. {
  12983. auto localVar = new BfLocalVariable();
  12984. *localVar = constLocal;
  12985. DoAddLocalVariable(localVar);
  12986. }*/
  12987. }
  12988. BfMethodInstanceGroup methodInstanceGroup;
  12989. methodInstanceGroup.mOwner = mCurTypeInstance;
  12990. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12991. bool doProcess = !mCompiler->mCanceling;
  12992. if (doProcess)
  12993. {
  12994. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  12995. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  12996. ProcessMethod(lambdaInstance->mMethodInstance);
  12997. if (lambdaInstance->mDtorMethodInstance != NULL)
  12998. {
  12999. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13000. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13001. }
  13002. }
  13003. }
  13004. mSystem->CheckLockYield();
  13005. }
  13006. }
  13007. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13008. {
  13009. if (checkType->IsComposite())
  13010. PopulateType(checkType, BfPopulateType_Data);
  13011. if (!checkType->WantsGCMarking())
  13012. return;
  13013. auto typeInstance = checkType->ToTypeInstance();
  13014. bool callMarkMethod = false;
  13015. // Call the actual marking method
  13016. if (memberDepth == 0)
  13017. {
  13018. // Don't call marking method on self
  13019. }
  13020. else if (checkType->IsObjectOrInterface())
  13021. {
  13022. if (!objectOffsets.Add(curOffset))
  13023. {
  13024. return;
  13025. }
  13026. callMarkMethod = true;
  13027. }
  13028. else if (checkType->IsSizedArray())
  13029. {
  13030. callMarkMethod = true;
  13031. }
  13032. else if (typeInstance != NULL)
  13033. {
  13034. typeInstance->mTypeDef->PopulateMemberSets();
  13035. BfMemberSetEntry* entry = NULL;
  13036. BfMethodDef* methodDef = NULL;
  13037. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13038. {
  13039. methodDef = (BfMethodDef*)entry->mMemberDef;
  13040. if (methodDef->HasBody())
  13041. {
  13042. callMarkMethod = true;
  13043. }
  13044. }
  13045. }
  13046. if (callMarkMethod)
  13047. {
  13048. BfTypedValue markValue;
  13049. auto memberType = checkType;
  13050. if (memberType->IsObjectOrInterface())
  13051. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13052. auto memberPtrType = CreatePointerType(memberType);
  13053. if (curOffset == 0)
  13054. {
  13055. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13056. }
  13057. else
  13058. {
  13059. if (!thisValue.mType->IsPointer())
  13060. {
  13061. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13062. auto int8PtrType = CreatePointerType(int8Type);
  13063. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13064. }
  13065. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13066. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13067. }
  13068. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13069. return;
  13070. }
  13071. auto methodDef = mCurMethodInstance->mMethodDef;
  13072. if (checkType->IsPayloadEnum())
  13073. {
  13074. for (auto& fieldInst : typeInstance->mFieldInstances)
  13075. {
  13076. if (!fieldInst.mIsEnumPayloadCase)
  13077. continue;
  13078. auto fieldDef = fieldInst.GetFieldDef();
  13079. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13080. }
  13081. return;
  13082. }
  13083. if (typeInstance == NULL)
  13084. return;
  13085. for (auto& fieldInst : typeInstance->mFieldInstances)
  13086. {
  13087. auto fieldDef = fieldInst.GetFieldDef();
  13088. if (fieldDef == NULL)
  13089. continue;
  13090. if (fieldDef->mIsStatic)
  13091. continue;
  13092. if (typeInstance == mCurTypeInstance)
  13093. {
  13094. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13095. // we may be marking member values that can never contain a value anyway, but this is benign
  13096. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13097. continue;
  13098. }
  13099. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13100. }
  13101. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13102. {
  13103. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13104. }
  13105. }
  13106. void BfModule::EmitGCMarkMembers()
  13107. {
  13108. auto methodDef = mCurMethodInstance->mMethodDef;
  13109. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13110. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13111. if (gcType != NULL)
  13112. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13113. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13114. {
  13115. if (mCurTypeInstance->IsBoxed())
  13116. {
  13117. // This already gets filled in by the normal boxed forwarding
  13118. }
  13119. else
  13120. {
  13121. auto thisValue = GetThis();
  13122. if (thisValue.IsSplat())
  13123. {
  13124. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13125. int argIdx = 0;
  13126. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13127. {
  13128. if (checkType->IsStruct())
  13129. {
  13130. auto checkTypeInstance = checkType->ToTypeInstance();
  13131. if (checkTypeInstance->mBaseType != NULL)
  13132. checkTypeLambda(checkTypeInstance->mBaseType);
  13133. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13134. {
  13135. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13136. if (fieldInstance->mDataIdx >= 0)
  13137. checkTypeLambda(fieldInstance->GetResolvedType());
  13138. }
  13139. }
  13140. else if (checkType->IsMethodRef())
  13141. {
  13142. BF_FATAL("Not handled");
  13143. }
  13144. else if (checkType->WantsGCMarking())
  13145. {
  13146. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13147. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13148. argIdx++;
  13149. }
  13150. };
  13151. checkTypeLambda(thisValue.mType);
  13152. }
  13153. else if (!methodDef->mIsStatic)
  13154. {
  13155. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13156. {
  13157. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13158. if (moduleMethodInst)
  13159. {
  13160. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13161. if (methodBaseType != mContext->mBfObjectType)
  13162. {
  13163. auto thisValue = GetThis();
  13164. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13165. SizedArray<BfIRValue, 1> args;
  13166. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13167. {
  13168. BfExprEvaluator exprEvaluator(this);
  13169. exprEvaluator.SplatArgs(baseValue, args);
  13170. }
  13171. else
  13172. {
  13173. args.push_back(baseValue.mValue);
  13174. }
  13175. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13176. }
  13177. }
  13178. }
  13179. }
  13180. if (!methodDef->mIsStatic)
  13181. {
  13182. HashSet<int> objectOffsets;
  13183. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13184. }
  13185. else
  13186. {
  13187. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13188. {
  13189. if (thisValue.IsSplat())
  13190. break;
  13191. auto fieldDef = fieldInst.GetFieldDef();
  13192. if (fieldDef == NULL)
  13193. continue;
  13194. if (fieldInst.mIsThreadLocal)
  13195. continue;
  13196. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13197. {
  13198. // For extensions, only handle these fields in the appropriate extension
  13199. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13200. continue;
  13201. if (!fieldInst.mFieldIncluded)
  13202. continue;
  13203. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13204. if (fieldTypeInst != NULL)
  13205. {
  13206. auto fieldDef = fieldInst.GetFieldDef();
  13207. BfTypedValue markVal;
  13208. if (fieldDef->mIsConst)
  13209. continue;
  13210. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13211. continue;
  13212. mBfIRBuilder->PopulateType(fieldTypeInst);
  13213. if (fieldTypeInst->IsValuelessType())
  13214. continue;
  13215. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13216. {
  13217. markVal = ReferenceStaticField(&fieldInst);
  13218. }
  13219. else if (!fieldDef->mIsStatic)
  13220. {
  13221. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13222. }
  13223. if (markVal)
  13224. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13225. }
  13226. }
  13227. }
  13228. }
  13229. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13230. CallChainedMethods(mCurMethodInstance, false);
  13231. }
  13232. }
  13233. }
  13234. void BfModule::EmitGCFindTLSMembers()
  13235. {
  13236. auto methodDef = mCurMethodInstance->mMethodDef;
  13237. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13238. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13239. BF_ASSERT(reportTLSMark);
  13240. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13241. {
  13242. auto fieldDef = fieldInst.GetFieldDef();
  13243. if (fieldDef == NULL)
  13244. continue;
  13245. if (!fieldInst.mIsThreadLocal)
  13246. continue;
  13247. // For extensions, only handle these fields in the appropriate extension
  13248. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13249. continue;
  13250. if (!fieldInst.mFieldIncluded)
  13251. continue;
  13252. if (fieldDef->mIsConst)
  13253. continue;
  13254. auto fieldType = fieldInst.mResolvedType;
  13255. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13256. continue;
  13257. if (fieldType->IsValuelessType())
  13258. continue;
  13259. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13260. if (markVal)
  13261. {
  13262. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13263. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13264. SizedArray<BfIRValue, 2> llvmArgs;
  13265. llvmArgs.push_back(fieldRefPtr);
  13266. llvmArgs.push_back(markFuncPtr);
  13267. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13268. }
  13269. }
  13270. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13271. CallChainedMethods(mCurMethodInstance, false);
  13272. }
  13273. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13274. {
  13275. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13276. if (mAwaitingInitFinish)
  13277. FinishInit();
  13278. if (!methodInstance->mIsReified)
  13279. BF_ASSERT(!mIsReified);
  13280. if (methodInstance->mMethodInfoEx != NULL)
  13281. {
  13282. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13283. {
  13284. if (methodGenericArg->IsMethodRef())
  13285. {
  13286. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13287. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13288. }
  13289. }
  13290. }
  13291. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13292. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13293. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13294. {
  13295. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13296. }
  13297. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13298. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13299. (mCompiler->mResolvePassData != NULL))
  13300. {
  13301. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13302. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13303. }
  13304. if (methodInstance->mHasBeenProcessed)
  13305. {
  13306. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13307. return;
  13308. }
  13309. if (methodInstance->mFailedConstraints)
  13310. {
  13311. // The only way this should be able to happen is if we fail our generic param check
  13312. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13313. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13314. methodInstance->mHasBeenProcessed = true;
  13315. return;
  13316. }
  13317. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13318. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13319. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13320. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13321. {
  13322. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13323. auto owningModule = methodInstance->GetOwner()->mModule;
  13324. if (owningModule->mIsScratchModule)
  13325. {
  13326. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13327. }
  13328. else
  13329. {
  13330. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13331. if (owningModule->mOnDemandMethodCount > 0)
  13332. owningModule->mOnDemandMethodCount--;
  13333. }
  13334. }
  13335. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13336. // self-referencing append allocations in ctor@calcAppend
  13337. methodInstance->mHasBeenProcessed = true;
  13338. mIncompleteMethodCount--;
  13339. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13340. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13341. auto methodDef = methodInstance->mMethodDef;
  13342. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13343. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13344. {
  13345. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13346. // so we get the new vdata for it
  13347. methodInstance->GetOwner()->mDirty = true;
  13348. }
  13349. int dependentGenericStartIdx = 0;
  13350. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13351. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13352. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13353. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13354. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13355. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13356. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13357. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13358. if ((methodInstance->mIsReified) &&
  13359. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13360. {
  13361. mCurTypeInstance->mHasBeenInstantiated = true;
  13362. }
  13363. // Warnings are shown in the capture phase
  13364. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13365. mIgnoreWarnings = true;
  13366. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13367. UseDefaultSrcPos();
  13368. // We may not actually be populated in relatively rare autocompelte cases
  13369. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13370. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13371. BfAstNode* nameNode = NULL;
  13372. if (methodDeclaration != NULL)
  13373. {
  13374. nameNode = methodDeclaration->mNameNode;
  13375. if (nameNode == NULL)
  13376. {
  13377. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13378. nameNode = ctorDeclaration->mThisToken;
  13379. }
  13380. }
  13381. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13382. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13383. {
  13384. if (methodInstance->GetExplicitInterface() == NULL)
  13385. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13386. else
  13387. {
  13388. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13389. {
  13390. auto ifaceInst = ifaceEntry.mInterfaceType;
  13391. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13392. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13393. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13394. continue;
  13395. ifaceInst->mTypeDef->PopulateMemberSets();
  13396. BfMethodDef* nextMethod = NULL;
  13397. BfMemberSetEntry* entry = NULL;
  13398. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13399. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13400. while (nextMethod != NULL)
  13401. {
  13402. auto checkMethod = nextMethod;
  13403. nextMethod = nextMethod->mNextWithSameName;
  13404. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13405. if (implMethodInst == methodInstance)
  13406. {
  13407. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13408. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13409. }
  13410. }
  13411. }
  13412. }
  13413. if (methodDef->mIsOverride)
  13414. {
  13415. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13416. {
  13417. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13418. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13419. continue;
  13420. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13421. if (virtMethod != NULL)
  13422. {
  13423. if (virtMethod == methodInstance)
  13424. {
  13425. // Is matching method
  13426. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13427. {
  13428. auto baseType = mCurTypeInstance->mBaseType;
  13429. if (baseType != NULL)
  13430. {
  13431. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13432. baseType = baseType->mBaseType;
  13433. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13434. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13435. }
  13436. }
  13437. break;
  13438. }
  13439. }
  13440. }
  13441. }
  13442. }
  13443. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13444. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13445. {
  13446. if (mBfIRBuilder->mIgnoreWrites)
  13447. return;
  13448. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13449. if (!methodInstance->mIRFunction)
  13450. {
  13451. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13452. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13453. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13454. }
  13455. if (HasCompiledOutput())
  13456. {
  13457. BfDllImportEntry dllImportEntry;
  13458. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13459. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13460. mDllImportEntries.push_back(dllImportEntry);
  13461. }
  13462. return;
  13463. }
  13464. StringT<128> mangledName;
  13465. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13466. if (!methodInstance->mIRFunction)
  13467. {
  13468. bool isIntrinsic = false;
  13469. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13470. }
  13471. if (methodInstance->mIsIntrinsic)
  13472. return;
  13473. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13474. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13475. if (methodDef->mBody != NULL)
  13476. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13477. else if (methodDeclaration != NULL)
  13478. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13479. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13480. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13481. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13482. {
  13483. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13484. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13485. {
  13486. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13487. }
  13488. }
  13489. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13490. BfMethodState methodState;
  13491. if (mCurMethodState != NULL)
  13492. methodState.mClosureState = mCurMethodState->mClosureState;
  13493. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13494. {
  13495. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13496. if (methodInstance->mHotMethod == NULL)
  13497. CheckHotMethod(methodInstance, mangledName);
  13498. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13499. }
  13500. methodState.mPrevMethodState = mCurMethodState;
  13501. methodState.mMethodInstance = methodInstance;
  13502. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13503. if (methodInstance->GetCustomAttributes() != NULL)
  13504. {
  13505. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13506. if (typeOptionsIdx != -1)
  13507. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13508. }
  13509. BfTypeState typeState(mCurTypeInstance);
  13510. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13511. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13512. BfMethodInstance* unspecializedMethodInstance = NULL;
  13513. if ((prevMethodState.mPrevVal != NULL) &&
  13514. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13515. {
  13516. // This is 'inner' (probably a closure) - use binding from outer function
  13517. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13518. }
  13519. else if ((methodInstance->mIsUnspecialized) ||
  13520. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13521. {
  13522. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13523. }
  13524. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13525. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13526. {
  13527. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13528. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13529. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13530. {
  13531. // Make sure the unspecialized method is processed so we can take its bindings
  13532. // Clear mCurMethodState so we don't think we're in a local method
  13533. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13534. mContext->ProcessMethod(unspecializedMethodInstance);
  13535. }
  13536. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13537. }
  13538. if (methodDef->mMethodType == BfMethodType_Operator)
  13539. {
  13540. auto operatorDef = (BfOperatorDef*) methodDef;
  13541. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13542. auto paramErrorRefNode = refNode;
  13543. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13544. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13545. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13546. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13547. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13548. {
  13549. if (methodDef->mParams.size() != 2)
  13550. {
  13551. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13552. }
  13553. else
  13554. {
  13555. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13556. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13557. {
  13558. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13559. }
  13560. }
  13561. BfType* wantType = NULL;
  13562. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13563. {
  13564. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13565. }
  13566. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13567. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13568. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13569. }
  13570. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13571. {
  13572. if (methodDef->mParams.size() != 1)
  13573. {
  13574. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13575. }
  13576. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13577. {
  13578. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13579. }
  13580. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13581. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13582. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13583. {
  13584. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13585. }
  13586. }
  13587. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13588. {
  13589. if (methodDef->mParams.size() != 1)
  13590. {
  13591. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13592. }
  13593. if (mCurMethodInstance->mReturnType->IsVoid())
  13594. {
  13595. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13596. }
  13597. }
  13598. else // Conversion
  13599. {
  13600. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13601. {
  13602. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13603. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13604. }
  13605. if (methodDef->mParams.size() != 1)
  13606. {
  13607. auto refNode = paramErrorRefNode;
  13608. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13609. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13610. Fail("Conversion operators must declare one parameter", refNode);
  13611. }
  13612. else
  13613. {
  13614. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13615. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13616. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13617. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13618. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13619. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13620. // happened here
  13621. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13622. {
  13623. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13624. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13625. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13626. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13627. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13628. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13629. }
  13630. }
  13631. }
  13632. }
  13633. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13634. if (methodDef->mMethodType == BfMethodType_Mixin)
  13635. wantsDIData = false;
  13636. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13637. wantsDIData = false;
  13638. bool wantsDIVariables = wantsDIData;
  13639. if (methodDef->mIsExtern)
  13640. wantsDIVariables = false;
  13641. SizedArray<BfIRMDNode, 8> diParams;
  13642. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13643. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13644. BfType* thisType = NULL;
  13645. if (!methodDef->mIsStatic)
  13646. {
  13647. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13648. thisType = methodState.mClosureState->mClosureType;
  13649. else
  13650. thisType = mCurTypeInstance;
  13651. }
  13652. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13653. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13654. //////////////////////////////////////////////////////////////////////////
  13655. //
  13656. {
  13657. if (methodDeclaration != NULL)
  13658. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13659. else if (methodDef->mBody != NULL)
  13660. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13661. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13662. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13663. }
  13664. BfIRMDNode diFunction;
  13665. if (wantsDIData)
  13666. {
  13667. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13668. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13669. int defLine = mCurFilePosition.mCurLine;
  13670. if (mDICompileUnit)
  13671. {
  13672. int flags = 0;
  13673. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13674. if (methodDef->mProtection == BfProtection_Public)
  13675. flags = llvm::DINode::FlagPublic;
  13676. else if (methodDef->mProtection == BfProtection_Protected)
  13677. flags = llvm::DINode::FlagProtected;
  13678. else
  13679. flags = llvm::DINode::FlagPrivate;
  13680. if (methodDef->mIsOverride)
  13681. {
  13682. //flags |= llvm::DINode::FlagVirtual;
  13683. }
  13684. else if (methodDef->mIsVirtual)
  13685. flags |= llvm::DINode::FlagIntroducedVirtual;
  13686. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13687. flags |= llvm::DINode::FlagStaticMember;
  13688. else
  13689. {
  13690. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13691. flags |= llvm::DINode::FlagStaticMember;
  13692. }
  13693. flags |= llvm::DINode::FlagPrototyped;
  13694. if (methodDef->mMethodType == BfMethodType_Ctor)
  13695. {
  13696. flags |= llvm::DINode::FlagArtificial;
  13697. }
  13698. auto llvmFunction = methodInstance->mIRFunction;
  13699. SizedArray<BfIRMDNode, 1> genericArgs;
  13700. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13701. String methodName;
  13702. if (methodInstance->GetForeignType() != NULL)
  13703. {
  13704. methodName += TypeToString(methodInstance->GetForeignType());
  13705. methodName += ".";
  13706. }
  13707. if (methodInstance->GetExplicitInterface() != NULL)
  13708. {
  13709. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13710. methodName += ".";
  13711. }
  13712. methodName += methodDef->mName;
  13713. if (methodInstance->GetNumGenericArguments() != 0)
  13714. {
  13715. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13716. {
  13717. if (genericArg->IsConstExprValue())
  13718. {
  13719. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13720. while (genericConstValueArgs.size() < genericArgs.size())
  13721. genericConstValueArgs.push_back(BfIRValue());
  13722. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13723. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13724. }
  13725. else
  13726. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13727. }
  13728. methodName += "<";
  13729. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13730. {
  13731. if (i > 0)
  13732. methodName += ", ";
  13733. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13734. methodName += TypeToString(type);
  13735. }
  13736. methodName += ">";
  13737. }
  13738. if ((methodName.empty()) && (methodDeclaration != NULL))
  13739. {
  13740. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13741. {
  13742. methodName += "operator";
  13743. if (operatorDecl->mIsConvOperator)
  13744. {
  13745. methodName += " ";
  13746. methodName += TypeToString(methodInstance->mReturnType);
  13747. }
  13748. else if (operatorDecl->mOpTypeToken != NULL)
  13749. methodName += operatorDecl->mOpTypeToken->ToString();
  13750. }
  13751. }
  13752. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13753. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13754. // defLine + 1, diFuncType, false, true,
  13755. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13756. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13757. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13758. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13759. defLine + 1, diFuncType, false, true,
  13760. llvm::dwarf::DW_VIRTUALITY_none,
  13761. 0,
  13762. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13763. }
  13764. }
  13765. //////////////////////////////////////////////////////////////////////////
  13766. // Head and Init get rolled into Entry afterwards.
  13767. methodState.mIRFunction = methodInstance->mIRFunction;
  13768. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13769. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13770. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13771. methodState.mCurScope->mDIScope = diFunction;
  13772. auto llvmEntryBlock = methodState.mIREntryBlock;
  13773. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13774. if (methodDef->mBody != NULL)
  13775. {
  13776. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13777. }
  13778. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13779. {
  13780. // We want to be able to step into delegate invokes -- we actually step over them
  13781. if (methodDef->mName != "Invoke")
  13782. {
  13783. UpdateSrcPos(typeDef->mTypeDeclaration);
  13784. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13785. }
  13786. }
  13787. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13788. mBfIRBuilder->ClearDebugLocation();
  13789. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13790. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13791. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13792. {
  13793. int localIdx = 0;
  13794. int argIdx = 0;
  13795. if (methodInstance->HasStructRet())
  13796. argIdx++;
  13797. //
  13798. bool doDbgAgg = false;
  13799. Array<BfIRValue> splatAddrValues;
  13800. for ( ; argIdx < irParamCount; localIdx++)
  13801. {
  13802. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13803. if ((isThis) && (thisType->IsValuelessType()))
  13804. isThis = false;
  13805. BfLocalVariable* paramVar = NULL;
  13806. while (true)
  13807. {
  13808. BF_ASSERT(localIdx < methodState.mLocals.size());
  13809. paramVar = methodState.mLocals[localIdx];
  13810. if ((paramVar->mCompositeCount == -1) &&
  13811. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13812. break;
  13813. localIdx++;
  13814. }
  13815. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13816. {
  13817. paramVar->mIsReadOnly = true;
  13818. }
  13819. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13820. if (paramVar->mResolvedType->IsMethodRef())
  13821. wantsAddr = false;
  13822. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13823. // {
  13824. // BF_ASSERT(paramVar->mName == "appendIdx");
  13825. // wantsAddr = true;
  13826. // }
  13827. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13828. {
  13829. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13830. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13831. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13832. {
  13833. BfIRType splatIRType;
  13834. if (checkType->IsComposite())
  13835. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13836. else
  13837. splatIRType = mBfIRBuilder->MapType(checkType);
  13838. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13839. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13840. if (!paramVar->mAddr)
  13841. paramVar->mAddr = allocaInst;
  13842. if (WantsLifetimes())
  13843. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13844. splatAddrValues.push_back(allocaInst);
  13845. }, paramVar->mResolvedType);
  13846. mBfIRBuilder->SetInsertPoint(prevInsert);
  13847. }
  13848. else if (isThis)
  13849. {
  13850. if (wantsAddr)
  13851. {
  13852. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13853. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13854. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13855. if (paramVar->mIsSplat)
  13856. {
  13857. if (doDbgAgg)
  13858. {
  13859. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13860. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13861. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13862. paramVar->mAddr = allocaInst;
  13863. if (WantsLifetimes())
  13864. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13865. }
  13866. }
  13867. else
  13868. {
  13869. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13870. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13871. wantPtr = true;
  13872. if (wantPtr)
  13873. {
  13874. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13875. }
  13876. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13877. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13878. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13879. paramVar->mAddr = allocaInst;
  13880. if (WantsLifetimes())
  13881. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13882. }
  13883. mBfIRBuilder->SetInsertPoint(prevInsert);
  13884. }
  13885. }
  13886. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13887. {
  13888. // Address doesn't change so we don't have to alloca it
  13889. BfIRType allocType;
  13890. int alignSize = mSystem->mPtrSize;
  13891. if (paramVar->mResolvedType->IsRef())
  13892. {
  13893. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13894. }
  13895. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13896. {
  13897. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13898. alignSize = paramVar->mResolvedType->mAlign;
  13899. }
  13900. else
  13901. {
  13902. paramVar->mHasLocalStructBacking = true;
  13903. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13904. if (typeInst != NULL)
  13905. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13906. else
  13907. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13908. }
  13909. if (wantsAddr)
  13910. {
  13911. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13912. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13913. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13914. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13915. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13916. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13917. paramVar->mAddr = allocaInst;
  13918. mBfIRBuilder->SetInsertPoint(prevInsert);
  13919. if (WantsLifetimes())
  13920. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13921. }
  13922. }
  13923. else if (wantsAddr)
  13924. {
  13925. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13926. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13927. paramVar->mAddr = allocaInst;
  13928. }
  13929. if (paramVar->mIsSplat)
  13930. {
  13931. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13932. }
  13933. else
  13934. {
  13935. argIdx++;
  13936. }
  13937. }
  13938. if (methodDef->mBody != NULL)
  13939. UpdateSrcPos(methodDef->mBody);
  13940. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13941. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13942. int declArgIdx = 0;
  13943. localIdx = 0;
  13944. argIdx = 0;
  13945. if (methodInstance->HasStructRet())
  13946. argIdx++;
  13947. int splatAddrIdx = 0;
  13948. while (localIdx < (int)methodState.mLocals.size())
  13949. {
  13950. int curLocalIdx = localIdx++;
  13951. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13952. if (!paramVar->IsParam())
  13953. continue;
  13954. if (paramVar->mCompositeCount != -1)
  13955. continue;
  13956. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13957. if ((isThis) && (thisType->IsValuelessType()))
  13958. isThis = false;
  13959. BfIRMDNode diVariable;
  13960. if (wantsDIData)
  13961. {
  13962. String paramName = paramVar->mName;
  13963. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13964. if (isThis)
  13965. {
  13966. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13967. paramName = "__closure";
  13968. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13969. {
  13970. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13971. bool wantRef = paramVar->mResolvedType->IsComposite();
  13972. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13973. wantRef = true;
  13974. if (wantRef)
  13975. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13976. }
  13977. else if (!paramVar->mResolvedType->IsValueType())
  13978. {
  13979. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  13980. }
  13981. }
  13982. else
  13983. {
  13984. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13985. {
  13986. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13987. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13988. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13989. }
  13990. }
  13991. if ((!paramVar->mIsSplat) || (doDbgAgg))
  13992. {
  13993. if (paramVar->mResolvedType->IsValuelessType())
  13994. {
  13995. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  13996. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  13997. }
  13998. else if (paramVar->mIsImplicitParam)
  13999. {
  14000. // Annotate this specially?
  14001. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14002. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14003. }
  14004. else
  14005. {
  14006. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14007. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14008. }
  14009. paramVar->mDbgVarInst = diVariable;
  14010. }
  14011. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14012. {
  14013. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14014. // {
  14015. // // Only add this placeholder if we don't have any values
  14016. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14017. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14018. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14019. // }
  14020. }
  14021. }
  14022. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14023. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14024. {
  14025. // Write our argument value into the .addr
  14026. mBfIRBuilder->ClearDebugLocation();
  14027. if (paramVar->mIsSplat)
  14028. {
  14029. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14030. if (doDbgAgg)
  14031. {
  14032. auto curArgIdx = argIdx;
  14033. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14034. {
  14035. if (checkType->IsStruct())
  14036. {
  14037. auto checkTypeInstance = checkType->ToTypeInstance();
  14038. if (checkTypeInstance->mBaseType != NULL)
  14039. {
  14040. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14041. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14042. }
  14043. if (checkTypeInstance->mIsUnion)
  14044. {
  14045. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14046. if (!unionInnerType->IsValuelessType())
  14047. {
  14048. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14049. checkTypeLambda(unionInnerType, newDestAddr);
  14050. }
  14051. if (checkTypeInstance->IsEnum())
  14052. {
  14053. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14054. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14055. checkTypeLambda(dscrType, newDestAddr);
  14056. }
  14057. }
  14058. else
  14059. {
  14060. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14061. {
  14062. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14063. if (fieldInstance->mDataIdx >= 0)
  14064. {
  14065. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14066. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14067. }
  14068. }
  14069. }
  14070. }
  14071. else if (checkType->IsMethodRef())
  14072. {
  14073. BF_FATAL("Unimplemented");
  14074. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14075. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14076. // {
  14077. // checkTypeLambda->
  14078. // }
  14079. }
  14080. else if (!checkType->IsValuelessType())
  14081. {
  14082. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14083. curArgIdx++;
  14084. }
  14085. };
  14086. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14087. }
  14088. }
  14089. else
  14090. {
  14091. bool handled = false;
  14092. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14093. if (paramVar->mIsLowered)
  14094. {
  14095. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14096. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14097. if (loweredTypeCode != BfTypeCode_None)
  14098. {
  14099. // We have a lowered type coming in, so we have to cast the .addr before storing
  14100. auto primType = GetPrimitiveType(loweredTypeCode);
  14101. auto primPtrType = CreatePointerType(primType);
  14102. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14103. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14104. // We don't want to allow directly using value
  14105. paramVar->mValue = BfIRValue();
  14106. handled = true;
  14107. }
  14108. }
  14109. if (!handled)
  14110. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14111. }
  14112. }
  14113. if (!isThis)
  14114. declArgIdx++;
  14115. if (methodDef->mBody != NULL)
  14116. UpdateSrcPos(methodDef->mBody);
  14117. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14118. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14119. else if (methodDeclaration == NULL)
  14120. UseDefaultSrcPos();
  14121. // Write our argument value into the .addr
  14122. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14123. {
  14124. int splatComponentIdx = 0;
  14125. auto curArgIdx = argIdx;
  14126. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14127. {
  14128. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14129. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14130. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14131. mBfIRBuilder->ClearDebugLocation(storeInst);
  14132. if (wantsDIData)
  14133. {
  14134. BfIRMDNode diType;
  14135. if (checkType->IsComposite())
  14136. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14137. else
  14138. diType = mBfIRBuilder->DbgGetType(checkType);
  14139. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14140. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14141. if (wantsDIVariables)
  14142. {
  14143. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14144. }
  14145. }
  14146. curArgIdx++;
  14147. splatComponentIdx++;
  14148. };
  14149. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14150. {
  14151. if (checkType->IsStruct())
  14152. {
  14153. auto checkTypeInstance = checkType->ToTypeInstance();
  14154. if (checkTypeInstance->mBaseType != NULL)
  14155. {
  14156. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14157. }
  14158. if (checkTypeInstance->mIsUnion)
  14159. {
  14160. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14161. if (!unionInnerType->IsValuelessType())
  14162. {
  14163. _FinishSplatsIterate(unionInnerType, name + "$u");
  14164. }
  14165. if (checkTypeInstance->IsEnum())
  14166. {
  14167. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14168. _FinishSplatsIterate(dscrType, name + "$d");
  14169. }
  14170. }
  14171. else
  14172. {
  14173. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14174. {
  14175. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14176. auto fieldDef = fieldInstance->GetFieldDef();
  14177. if (fieldInstance->mDataIdx >= 0)
  14178. {
  14179. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14180. }
  14181. }
  14182. }
  14183. }
  14184. else if (checkType->IsMethodRef())
  14185. {
  14186. auto methodRefType = (BfMethodRefType*)checkType;
  14187. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14188. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14189. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14190. // {
  14191. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14192. // if (!paramType->IsValuelessType())
  14193. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14194. // }
  14195. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14196. {
  14197. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14198. String paramName = methodInstance->GetParamName(paramIdx);
  14199. if (paramName == "this")
  14200. paramName = "__this";
  14201. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14202. {
  14203. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14204. }
  14205. else
  14206. {
  14207. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14208. }
  14209. }
  14210. }
  14211. else if (!checkType->IsValuelessType())
  14212. {
  14213. _FinishSplats(checkType, name);
  14214. }
  14215. };
  14216. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14217. if (!paramVar->mConstValue)
  14218. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14219. }
  14220. BfIRValue declareCall;
  14221. if (diVariable)
  14222. {
  14223. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14224. {
  14225. if (!paramVar->mAddr)
  14226. {
  14227. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14228. {
  14229. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14230. {
  14231. // We don't need to set the location for this
  14232. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14233. }
  14234. }
  14235. else
  14236. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14237. }
  14238. else
  14239. {
  14240. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14241. }
  14242. }
  14243. }
  14244. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14245. {
  14246. // We don't allow actually assignment to "this", so we just do a single load
  14247. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14248. // we need to store it in the stack frame for debugging purposes
  14249. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14250. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14251. paramVar->mValue = loadedThis;
  14252. }
  14253. if ((wantsDIData) && (declareCall))
  14254. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14255. if (paramVar->mIsSplat)
  14256. {
  14257. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14258. }
  14259. else if (!paramVar->mResolvedType->IsValuelessType())
  14260. {
  14261. argIdx++;
  14262. }
  14263. }
  14264. if (wantsDIData)
  14265. {
  14266. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14267. }
  14268. }
  14269. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14270. {
  14271. auto paramVar = mCurMethodState->mLocals[varIdx];
  14272. // 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
  14273. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14274. // if (paramVar->mIsSplat)
  14275. // {
  14276. // if (wantsDIVariables)
  14277. // {
  14278. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14279. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14280. // }
  14281. // }
  14282. if (paramVar->mResolvedType->IsValuelessType())
  14283. {
  14284. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14285. {
  14286. // Only add this placeholder if we don't have any values
  14287. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14288. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14289. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14290. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14291. }
  14292. }
  14293. }
  14294. if (IsTargetingBeefBackend())
  14295. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14296. if (methodState.mClosureState != NULL)
  14297. {
  14298. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14299. {
  14300. BfLocalVariable* localVar = new BfLocalVariable();
  14301. *localVar = constLocal;
  14302. AddLocalVariableDef(localVar, true);
  14303. }
  14304. }
  14305. bool wantsRemoveBody = false;
  14306. bool skipBody = false;
  14307. bool skipUpdateSrcPos = false;
  14308. bool skipEndChecks = false;
  14309. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14310. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14311. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14312. hasExternSpecifier = true;
  14313. // Allocate, clear, set classVData
  14314. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14315. {
  14316. CreateStaticCtor();
  14317. }
  14318. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14319. {
  14320. skipBody = true;
  14321. skipEndChecks = true;
  14322. if (HasCompiledOutput())
  14323. {
  14324. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14325. mBfIRBuilder->ClearDebugLocation();
  14326. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14327. BfTypeInstance* innerType = boxedType->mElementType;
  14328. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14329. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14330. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14331. if (methodInstance->mIsForeignMethodDef)
  14332. {
  14333. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14334. }
  14335. BfTypeVector methodGenericArguments;
  14336. if (methodInstance->mMethodInfoEx != NULL)
  14337. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14338. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14339. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14340. {
  14341. if (!methodInstance->mReturnType->IsValuelessType())
  14342. {
  14343. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14344. CreateReturn(retVal);
  14345. }
  14346. }
  14347. else
  14348. {
  14349. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14350. SizedArray<BfIRValue, 8> innerParams;
  14351. BfExprEvaluator exprEvaluator(this);
  14352. if (!innerType->IsValuelessType())
  14353. {
  14354. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14355. BfTypedValue innerVal(thisValue, innerType, true);
  14356. if (boxedType->IsBoxedStructPtr())
  14357. {
  14358. innerVal = LoadValue(innerVal);
  14359. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14360. }
  14361. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14362. }
  14363. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14364. {
  14365. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14366. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14367. exprEvaluator.PushArg(localVal, innerParams);
  14368. }
  14369. if (!innerMethodInstance.mFunc)
  14370. {
  14371. BF_ASSERT(innerType->IsUnspecializedType());
  14372. }
  14373. else if (methodInstance->HasStructRet())
  14374. {
  14375. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14376. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14377. exprEvaluator.mReceivingValue = &returnType;
  14378. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14379. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14380. mBfIRBuilder->CreateRetVoid();
  14381. }
  14382. else
  14383. {
  14384. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14385. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14386. if (mCurMethodInstance->mReturnType->IsValueType())
  14387. retVal = LoadValue(retVal);
  14388. CreateReturn(retVal.mValue);
  14389. }
  14390. }
  14391. }
  14392. mCurMethodState->SetHadReturn(true);
  14393. mCurMethodState->mLeftBlockUncond = true;
  14394. }
  14395. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14396. {
  14397. SetIllegalSrcPos();
  14398. mBfIRBuilder->ClearDebugLocation();
  14399. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14400. auto thisVal = GetThis();
  14401. int prevSize = mContext->mBfObjectType->mInstSize;
  14402. int curSize = mCurTypeInstance->mInstSize;
  14403. if (curSize > prevSize)
  14404. {
  14405. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14406. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14407. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14408. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14409. }
  14410. skipUpdateSrcPos = true;
  14411. }
  14412. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14413. {
  14414. EmitCtorBody(skipBody);
  14415. }
  14416. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14417. {
  14418. EmitDtorBody();
  14419. skipBody = true;
  14420. }
  14421. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14422. {
  14423. EmitIteratorBlock(skipBody);
  14424. }
  14425. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14426. {
  14427. // We need to be able to mark deleted objects
  14428. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14429. }
  14430. auto customAttributes = methodInstance->GetCustomAttributes();
  14431. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14432. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14433. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14434. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14435. {
  14436. // We chain even non-default ctors to the default ctors
  14437. auto defaultCtor = methodInstance;
  14438. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14439. CallChainedMethods(defaultCtor, false);
  14440. }
  14441. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14442. if (methodDef->mBody == NULL)
  14443. {
  14444. if (methodDeclaration != NULL)
  14445. {
  14446. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14447. {
  14448. if (operatorDeclaration->mIsConvOperator)
  14449. wantsRemoveBody = true;
  14450. }
  14451. }
  14452. bool isDllImport = false;
  14453. if (methodDef->mImportKind == BfImportKind_Static)
  14454. {
  14455. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14456. {
  14457. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14458. {
  14459. if (customAttr.mCtorArgs.size() == 1)
  14460. {
  14461. auto fileNameArg = customAttr.mCtorArgs[0];
  14462. int strNum = 0;
  14463. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14464. if (constant != NULL)
  14465. {
  14466. if (constant->IsNull())
  14467. continue; // Invalid
  14468. strNum = constant->mInt32;
  14469. }
  14470. else
  14471. {
  14472. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14473. }
  14474. if (!mImportFileNames.Contains(strNum))
  14475. mImportFileNames.Add(strNum);
  14476. }
  14477. }
  14478. }
  14479. //mImportFileNames
  14480. }
  14481. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14482. {
  14483. CreateDllImportMethod();
  14484. }
  14485. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14486. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14487. {
  14488. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14489. {
  14490. // Emit nothing
  14491. }
  14492. else
  14493. {
  14494. CreateDelegateInvokeMethod();
  14495. mCurMethodState->SetHadReturn(true);
  14496. mCurMethodState->mLeftBlockUncond = true;
  14497. }
  14498. }
  14499. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14500. {
  14501. if (mCurTypeInstance->IsObject())
  14502. {
  14503. CreateDynamicCastMethod();
  14504. }
  14505. else
  14506. {
  14507. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14508. mCurMethodState->mHadReturn = true;
  14509. }
  14510. }
  14511. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14512. {
  14513. BfIRValue ret;
  14514. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14515. {
  14516. // This can happen if we provide an invalid name
  14517. AssertErrorState();
  14518. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14519. }
  14520. else
  14521. {
  14522. // Unfortunate DebugLoc shenanigans-
  14523. // 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,
  14524. // so we only set the loc on the CreateRet which gets inlined out
  14525. mBfIRBuilder->SaveDebugLocation();
  14526. mBfIRBuilder->ClearDebugLocation();
  14527. BfIRValue fromBool;
  14528. if (!mCurTypeInstance->IsTypedPrimitive())
  14529. {
  14530. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14531. }
  14532. else
  14533. {
  14534. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14535. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14536. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14537. }
  14538. mBfIRBuilder->RestoreDebugLocation();
  14539. ret = mBfIRBuilder->CreateRet(fromBool);
  14540. //ExtendLocalLifetimes(0);
  14541. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14542. }
  14543. mCurMethodState->SetHadReturn(true);
  14544. mCurMethodState->mLeftBlockUncond = true;
  14545. }
  14546. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14547. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14548. {
  14549. BfIRValue ret;
  14550. // Unfortunate DebugLoc shenanigans-
  14551. // 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,
  14552. // so we only set the loc on the CreateRet which gets inlined out
  14553. mBfIRBuilder->SaveDebugLocation();
  14554. mBfIRBuilder->ClearDebugLocation();
  14555. BfIRValue fromBool;
  14556. mBfIRBuilder->RestoreDebugLocation();
  14557. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14558. //ExtendLocalLifetimes(0);
  14559. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14560. mCurMethodState->SetHadReturn(true);
  14561. mCurMethodState->mLeftBlockUncond = true;
  14562. }
  14563. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14564. {
  14565. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14566. if (HasCompiledOutput())
  14567. {
  14568. EmitEnumToStringBody();
  14569. }
  14570. mBfIRBuilder->CreateRetVoid();
  14571. mCurMethodState->SetHadReturn(true);
  14572. mCurMethodState->mLeftBlockUncond = true;
  14573. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14574. }
  14575. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14576. {
  14577. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14578. if (HasCompiledOutput())
  14579. {
  14580. EmitTupleToStringBody();
  14581. }
  14582. mBfIRBuilder->CreateRetVoid();
  14583. mCurMethodState->SetHadReturn(true);
  14584. mCurMethodState->mLeftBlockUncond = true;
  14585. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14586. }
  14587. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14588. {
  14589. CreateValueTypeEqualsMethod();
  14590. skipBody = true;
  14591. skipEndChecks = true;
  14592. }
  14593. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14594. {
  14595. CreateValueTypeEqualsMethod();
  14596. skipBody = true;
  14597. skipEndChecks = true;
  14598. }
  14599. else if (HasCompiledOutput())
  14600. {
  14601. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14602. {
  14603. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14604. {
  14605. EmitGCMarkMembers();
  14606. }
  14607. else if (!mCurTypeInstance->IsObject())
  14608. {
  14609. }
  14610. }
  14611. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14612. {
  14613. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14614. {
  14615. EmitGCFindTLSMembers();
  14616. }
  14617. }
  14618. }
  14619. }
  14620. else if (!skipBody)
  14621. {
  14622. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14623. if (isEmptyBodied) // Generate autoProperty things
  14624. {
  14625. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14626. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14627. {
  14628. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14629. Fail("Body expected", methodDef->mBody);
  14630. }
  14631. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14632. {
  14633. if (methodInstance->mReturnType->IsValuelessType())
  14634. {
  14635. mBfIRBuilder->CreateRetVoid();
  14636. }
  14637. else if (HasCompiledOutput())
  14638. {
  14639. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14640. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14641. BfFieldDef* fieldDef = NULL;
  14642. if (fieldInstance != NULL)
  14643. fieldDef = fieldInstance->GetFieldDef();
  14644. BfType* retType = methodInstance->mReturnType;
  14645. if (retType->IsRef())
  14646. retType = retType->GetUnderlyingType();
  14647. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14648. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14649. {
  14650. BfTypedValue lookupValue;
  14651. if (fieldDef->IsNonConstStatic())
  14652. lookupValue = ReferenceStaticField(fieldInstance);
  14653. else if (mCurTypeInstance->IsObject())
  14654. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14655. else
  14656. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14657. if (!methodInstance->mReturnType->IsRef())
  14658. lookupValue = LoadValue(lookupValue);
  14659. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14660. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14661. }
  14662. else
  14663. {
  14664. // This can happen if we have two properties with the same name but different types
  14665. AssertErrorState();
  14666. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14667. }
  14668. }
  14669. else
  14670. {
  14671. // During autocomplete, the actual type may not have the proper field instance
  14672. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14673. }
  14674. mCurMethodState->SetHadReturn(true);
  14675. }
  14676. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14677. {
  14678. if (!mCompiler->IsAutocomplete())
  14679. {
  14680. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14681. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14682. auto fieldDef = fieldInstance->GetFieldDef();
  14683. auto& lastParam = mCurMethodState->mLocals.back();
  14684. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14685. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14686. {
  14687. BfIRValue lookupAddr;
  14688. if (fieldDef->IsNonConstStatic())
  14689. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14690. else
  14691. {
  14692. auto thisValue = GetThis();
  14693. if (thisValue.IsSplat())
  14694. {
  14695. BF_FATAL("Should not happen");
  14696. }
  14697. if (mCurTypeInstance->IsObject())
  14698. thisValue = LoadValue(thisValue);
  14699. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14700. }
  14701. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14702. }
  14703. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14704. {
  14705. // This can happen if we have two properties with the same name but different types
  14706. AssertErrorState();
  14707. }
  14708. }
  14709. }
  14710. }
  14711. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14712. {
  14713. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14714. if (mCurMethodInstance->HasStructRet())
  14715. {
  14716. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14717. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14718. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14719. mBfIRBuilder->ClearDebugLocation(storeInst);
  14720. mCurMethodState->mRetValAddr = allocaInst;
  14721. }
  14722. else
  14723. {
  14724. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14725. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14726. }
  14727. }
  14728. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14729. {
  14730. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14731. BfGetSymbolReferenceKind prevSymbolKind;
  14732. BfAutoComplete* prevAutoComplete;
  14733. if (mCompiler->mResolvePassData != NULL)
  14734. {
  14735. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14736. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14737. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14738. }
  14739. EmitCtorCalcAppend();
  14740. if (mCompiler->mResolvePassData != NULL)
  14741. {
  14742. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14743. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14744. }
  14745. }
  14746. else if (!isEmptyBodied)
  14747. {
  14748. if (!mCurMethodState->mIRExitBlock)
  14749. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14750. bool isExpressionBody = false;
  14751. if (methodDeclaration != NULL)
  14752. {
  14753. if (methodDeclaration->mFatArrowToken != NULL)
  14754. isExpressionBody = true;
  14755. }
  14756. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14757. {
  14758. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14759. {
  14760. isExpressionBody = true;
  14761. }
  14762. }
  14763. else
  14764. {
  14765. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14766. {
  14767. if (!block->mChildArr.IsEmpty())
  14768. {
  14769. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14770. {
  14771. if (exprStmt->mTrailingSemicolon == NULL)
  14772. isExpressionBody = true;
  14773. }
  14774. }
  14775. }
  14776. else
  14777. isExpressionBody = true;
  14778. }
  14779. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14780. {
  14781. while (fieldDtorBody != NULL)
  14782. {
  14783. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14784. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14785. }
  14786. }
  14787. else if (!isExpressionBody)
  14788. {
  14789. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14790. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14791. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14792. VisitCodeBlock(bodyBlock);
  14793. }
  14794. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14795. {
  14796. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14797. {
  14798. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14799. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14800. }
  14801. auto expectingType = mCurMethodInstance->mReturnType;
  14802. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14803. // {
  14804. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14805. // }
  14806. //TODO: Why did we have all this stuff for handling void?
  14807. // if (expectingType->IsVoid())
  14808. // {
  14809. // bool wasReturnGenericParam = false;
  14810. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14811. // {
  14812. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14813. // }
  14814. // else
  14815. // {
  14816. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14817. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14818. // wasReturnGenericParam = true;
  14819. // }
  14820. //
  14821. // // If we the void return was from a generic specialization, allow us to return a void result,
  14822. // // otherwise treat expression as though it must be a statement
  14823. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14824. // if (isStatement)
  14825. // expectingType = NULL;
  14826. // }
  14827. UpdateSrcPos(expressionBody);
  14828. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14829. if ((retVal) && (expectingType != NULL))
  14830. {
  14831. mCurMethodState->mHadReturn = true;
  14832. retVal = LoadValue(retVal);
  14833. EmitReturn(retVal.mValue);
  14834. }
  14835. }
  14836. }
  14837. }
  14838. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14839. if (skipUpdateSrcPos)
  14840. {
  14841. // Skip
  14842. }
  14843. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14844. UpdateSrcPos(bodyBlock->mCloseBrace);
  14845. else if (methodDef->mBody != NULL)
  14846. UpdateSrcPos(methodDef->mBody);
  14847. else if (methodDeclaration != NULL)
  14848. UpdateSrcPos(methodDeclaration);
  14849. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14850. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14851. else
  14852. UseDefaultSrcPos();
  14853. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14854. {
  14855. if (mCurMethodState->mRetVal)
  14856. {
  14857. mCurMethodState->SetHadReturn(true);
  14858. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14859. mBfIRBuilder->CreateRet(retVal);
  14860. }
  14861. else
  14862. AssertErrorState();
  14863. }
  14864. if (!mCurMethodState->mHadReturn)
  14865. {
  14866. // Clear off the stackallocs that have occurred after a scopeData break
  14867. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14868. }
  14869. if (mCurMethodState->mIRExitBlock)
  14870. {
  14871. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14872. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14873. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14874. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14875. if (!mCurMethodState->mDIRetVal)
  14876. CreateDIRetVal();
  14877. }
  14878. for (auto localVar : mCurMethodState->mLocals)
  14879. {
  14880. if ((skipEndChecks) || (bodyBlock == NULL))
  14881. break;
  14882. LocalVariableDone(localVar, true);
  14883. }
  14884. if (mCurMethodState->mIRExitBlock)
  14885. {
  14886. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14887. {
  14888. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14889. CreateReturn(loadedVal);
  14890. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14891. if (mCurMethodState->mDIRetVal)
  14892. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14893. }
  14894. else
  14895. {
  14896. // Have something on the last line to step onto
  14897. if (mHasFullDebugInfo)
  14898. {
  14899. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14900. UpdateSrcPos(bodyBlock->mCloseBrace);
  14901. EmitEnsureInstructionAt();
  14902. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14903. {
  14904. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14905. mBfIRBuilder->EnsureFunctionPatchable();
  14906. }
  14907. }
  14908. mBfIRBuilder->CreateRetVoid();
  14909. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14910. if (mCurMethodState->mDIRetVal)
  14911. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14912. }
  14913. }
  14914. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14915. {
  14916. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14917. {
  14918. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14919. {
  14920. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14921. mBfIRBuilder->EnsureFunctionPatchable();
  14922. }
  14923. mBfIRBuilder->CreateRetVoid();
  14924. }
  14925. }
  14926. else
  14927. {
  14928. if (!mCurMethodState->mHadReturn)
  14929. {
  14930. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14931. if (bodyBlock != NULL)
  14932. {
  14933. if (bodyBlock->mCloseBrace != NULL)
  14934. {
  14935. BfAstNode* target = bodyBlock->mCloseBrace;
  14936. Fail("Method must return value", target);
  14937. }
  14938. else
  14939. {
  14940. // It's possible to not have a closing brace if the method ends in an EOF
  14941. AssertErrorState();
  14942. }
  14943. }
  14944. }
  14945. }
  14946. // Move 'init' into 'entry'
  14947. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14948. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14949. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14950. {
  14951. // Don't keep instructions for unspecialized types
  14952. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14953. }
  14954. if ((hasExternSpecifier) && (!skipBody))
  14955. {
  14956. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14957. // incase it gets called later by some hot-loaded coded
  14958. if (mCompiler->mOptions.mAllowHotSwapping)
  14959. CreateFakeCallerMethod(mangledName);
  14960. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14961. }
  14962. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14963. {
  14964. // We only need the DLL stub when we may be hot swapping
  14965. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14966. }
  14967. else if (wantsRemoveBody)
  14968. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14969. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  14970. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  14971. // unspecialized types
  14972. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  14973. {
  14974. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  14975. methodInstance->mIRFunction = BfIRFunction();
  14976. }
  14977. CheckAddFailType();
  14978. if (mHadBuildError)
  14979. prevHadBuildError.CancelRestore();
  14980. if (mHadBuildWarning)
  14981. prevHadWarning.CancelRestore();
  14982. if (!methodDef->mIsLocalMethod)
  14983. ProcessMethod_ProcessDeferredLocals();
  14984. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  14985. if (methodState.mHotDataReferenceBuilder != NULL)
  14986. {
  14987. AddHotDataReferences(&hotDataReferenceBuilder);
  14988. }
  14989. else
  14990. {
  14991. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  14992. {
  14993. // Remove the hot method data
  14994. auto hotMethod = methodInstance->mHotMethod;
  14995. auto prevMethod = hotMethod->mPrevVersion;
  14996. if (prevMethod != NULL)
  14997. {
  14998. // If there's a prev method then pull its data into the main HotMethod.
  14999. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15000. // over to the main HotMethod definition to keep the HotMethod address
  15001. // invariant
  15002. for (auto ref : hotMethod->mReferences)
  15003. ref->Deref();
  15004. hotMethod->mReferences.Clear();
  15005. BF_ASSERT(prevMethod->mRefCount == 1);
  15006. hotMethod->mReferences = prevMethod->mReferences;
  15007. if (hotMethod->mSrcTypeVersion != NULL)
  15008. hotMethod->mSrcTypeVersion->Deref();
  15009. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15010. prevMethod->mSrcTypeVersion = NULL;
  15011. prevMethod->mReferences.Clear();
  15012. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15013. prevMethod->mPrevVersion = NULL;
  15014. prevMethod->Deref();
  15015. }
  15016. hotMethod->Deref();
  15017. methodInstance->mHotMethod = NULL;
  15018. }
  15019. }
  15020. }
  15021. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15022. {
  15023. String name;
  15024. bool found = false;
  15025. auto checkMethodState = mCurMethodState;
  15026. while (checkMethodState != NULL)
  15027. {
  15028. if (checkMethodState->mClosureState == NULL)
  15029. break;
  15030. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15031. {
  15032. found = true;
  15033. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15034. break;
  15035. }
  15036. checkMethodState = checkMethodState->mPrevMethodState;
  15037. }
  15038. if (!found)
  15039. name += mCurMethodInstance->mMethodDef->mName;
  15040. int prevSepPos = (int)name.LastIndexOf('$');
  15041. if (prevSepPos != -1)
  15042. {
  15043. name.RemoveToEnd(prevSepPos);
  15044. }
  15045. name += "@";
  15046. name += baseName;
  15047. HashContext hashCtx;
  15048. if (anchorNode != NULL)
  15049. {
  15050. hashCtx.Mixin(anchorNode->GetStartCharId());
  15051. }
  15052. //
  15053. {
  15054. auto checkMethodState = declMethodState;
  15055. auto checkMixinState = declMixinState;
  15056. while (checkMethodState != NULL)
  15057. {
  15058. if (checkMixinState != NULL)
  15059. {
  15060. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15061. }
  15062. checkMethodState = checkMethodState->mPrevMethodState;
  15063. if (checkMethodState != NULL)
  15064. checkMixinState = checkMethodState->mMixinState;
  15065. }
  15066. }
  15067. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15068. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15069. {
  15070. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15071. {
  15072. StringT<128> genericTypeName;
  15073. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15074. hashCtx.MixinStr(genericTypeName);
  15075. }
  15076. }
  15077. uint64 hashVal = hashCtx.Finish64();
  15078. name += "$";
  15079. name += BfTypeUtils::HashEncode64(hashVal);
  15080. return name;
  15081. }
  15082. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15083. {
  15084. if (localMethod->mMethodDef != NULL)
  15085. return localMethod->mMethodDef;
  15086. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15087. auto declMethodState = localMethod->mDeclMethodState;
  15088. auto declMixinState = localMethod->mDeclMixinState;
  15089. auto typeInst = mCurTypeInstance;
  15090. BfAstNode* body = NULL;
  15091. BfAstNode* anchorNode = NULL;
  15092. auto _AllocDirectTypeRef = [&](BfType* type)
  15093. {
  15094. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15095. directTypeRef->Init(type);
  15096. return directTypeRef;
  15097. };
  15098. auto methodDeclaration = localMethod->mMethodDeclaration;
  15099. if (methodDeclaration != NULL)
  15100. {
  15101. body = methodDeclaration->mBody;
  15102. anchorNode = methodDeclaration->mOpenParen;
  15103. }
  15104. else
  15105. {
  15106. body = localMethod->mLambdaBindExpr->mBody;
  15107. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15108. }
  15109. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15110. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15111. BfMethodDef* methodDef;
  15112. if (methodDeclaration != NULL)
  15113. {
  15114. BfDefBuilder defBuilder(mCompiler->mSystem);
  15115. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15116. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15117. BfMethodDef* outerMethodDef = NULL;
  15118. if (localMethod->mOuterLocalMethod != NULL)
  15119. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15120. else
  15121. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15122. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15123. }
  15124. else
  15125. {
  15126. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15127. methodDef = new BfMethodDef();
  15128. methodDef->mName = localMethod->mMethodName;
  15129. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15130. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15131. methodDef->mBody = body;
  15132. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15133. {
  15134. auto paramType = invokeMethod->GetParamType(paramIdx);
  15135. String paramName;
  15136. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15137. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15138. else
  15139. paramName = invokeMethod->GetParamName(paramIdx);
  15140. auto paramDef = new BfParameterDef();
  15141. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15142. paramDef->mName = paramName;
  15143. methodDef->mParams.Add(paramDef);
  15144. }
  15145. }
  15146. methodDef->mIdx = ~methodLocalIdx;
  15147. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15148. methodDef->mName = localMethod->mExpectedFullName;
  15149. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15150. //
  15151. // if (!localMethod->mExpectedFullName.IsEmpty())
  15152. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15153. methodDef->mIsStatic = true;
  15154. methodDef->mIsLocalMethod = true;
  15155. methodDef->mIsVirtual = false;
  15156. localMethod->mMethodDef = methodDef;
  15157. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15158. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15159. methodInstanceGroup->mMethodIdx = -1;
  15160. methodInstanceGroup->mOwner = mCurTypeInstance;
  15161. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15162. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15163. {
  15164. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15165. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15166. }
  15167. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15168. {
  15169. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15170. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15171. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15172. {
  15173. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15174. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15175. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15176. autoComplete->mDefType = typeInst->mTypeDef;
  15177. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15178. autoComplete->mReplaceLocalId = methodLocalIdx;
  15179. }
  15180. }
  15181. return localMethod->mMethodDef;
  15182. }
  15183. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15184. {
  15185. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15186. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15187. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15188. auto declMethodState = localMethod->mDeclMethodState;
  15189. auto declMixinState = localMethod->mDeclMixinState;
  15190. auto callerMethodState = mCurMethodState;
  15191. auto typeInst = mCurTypeInstance;
  15192. auto methodDef = GetLocalMethodDef(localMethod);
  15193. BfAstNode* body = NULL;
  15194. auto methodDeclaration = localMethod->mMethodDeclaration;
  15195. if (methodDeclaration != NULL)
  15196. {
  15197. body = methodDeclaration->mBody;
  15198. }
  15199. else
  15200. {
  15201. body = localMethod->mLambdaBindExpr->mBody;
  15202. }
  15203. bool hadConcreteInterfaceGenericArgument = false;
  15204. BfTypeVector sanitizedMethodGenericArguments;
  15205. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15206. // version of this method for this pass through the outermost method
  15207. int dependentGenericStartIdx = 0;
  15208. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15209. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15210. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15211. if (methodGenericArguments.size() == 0)
  15212. {
  15213. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15214. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15215. }
  15216. else
  15217. {
  15218. int genericArgIdx = 0;
  15219. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15220. // {
  15221. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15222. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15223. // }
  15224. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15225. {
  15226. auto genericArgType = methodGenericArguments[genericArgIdx];
  15227. BF_ASSERT(!genericArgType->IsRef());
  15228. if (genericArgType->IsConcreteInterfaceType())
  15229. {
  15230. hadConcreteInterfaceGenericArgument = true;
  15231. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15232. genericArgType = concreteInterfaceType->mInterface;
  15233. }
  15234. sanitizedMethodGenericArguments.push_back(genericArgType);
  15235. }
  15236. }
  15237. bool wantPrematureMethodInstance = false;
  15238. if (!force)
  15239. {
  15240. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15241. }
  15242. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15243. bool isDefaultPass = true;
  15244. BfTypeVector lookupMethodGenericArguments;
  15245. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15246. {
  15247. auto genericArgType = methodGenericArguments[genericArgIdx];
  15248. BF_ASSERT(!genericArgType->IsRef());
  15249. lookupMethodGenericArguments.Add(genericArgType);
  15250. if (genericArgType->IsGenericParam())
  15251. {
  15252. auto genericParam = (BfGenericParamType*)genericArgType;
  15253. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15254. isDefaultPass = false;
  15255. }
  15256. else
  15257. {
  15258. isDefaultPass = false;
  15259. }
  15260. }
  15261. bool hadExistingMethodInstance = false;
  15262. if (methodInstance != NULL)
  15263. {
  15264. hadExistingMethodInstance = true;
  15265. }
  15266. else
  15267. {
  15268. if (isDefaultPass)
  15269. {
  15270. methodInstance = methodInstGroup->mDefault;
  15271. if (methodInstance != NULL)
  15272. {
  15273. hadExistingMethodInstance = true;
  15274. }
  15275. else
  15276. {
  15277. methodInstance = new BfMethodInstance();
  15278. methodInstGroup->mDefault = methodInstance;
  15279. }
  15280. }
  15281. else
  15282. {
  15283. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15284. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15285. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15286. BfMethodInstance** methodInstancePtr = NULL;
  15287. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15288. {
  15289. methodInstance = *methodInstancePtr;
  15290. hadExistingMethodInstance = true;
  15291. }
  15292. else
  15293. {
  15294. methodInstance = new BfMethodInstance();
  15295. *methodInstancePtr = methodInstance;
  15296. }
  15297. }
  15298. }
  15299. if (hadExistingMethodInstance)
  15300. {
  15301. if ((!methodInstance->mDisallowCalling) ||
  15302. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15303. return BfModuleMethodInstance(methodInstance);
  15304. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15305. }
  15306. else
  15307. {
  15308. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15309. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15310. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15311. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15312. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15313. methodInstance->mMethodDef = methodDef;
  15314. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15315. if (hadConcreteInterfaceGenericArgument)
  15316. methodInstance->mIgnoreBody = true;
  15317. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15318. for (auto genericArg : sanitizedMethodGenericArguments)
  15319. {
  15320. if (genericArg->IsPrimitiveType())
  15321. genericArg = GetWrappedStructType(genericArg);
  15322. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15323. }
  15324. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15325. {
  15326. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15327. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15328. }
  15329. SetupMethodIdHash(methodInstance);
  15330. }
  15331. auto _SetupMethodInstance = [&]()
  15332. {
  15333. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15334. // Generic constraints
  15335. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15336. {
  15337. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15338. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15339. }
  15340. };
  15341. //////////////////////////////////////////////////////////////////////////
  15342. auto _VisitLambdaBody = [&]()
  15343. {
  15344. if (localMethod->mDeclOnly)
  15345. return;
  15346. if (mCompiler->mCanceling)
  15347. return;
  15348. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15349. {
  15350. VisitCodeBlock(blockBody);
  15351. }
  15352. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15353. CreateValueFromExpression(bodyExpr);
  15354. };
  15355. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15356. {
  15357. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15358. auto result = ResolveTypeRef(typeRef);
  15359. if (result == NULL)
  15360. result = mContext->mBfObjectType;
  15361. return result;
  15362. };
  15363. BfTypeInstance* outerClosure = NULL;
  15364. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15365. outerClosure = declMethodState->mClosureState->mClosureType;
  15366. BfMethodState methodState;
  15367. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15368. BfIRFunctionType funcType;
  15369. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15370. SizedArray<BfIRType, 0> paramTypes;
  15371. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15372. mBfIRBuilder->SaveDebugLocation();
  15373. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15374. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15375. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15376. BfDeferredLocalAssignData deferredLocalAssignData;
  15377. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15378. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15379. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15380. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15381. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15382. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15383. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15384. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15385. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15386. methodState.mIRFunction = declMethodState->mIRFunction;
  15387. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15388. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15389. BfClosureState closureState;
  15390. if (methodDef->mMethodType == BfMethodType_Mixin)
  15391. {
  15392. if (declMethodState != NULL)
  15393. {
  15394. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15395. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15396. else if (declMethodState->mMethodInstance != NULL)
  15397. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15398. }
  15399. }
  15400. if (closureState.mReturnType == NULL)
  15401. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15402. closureState.mCapturing = true;
  15403. closureState.mLocalMethod = localMethod;
  15404. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15405. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15406. methodState.mClosureState = &closureState;
  15407. closureState.mClosureType = outerClosure;
  15408. int outerLocalsCount = (int)methodState.mLocals.size();
  15409. if (!hadExistingMethodInstance)
  15410. {
  15411. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15412. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15413. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15414. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15415. auto declareModule = this;
  15416. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15417. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15418. BF_ASSERT(declareModule != NULL);
  15419. methodInstance->mDeclModule = declareModule;
  15420. _SetupMethodInstance();
  15421. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15422. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15423. }
  15424. if (wantPrematureMethodInstance)
  15425. {
  15426. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15427. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15428. // its true method instance
  15429. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15430. //BF_ASSERT(moduleMethodInstance);
  15431. return BfModuleMethodInstance(methodInstance);
  15432. }
  15433. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15434. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15435. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15436. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15437. closureState.mClosureMethodDef = methodDef;
  15438. bool wantsVisitBody = true;
  15439. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15440. wantsVisitBody = false;
  15441. if (methodInstance->mIsUnspecializedVariation)
  15442. wantsVisitBody = false;
  15443. if (wantsVisitBody)
  15444. {
  15445. BP_ZONE("VisitLambdaBody");
  15446. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15447. // this capture stage for each of those times
  15448. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15449. /*
  15450. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15451. // that will not occur during the actual lambda method generation, for example: returning a value
  15452. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15453. // our AST nodes will still be visited
  15454. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15455. */
  15456. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15457. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15458. mBfIRBuilder->SaveDebugLocation();
  15459. closureState.mCaptureVisitingBody = true;
  15460. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15461. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15462. NewScopeState();
  15463. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15464. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15465. {
  15466. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15467. for (auto localDef : methodState.mLocals)
  15468. {
  15469. if (localDef->mResolvedType->IsVar())
  15470. continue;
  15471. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15472. }
  15473. }
  15474. _VisitLambdaBody();
  15475. RestoreScopeState();
  15476. //ProcessMethod(methodInstance);
  15477. closureState.mCaptureVisitingBody = false;
  15478. mBfIRBuilder->RestoreDebugLocation();
  15479. }
  15480. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15481. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15482. {
  15483. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15484. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15485. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15486. }
  15487. //RestoreScopeState();
  15488. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15489. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15490. closureState.mClosureMethodDef = NULL;
  15491. for (auto methodInstance : closureState.mLocalMethodRefs)
  15492. {
  15493. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15494. }
  15495. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15496. prevIgnoreWrites.Restore();
  15497. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15498. //
  15499. {
  15500. auto varMethodState = declMethodState;
  15501. while (varMethodState != NULL)
  15502. {
  15503. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15504. {
  15505. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15506. methodDef->mIsStatic = false;
  15507. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15508. methodDef->mIsMutating = true;
  15509. }
  15510. bool copyOuterCaptures = false;
  15511. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15512. {
  15513. auto localVar = varMethodState->mLocals[localIdx];
  15514. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15515. {
  15516. if (localVar->mIsThis)
  15517. {
  15518. // We can only set mutating if our owning type is mutating
  15519. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15520. {
  15521. if (mCurTypeInstance->IsValueType())
  15522. {
  15523. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15524. methodDef->mIsMutating = true;
  15525. }
  15526. }
  15527. methodDef->mIsStatic = false;
  15528. continue;
  15529. }
  15530. if ((localVar->mIsThis) && (outerClosure != NULL))
  15531. {
  15532. continue;
  15533. }
  15534. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15535. {
  15536. closureState.mConstLocals.push_back(*localVar);
  15537. continue;
  15538. }
  15539. BfClosureCapturedEntry capturedEntry;
  15540. auto capturedType = localVar->mResolvedType;
  15541. bool captureByRef = false;
  15542. if (!capturedType->IsRef())
  15543. {
  15544. if (localVar->mIsThis)
  15545. {
  15546. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15547. captureByRef = true;
  15548. }
  15549. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15550. captureByRef = true;
  15551. }
  15552. else
  15553. {
  15554. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15555. {
  15556. capturedType = ((BfRefType*)capturedType)->mElementType;
  15557. }
  15558. }
  15559. if (captureByRef)
  15560. {
  15561. //capturedEntry.mIsByReference = true;
  15562. capturedType = CreateRefType(capturedType);
  15563. }
  15564. else
  15565. {
  15566. //capturedEntry.mIsByReference = false;
  15567. }
  15568. capturedEntry.mNameNode = localVar->mNameNode;
  15569. capturedEntry.mType = capturedType;
  15570. capturedEntry.mName = localVar->mName;
  15571. //capturedEntry.mLocalVarDef = localVar;
  15572. capturedEntries.insert(capturedEntry);
  15573. }
  15574. }
  15575. varMethodState = varMethodState->mPrevMethodState;
  15576. if ((varMethodState == NULL) ||
  15577. (varMethodState->mMixinState != NULL) ||
  15578. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15579. break;
  15580. }
  15581. }
  15582. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15583. {
  15584. auto fieldDef = copyField->GetFieldDef();
  15585. BfClosureCapturedEntry capturedEntry;
  15586. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15587. capturedEntry.mType = copyField->mResolvedType;
  15588. if (capturedEntry.mType->IsRef())
  15589. {
  15590. // Keep by ref
  15591. }
  15592. else if (!fieldDef->mIsReadOnly)
  15593. {
  15594. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15595. }
  15596. capturedEntries.insert(capturedEntry);
  15597. }
  15598. int captureIdx = 0;
  15599. for (auto& capturedEntry : capturedEntries)
  15600. {
  15601. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15602. }
  15603. /*if (isDefaultPass)
  15604. {
  15605. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15606. int captureIdx = 0;
  15607. for (auto& capturedEntry : capturedEntries)
  15608. {
  15609. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15610. BfParameterDef* paramDef = new BfParameterDef();
  15611. paramDef->mName = capturedEntry.mName;
  15612. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15613. directTypeRef->mType = capturedEntry.mType;
  15614. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15615. paramDef->mTypeRef = directTypeRef;
  15616. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15617. methodDef->mParams.Insert(captureIdx, paramDef);
  15618. captureIdx++;
  15619. }
  15620. }
  15621. else
  15622. {
  15623. auto defaultMethodInstance = methodInstGroup->mDefault;
  15624. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15625. }*/
  15626. methodState.Reset();
  15627. closureState.mCapturing = false;
  15628. //////////////////////////////////////////////////////////////////////////
  15629. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15630. if (methodInstance->mReturnType != NULL)
  15631. {
  15632. BF_ASSERT(methodInstance->mDisallowCalling);
  15633. // We did a premature declaration (without captures)
  15634. methodInstance->UndoDeclaration();
  15635. methodInstance->mDisallowCalling = false;
  15636. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15637. }
  15638. auto declareModule = this;
  15639. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15640. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15641. BF_ASSERT(declareModule != NULL);
  15642. methodInstance->mDeclModule = declareModule;
  15643. _SetupMethodInstance();
  15644. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15645. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15646. closureState.mReturnType = methodInstance->mReturnType;
  15647. mCompiler->mStats.mMethodsQueued++;
  15648. mCompiler->UpdateCompletion();
  15649. declareModule->mIncompleteMethodCount++;
  15650. mCompiler->mStats.mMethodsProcessed++;
  15651. if (!methodInstance->mIsReified)
  15652. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15653. auto deferMethodState = rootMethodState;
  15654. // 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)
  15655. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15656. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15657. {
  15658. BP_ZONE("BfDeferredLocalMethod:create");
  15659. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15660. deferredLocalMethod->mLocalMethod = localMethod;
  15661. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15662. deferredLocalMethod->mMethodInstance = methodInstance;
  15663. auto checkMethodState = declMethodState;
  15664. while (checkMethodState != NULL)
  15665. {
  15666. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15667. {
  15668. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15669. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15670. }
  15671. if (checkMethodState->mMixinState != NULL)
  15672. {
  15673. BfMixinRecord mixinRecord;
  15674. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15675. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15676. }
  15677. checkMethodState = checkMethodState->mPrevMethodState;
  15678. }
  15679. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15680. }
  15681. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15682. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15683. mBfIRBuilder->RestoreDebugLocation();
  15684. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15685. {
  15686. auto checkMethodState = mCurMethodState;
  15687. while (checkMethodState != NULL)
  15688. {
  15689. BfLocalMethod* nextLocalMethod = NULL;
  15690. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15691. {
  15692. while (nextLocalMethod != NULL)
  15693. {
  15694. auto checkLocalMethod = nextLocalMethod;
  15695. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15696. if (checkLocalMethod == localMethod)
  15697. continue;
  15698. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15699. continue;
  15700. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15701. if (checkMethodInstance == NULL)
  15702. continue; // Not generated yet
  15703. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15704. {
  15705. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15706. if (bfError != NULL)
  15707. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15708. }
  15709. }
  15710. }
  15711. checkMethodState = checkMethodState->mPrevMethodState;
  15712. }
  15713. }
  15714. return BfModuleMethodInstance(methodInstance);
  15715. }
  15716. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15717. {
  15718. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15719. return 0;
  15720. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15721. int rootMethodGenericParamCount = 0;
  15722. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15723. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15724. if (mCurMethodInstance == NULL)
  15725. return rootMethodGenericParamCount;
  15726. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15727. return rootMethodGenericParamCount;
  15728. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15729. if (callerLocalMethod == NULL)
  15730. return rootMethodGenericParamCount;
  15731. BfLocalMethod* calledLocalMethod = NULL;
  15732. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15733. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15734. {
  15735. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15736. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15737. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15738. }
  15739. return rootMethodGenericParamCount;
  15740. }
  15741. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15742. {
  15743. auto methodDef = methodInstance->mMethodDef;
  15744. if (methodInstance->GetCustomAttributes() != NULL)
  15745. return;
  15746. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15747. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15748. auto typeInstance = methodInstance->GetOwner();
  15749. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15750. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15751. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15752. {
  15753. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15754. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15755. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15756. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15757. }
  15758. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15759. {
  15760. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15761. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15762. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15763. }
  15764. }
  15765. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15766. {
  15767. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15768. {
  15769. // Don't create a func
  15770. return;
  15771. }
  15772. auto typeInstance = methodInstance->GetOwner();
  15773. auto methodDef = methodInstance->mMethodDef;
  15774. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15775. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15776. if (mCompiler->mResolvePassData == NULL)
  15777. {
  15778. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15779. {
  15780. typeInstance->mHasStaticInitMethod = true;
  15781. }
  15782. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15783. {
  15784. typeInstance->mHasStaticDtorMethod = true;
  15785. }
  15786. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15787. {
  15788. typeInstance->mHasStaticMarkMethod = true;
  15789. }
  15790. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15791. {
  15792. typeInstance->mHasTLSFindMethod = true;
  15793. }
  15794. }
  15795. if (isTemporaryFunc)
  15796. {
  15797. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15798. mangledName = "autocomplete_tmp";
  15799. }
  15800. if (!mBfIRBuilder->mIgnoreWrites)
  15801. {
  15802. BfIRFunction prevFunc;
  15803. // Remove old version (if we have one)
  15804. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15805. if (prevFunc)
  15806. {
  15807. if (methodDef->mIsExtern)
  15808. {
  15809. // Allow this
  15810. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15811. }
  15812. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15813. {
  15814. // We can have a collision of names when we have generic methods that differ only in
  15815. // their constraints, but they should only collide in their unspecialized form
  15816. // since only one will be chosen for a given concrete type
  15817. mCurMethodInstance->mMangleWithIdx = true;
  15818. mangledName.Clear();
  15819. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15820. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15821. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15822. }
  15823. else
  15824. {
  15825. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15826. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15827. }
  15828. }
  15829. }
  15830. if (typeInstance != mContext->mBfObjectType)
  15831. {
  15832. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15833. GetMethodCustomAttributes(methodInstance);
  15834. }
  15835. // if (prevFunc)
  15836. // {
  15837. // if (methodDef->mIsExtern)
  15838. // {
  15839. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15840. // methodInstance->mIRFunction = prevFunc;
  15841. // }
  15842. // else
  15843. // {
  15844. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15845. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15846. // {
  15847. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15848. // BfLogSysM("Ignoring function name collision\n");
  15849. // }
  15850. // else
  15851. // {
  15852. // if (methodDef->mMethodDeclaration == NULL)
  15853. // {
  15854. // AssertErrorState();
  15855. // }
  15856. // else
  15857. // {
  15858. // BF_ASSERT(mIsSpecialModule);
  15859. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15860. // {
  15861. // // We shouldn't have name collisions on the first run!
  15862. // AssertErrorState();
  15863. // }
  15864. // }
  15865. // }
  15866. // BfLogSysM("Before erase\n");
  15867. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15868. // }
  15869. // }
  15870. bool isIntrinsic = false;
  15871. if (!methodInstance->mIRFunction)
  15872. {
  15873. BfIRFunction func;
  15874. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15875. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15876. {
  15877. if (!mIsReified)
  15878. wantsLLVMFunc = false;
  15879. }*/
  15880. if (wantsLLVMFunc)
  15881. {
  15882. func = GetIntrinsic(methodInstance, true);
  15883. if (func)
  15884. {
  15885. isIntrinsic = true;
  15886. }
  15887. else
  15888. {
  15889. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15890. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15891. if (methodInstance->mAlwaysInline)
  15892. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15893. // if (prevFunc)
  15894. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15895. }
  15896. methodInstance->mIRFunction = func;
  15897. //if (!ignoreWrites)
  15898. //BF_ASSERT(!func.IsFake());
  15899. }
  15900. }
  15901. if (outIsIntrinsic != NULL)
  15902. *outIsIntrinsic = isIntrinsic;
  15903. if (!isIntrinsic)
  15904. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15905. }
  15906. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15907. {
  15908. if (methodInstance->mHotMethod != NULL)
  15909. return;
  15910. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15911. {
  15912. auto srcTypeInst = methodInstance->GetOwner();
  15913. StringT<128> mangledName = inMangledName;
  15914. if (mangledName.IsEmpty())
  15915. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15916. // We always keep the current primary method at the same address
  15917. BfHotMethod* hotMethod;
  15918. BfHotMethod** hotMethodPtr;
  15919. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15920. {
  15921. hotMethod = new BfHotMethod();
  15922. *hotMethodPtr = hotMethod;
  15923. hotMethod->mRefCount = 1;
  15924. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15925. #ifdef BF_DBG_HOTMETHOD_IDX
  15926. static int sMethodIdx = 0;
  15927. hotMethod->mMethodIdx = sMethodIdx++;
  15928. #endif
  15929. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15930. }
  15931. else
  15932. {
  15933. hotMethod = *hotMethodPtr;
  15934. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15935. {
  15936. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15937. auto prevHotMethod = *hotMethodPtr;
  15938. hotMethod = new BfHotMethod();
  15939. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15940. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15941. hotDupMethod->mRefCount++;
  15942. prevHotMethod->mReferences.Add(hotDupMethod);
  15943. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15944. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15945. }
  15946. else if (mCompiler->IsHotCompile())
  15947. {
  15948. // Link the previous version into the mPrevVersion
  15949. BfHotMethod* prevMethod = new BfHotMethod();
  15950. prevMethod->mRefCount = 1;
  15951. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15952. hotMethod->mPrevVersion = prevMethod;
  15953. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15954. hotMethod->mSrcTypeVersion = NULL;
  15955. prevMethod->mFlags = hotMethod->mFlags;
  15956. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15957. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15958. #ifdef BF_DBG_HOTMETHOD_NAME
  15959. prevMethod->mMangledName = hotMethod->mMangledName;
  15960. #endif
  15961. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15962. }
  15963. else
  15964. {
  15965. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15966. hotMethod->Clear(true);
  15967. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15968. }
  15969. }
  15970. if (methodInstance->mIsClosure)
  15971. {
  15972. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  15973. }
  15974. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  15975. hotMethod->mSrcTypeVersion->mRefCount++;
  15976. hotMethod->mRefCount++;
  15977. #ifdef BF_DBG_HOTMETHOD_NAME
  15978. hotMethod->mMangledName = mangledName;
  15979. #endif
  15980. methodInstance->mHotMethod = hotMethod;
  15981. }
  15982. }
  15983. // methodDeclaration is NULL for default constructors
  15984. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  15985. {
  15986. BP_ZONE("BfModule::BfMethodDeclaration");
  15987. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  15988. // to effectively make mIgnoreWrites method-scoped
  15989. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  15990. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  15991. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  15992. if (mCompiler->IsAutocomplete())
  15993. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  15994. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  15995. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  15996. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  15997. if (mAwaitingInitFinish)
  15998. FinishInit();
  15999. auto typeInstance = mCurTypeInstance;
  16000. auto typeDef = typeInstance->mTypeDef;
  16001. auto methodDef = mCurMethodInstance->mMethodDef;
  16002. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16003. if (typeInstance->IsClosure())
  16004. {
  16005. if (methodDef->mName == "Invoke")
  16006. return;
  16007. }
  16008. auto methodInstance = mCurMethodInstance;
  16009. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16010. addToWorkList = false;
  16011. bool hasNonGenericParams = false;
  16012. bool hasGenericParams = false;
  16013. int dependentGenericStartIdx = 0;
  16014. if (methodDef->mIsLocalMethod)
  16015. {
  16016. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16017. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16018. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16019. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16020. // over the local method each time
  16021. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16022. dependentGenericStartIdx = 0;
  16023. if (rootMethodInstance->mMethodInfoEx != NULL)
  16024. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16025. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16026. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16027. }
  16028. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16029. {
  16030. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16031. if (genericArgType->IsGenericParam())
  16032. {
  16033. hasGenericParams = true;
  16034. auto genericParam = (BfGenericParamType*)genericArgType;
  16035. methodInstance->mIsUnspecialized = true;
  16036. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16037. methodInstance->mIsUnspecializedVariation = true;
  16038. }
  16039. else
  16040. {
  16041. hasNonGenericParams = true;
  16042. if (genericArgType->IsUnspecializedType())
  16043. {
  16044. methodInstance->mIsUnspecialized = true;
  16045. methodInstance->mIsUnspecializedVariation = true;
  16046. }
  16047. }
  16048. }
  16049. if ((hasGenericParams) && (hasNonGenericParams))
  16050. {
  16051. methodInstance->mIsUnspecializedVariation = true;
  16052. }
  16053. if (typeInstance->IsUnspecializedType())
  16054. {
  16055. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16056. // actually want to do method processing on it
  16057. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16058. methodInstance->mIsUnspecializedVariation = true;
  16059. methodInstance->mIsUnspecialized = true;
  16060. }
  16061. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16062. for (auto genericParamDef : methodDef->mGenericParams)
  16063. {
  16064. if (mCompiler->IsAutocomplete())
  16065. {
  16066. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16067. //autoComplete->CheckTypeRef()
  16068. }
  16069. }
  16070. if (methodInstance->mIsUnspecializedVariation)
  16071. {
  16072. }
  16073. if (methodInstance->mIsUnspecializedVariation)
  16074. BF_ASSERT(methodInstance->mIsUnspecialized);
  16075. if (methodDef->mMethodType == BfMethodType_Mixin)
  16076. methodInstance->mIsUnspecialized = true;
  16077. BfAutoComplete* bfAutocomplete = NULL;
  16078. if (mCompiler->mResolvePassData != NULL)
  16079. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16080. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16081. {
  16082. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16083. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16084. if (bfAutocomplete != NULL)
  16085. {
  16086. for (auto nameNode : genericParamDef->mNameNodes)
  16087. {
  16088. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16089. }
  16090. }
  16091. }
  16092. if (methodInstance->mMethodInfoEx != NULL)
  16093. {
  16094. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16095. {
  16096. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16097. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16098. if (genericParam->mTypeConstraint != NULL)
  16099. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16100. }
  16101. }
  16102. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16103. {
  16104. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16105. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16106. if (nameNode == NULL)
  16107. {
  16108. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16109. nameNode = ctorDeclaration->mThisToken;
  16110. }
  16111. if (autoComplete->IsAutocompleteNode(nameNode))
  16112. {
  16113. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16114. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16115. autoComplete->mDefType = typeDef;
  16116. autoComplete->mDefMethod = methodDef;
  16117. autoComplete->SetDefinitionLocation(nameNode);
  16118. if (methodDef->mIsOverride)
  16119. {
  16120. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16121. {
  16122. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16123. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16124. continue;
  16125. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16126. if (virtMethod != NULL)
  16127. {
  16128. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16129. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16130. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16131. {
  16132. // Is matching method
  16133. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16134. {
  16135. auto baseType = typeInstance->mBaseType;
  16136. if (baseType != NULL)
  16137. {
  16138. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16139. baseType = baseType->mBaseType;
  16140. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16141. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16142. autoComplete->mDefType = baseType->mTypeDef;
  16143. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16144. }
  16145. }
  16146. break;
  16147. }
  16148. }
  16149. }
  16150. }
  16151. }
  16152. }
  16153. bool reportErrors = true;
  16154. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16155. reportErrors = true;
  16156. // Only the defining contexts needs to report errors here
  16157. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16158. if (methodDef->mMethodType == BfMethodType_Dtor)
  16159. {
  16160. if (methodDef->mIsStatic)
  16161. {
  16162. }
  16163. else
  16164. {
  16165. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16166. {
  16167. BfAstNode* refNode = methodDeclaration;
  16168. if (refNode == NULL)
  16169. {
  16170. // Whatever caused this ctor to be generated should have caused another failure
  16171. // But that failure might not be generated until the ctor is generated
  16172. }
  16173. else
  16174. {
  16175. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16176. if (dtorDecl != NULL)
  16177. refNode = dtorDecl->mThisToken;
  16178. Fail("Structs cannot have destructors", refNode);
  16179. }
  16180. }
  16181. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16182. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16183. (mCurTypeInstance != mContext->mBfObjectType))
  16184. {
  16185. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16186. }
  16187. }
  16188. }
  16189. BfType* resolvedReturnType = NULL;
  16190. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16191. (methodDef->mReturnTypeRef != NULL))
  16192. {
  16193. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16194. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16195. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16196. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16197. {
  16198. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16199. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16200. }
  16201. if (resolvedReturnType == NULL)
  16202. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16203. }
  16204. else
  16205. {
  16206. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16207. }
  16208. BF_ASSERT(resolvedReturnType != NULL);
  16209. mCurMethodInstance->mReturnType = resolvedReturnType;
  16210. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16211. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16212. //if (!methodInstance->IsSpecializedGenericMethod())
  16213. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16214. if (methodDef->mExplicitInterface != NULL)
  16215. {
  16216. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16217. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16218. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16219. if (explicitInterface != NULL)
  16220. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16221. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16222. {
  16223. bool interfaceFound = false;
  16224. for (auto ifaceInst : typeInstance->mInterfaces)
  16225. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16226. if (!interfaceFound)
  16227. {
  16228. if (methodDef->mMethodDeclaration != NULL)
  16229. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16230. else
  16231. {
  16232. // For property decls, we should have already given the error during type population
  16233. if (mCompiler->mRevision == 1)
  16234. AssertErrorState();
  16235. }
  16236. }
  16237. }
  16238. }
  16239. bool isThisStruct = mCurTypeInstance->IsStruct();
  16240. BfType* thisType = NULL;
  16241. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16242. {
  16243. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16244. {
  16245. thisType = mCurTypeInstance;
  16246. if (thisType == NULL)
  16247. return;
  16248. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16249. {
  16250. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16251. {
  16252. PopulateType(checkType, BfPopulateType_Data);
  16253. }, thisType);
  16254. }
  16255. }
  16256. else
  16257. {
  16258. thisType = mCurTypeInstance;
  16259. PopulateType(thisType, BfPopulateType_Declaration);
  16260. }
  16261. }
  16262. int implicitParamCount = 0;
  16263. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16264. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16265. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16266. bool hadDelegateParams = false;
  16267. bool hadParams = false;
  16268. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16269. {
  16270. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16271. BfParameterDef* paramDef = NULL;
  16272. int paramDefIdx = -1;
  16273. if (paramIdx < implicitParamCount)
  16274. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16275. else
  16276. {
  16277. paramDefIdx = paramIdx - implicitParamCount;
  16278. paramDef = methodDef->mParams[paramDefIdx];
  16279. }
  16280. if (hadParams)
  16281. break;
  16282. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16283. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16284. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16285. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16286. {
  16287. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16288. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16289. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16290. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16291. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16292. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16293. }
  16294. BfType* resolvedParamType = NULL;
  16295. if (closureCaptureEntry != NULL)
  16296. resolvedParamType = closureCaptureEntry->mType;
  16297. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16298. {
  16299. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16300. resolvedParamType = mContext->mBfObjectType;
  16301. }
  16302. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16303. {
  16304. if (methodDef->mMethodType != BfMethodType_Mixin)
  16305. {
  16306. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16307. resolvedParamType = mContext->mBfObjectType;
  16308. }
  16309. else
  16310. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16311. }
  16312. BfType* unresolvedParamType = resolvedParamType;
  16313. bool wasGenericParam = false;
  16314. if (resolvedParamType == NULL)
  16315. {
  16316. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16317. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16318. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16319. }
  16320. if (resolvedParamType == NULL)
  16321. {
  16322. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16323. unresolvedParamType = resolvedParamType;
  16324. if (mCurTypeInstance->IsBoxed())
  16325. {
  16326. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16327. // If we failed a lookup here then we better have also failed it in the original type
  16328. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16329. }
  16330. }
  16331. if (!methodInstance->IsSpecializedGenericMethod())
  16332. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16333. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16334. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16335. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16336. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16337. {
  16338. BfMethodState methodState;
  16339. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16340. methodState.mTempKind = BfMethodState::TempKind_Static;
  16341. BfTypedValue defaultValue;
  16342. if (resolvedParamType->IsConstExprValue())
  16343. {
  16344. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16345. BfExprEvaluator exprEvaluator(this);
  16346. exprEvaluator.mExpectingType = constExprType->mType;
  16347. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16348. defaultValue = exprEvaluator.GetResult();
  16349. }
  16350. else
  16351. {
  16352. BfConstResolver constResolver(this);
  16353. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16354. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16355. {
  16356. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16357. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16358. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16359. {
  16360. defaultValue = castedDefaultValue; // Good!
  16361. }
  16362. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16363. {
  16364. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16365. // a conversion operator.
  16366. // This should throw an error
  16367. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16368. AssertErrorState();
  16369. if (!defaultValue.mValue.IsConst())
  16370. defaultValue = BfTypedValue();
  16371. }
  16372. }
  16373. }
  16374. if (!defaultValue)
  16375. {
  16376. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16377. if (!defaultValue.mValue.IsConst())
  16378. defaultValue = BfTypedValue();
  16379. }
  16380. if (defaultValue)
  16381. {
  16382. BF_ASSERT(defaultValue.mValue.IsConst());
  16383. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16384. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16385. CurrentAddToConstHolder(defaultValue.mValue);
  16386. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16387. }
  16388. }
  16389. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16390. {
  16391. bool addParams = true;
  16392. bool isValid = false;
  16393. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16394. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16395. {
  16396. // Span<T>
  16397. isValid = true;
  16398. }
  16399. else if (resolvedParamType->IsArray())
  16400. {
  16401. // Array is the 'normal' params type
  16402. isValid = true;
  16403. }
  16404. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16405. {
  16406. hadDelegateParams = true;
  16407. // This means we copy the params from a delegate
  16408. BfMethodParam methodParam;
  16409. methodParam.mResolvedType = resolvedParamType;
  16410. methodParam.mParamDefIdx = paramDefIdx;
  16411. methodParam.mDelegateParamIdx = 0;
  16412. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16413. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16414. {
  16415. methodParam.mDelegateParamIdx = delegateParamIdx;
  16416. mCurMethodInstance->mParams.Add(methodParam);
  16417. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16418. if (!methodInstance->IsSpecializedGenericMethod())
  16419. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16420. }
  16421. isValid = true;
  16422. addParams = false;
  16423. }
  16424. else if (resolvedParamType->IsGenericParam())
  16425. {
  16426. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16427. if (genericParamInstance->mTypeConstraint != NULL)
  16428. {
  16429. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16430. if (genericParamInstance->mTypeConstraint->IsArray())
  16431. {
  16432. BfMethodParam methodParam;
  16433. methodParam.mResolvedType = resolvedParamType;
  16434. methodParam.mParamDefIdx = paramDefIdx;
  16435. mCurMethodInstance->mParams.Add(methodParam);
  16436. isValid = true;
  16437. }
  16438. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16439. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16440. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16441. {
  16442. mCurMethodInstance->mHadGenericDelegateParams = true;
  16443. isValid = true;
  16444. addParams = false;
  16445. }
  16446. }
  16447. }
  16448. else
  16449. {
  16450. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16451. if ((paramTypeInst != NULL) &&
  16452. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16453. {
  16454. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16455. isValid = true;
  16456. addParams = false;
  16457. }
  16458. }
  16459. if (!isValid)
  16460. {
  16461. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16462. // Failure case, make it an Object[]
  16463. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16464. }
  16465. if (addParams)
  16466. {
  16467. BfMethodParam methodParam;
  16468. methodParam.mResolvedType = resolvedParamType;
  16469. methodParam.mParamDefIdx = paramDefIdx;
  16470. mCurMethodInstance->mParams.push_back(methodParam);
  16471. }
  16472. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16473. {
  16474. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16475. }
  16476. }
  16477. else
  16478. {
  16479. BfMethodParam methodParam;
  16480. methodParam.mResolvedType = resolvedParamType;
  16481. methodParam.mParamDefIdx = paramDefIdx;
  16482. mCurMethodInstance->mParams.Add(methodParam);
  16483. }
  16484. }
  16485. if (hadDelegateParams)
  16486. {
  16487. HashSet<String> usedNames;
  16488. Dictionary<int, int> usedParamDefIdx;
  16489. for (auto methodParam : methodDef->mParams)
  16490. {
  16491. usedNames.Add(methodParam->mName);
  16492. }
  16493. for (auto& methodParam : mCurMethodInstance->mParams)
  16494. {
  16495. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16496. {
  16497. int* refCount = NULL;
  16498. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16499. (*refCount)++;
  16500. }
  16501. }
  16502. for (auto& methodParam : mCurMethodInstance->mParams)
  16503. {
  16504. if (methodParam.mDelegateParamIdx != -1)
  16505. {
  16506. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16507. methodParam.mDelegateParamNameCombine = true;
  16508. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16509. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16510. if (usedNames.Contains(paramName))
  16511. methodParam.mDelegateParamNameCombine = true;
  16512. }
  16513. }
  16514. }
  16515. int argIdx = 0;
  16516. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16517. if (methodInstance->HasStructRet())
  16518. argIdx++;
  16519. if (!methodDef->mIsStatic)
  16520. {
  16521. if (methodInstance->GetParamIsSplat(-1))
  16522. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16523. else if (!methodInstance->GetOwner()->IsValuelessType())
  16524. argIdx++;
  16525. }
  16526. for (auto& methodParam : mCurMethodInstance->mParams)
  16527. {
  16528. if (methodParam.mResolvedType->IsMethodRef())
  16529. {
  16530. methodParam.mIsSplat = true;
  16531. }
  16532. else if (methodParam.mResolvedType->IsComposite())
  16533. {
  16534. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16535. if (methodParam.mResolvedType->IsSplattable())
  16536. {
  16537. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16538. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16539. {
  16540. methodParam.mIsSplat = true;
  16541. argIdx += splatCount;
  16542. continue;
  16543. }
  16544. }
  16545. }
  16546. argIdx++;
  16547. }
  16548. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16549. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16550. {
  16551. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16552. }
  16553. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16554. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16555. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16556. (!methodDef->mIsSkipCall))
  16557. {
  16558. if (methodDeclaration->mEndSemicolon == NULL)
  16559. {
  16560. AssertParseErrorState();
  16561. }
  16562. else
  16563. {
  16564. bool isError = true;
  16565. if (typeInstance->IsTypedPrimitive())
  16566. {
  16567. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16568. {
  16569. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16570. {
  16571. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16572. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16573. {
  16574. isError = false;
  16575. }
  16576. }
  16577. }
  16578. }
  16579. if (isError)
  16580. {
  16581. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16582. MethodToString(methodInstance).c_str()),
  16583. methodDef->GetRefNode());
  16584. }
  16585. }
  16586. }
  16587. if (methodDef->IsEmptyPartial())
  16588. hasExternSpecifier = true;
  16589. if (!methodInstance->IsAutocompleteMethod())
  16590. {
  16591. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16592. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16593. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16594. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16595. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16596. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16597. int paramIdx = 0;
  16598. int defaultParamIdx = 0;
  16599. while (true)
  16600. {
  16601. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16602. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16603. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16604. {
  16605. paramIdx++;
  16606. continue;
  16607. }
  16608. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16609. {
  16610. defaultParamIdx++;
  16611. continue;
  16612. }
  16613. if ((isDone) || (isDefaultDone))
  16614. {
  16615. // 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
  16616. // to cause us to throw an assertion in the declaration here
  16617. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16618. BF_ASSERT((isDone) && (isDefaultDone));
  16619. break;
  16620. }
  16621. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16622. paramIdx++;
  16623. defaultParamIdx++;
  16624. }
  16625. }
  16626. StringT<128> mangledName;
  16627. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16628. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16629. {
  16630. auto paramType = methodInstance->GetParamType(paramIdx);
  16631. if (paramType->IsComposite())
  16632. PopulateType(paramType, BfPopulateType_Data);
  16633. if (!methodInstance->IsParamSkipped(paramIdx))
  16634. {
  16635. if (paramType->IsStruct())
  16636. {
  16637. //
  16638. }
  16639. else
  16640. {
  16641. PopulateType(paramType, BfPopulateType_Declaration);
  16642. }
  16643. }
  16644. }
  16645. // Only process method in default unspecialized mode, not in variations
  16646. if (methodInstance->mIsUnspecializedVariation)
  16647. return;
  16648. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16649. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16650. if (resolvedReturnType->IsValuelessType())
  16651. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16652. if (!mBfIRBuilder->mIgnoreWrites)
  16653. {
  16654. bool isIntrinsic = false;
  16655. if (!methodInstance->mIRFunction)
  16656. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16657. if (isIntrinsic)
  16658. {
  16659. addToWorkList = false;
  16660. }
  16661. }
  16662. auto func = methodInstance->mIRFunction;
  16663. // if (methodInstance->mIsReified)
  16664. // CheckHotMethod(methodInstance, mangledName);
  16665. 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);
  16666. SizedArray<BfIRMDNode, 8> diParams;
  16667. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16668. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16669. {
  16670. //CS0708
  16671. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16672. }
  16673. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16674. {
  16675. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16676. methodDef->mIsVirtual = false;
  16677. }
  16678. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16679. {
  16680. if (methodDef->mIsStatic)
  16681. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16682. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16683. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16684. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16685. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16686. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16687. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16688. }
  16689. if (isTemporaryFunc)
  16690. {
  16691. // This handles temporary methods for autocomplete types
  16692. BF_ASSERT(mIsScratchModule);
  16693. BF_ASSERT(mCompiler->IsAutocomplete());
  16694. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16695. return; // Bail out early for autocomplete pass
  16696. }
  16697. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16698. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16699. // autocompleter. Why did we have this check anyway?
  16700. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16701. {
  16702. AddMethodReference(methodInstance);
  16703. mFuncReferences[methodInstance] = func;
  16704. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16705. }*/
  16706. if (mParentModule != NULL)
  16707. {
  16708. // For extension modules we need to keep track of our own methods so we can know which methods
  16709. // we have defined ourselves and which are from the parent module or other extensions
  16710. if (!func.IsFake())
  16711. mFuncReferences[methodInstance] = func;
  16712. }
  16713. if (addToWorkList)
  16714. {
  16715. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16716. if (wasAwaitingDecl)
  16717. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16718. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16719. {
  16720. if (!wasAwaitingDecl)
  16721. AddMethodToWorkList(methodInstance);
  16722. }
  16723. else
  16724. {
  16725. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16726. methodInstance->mIgnoreBody = true;
  16727. if (typeInstance->IsUnspecializedType())
  16728. {
  16729. // Don't hold on to actual Function for unspecialized types
  16730. methodInstance->mIRFunction = BfIRFunction();
  16731. }
  16732. }
  16733. }
  16734. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16735. (!methodDef->mIsLocalMethod) &&
  16736. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16737. {
  16738. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16739. {
  16740. //TODO:
  16741. //CS0053
  16742. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16743. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16744. methodDef->mReturnTypeRef, true);
  16745. }
  16746. else
  16747. {
  16748. //CS0050
  16749. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16750. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16751. methodDef->mReturnTypeRef, true);
  16752. }
  16753. }
  16754. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16755. {
  16756. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16757. }
  16758. // Don't compare specialized generic methods against normal methods
  16759. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16760. (!methodDef->mIsLocalMethod))
  16761. {
  16762. if (!methodInstance->mIsForeignMethodDef)
  16763. {
  16764. typeDef->PopulateMemberSets();
  16765. BfMethodDef* nextMethod = NULL;
  16766. BfMemberSetEntry* entry = NULL;
  16767. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16768. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16769. while (nextMethod != NULL)
  16770. {
  16771. auto checkMethod = nextMethod;
  16772. nextMethod = nextMethod->mNextWithSameName;
  16773. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16774. {
  16775. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16776. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16777. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16778. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16779. {
  16780. bool canChain = false;
  16781. if ((methodDef->mParams.empty()) &&
  16782. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16783. {
  16784. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16785. canChain = true;
  16786. else if (methodDef->mMethodType == BfMethodType_Normal)
  16787. {
  16788. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16789. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16790. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16791. canChain = true;
  16792. }
  16793. }
  16794. if (canChain)
  16795. {
  16796. bool isBetter;
  16797. bool isWorse;
  16798. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16799. if (isBetter && !isWorse)
  16800. {
  16801. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16802. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16803. }
  16804. else
  16805. {
  16806. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16807. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16808. }
  16809. }
  16810. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16811. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16812. {
  16813. // We're allowed to override an empty-bodied method
  16814. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16815. }
  16816. else
  16817. {
  16818. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16819. continue;
  16820. bool silentlyAllow = false;
  16821. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16822. {
  16823. if (typeInstance->IsInterface())
  16824. {
  16825. if (methodDef->mIsOverride)
  16826. silentlyAllow = true;
  16827. }
  16828. else
  16829. silentlyAllow = true;
  16830. }
  16831. if (!silentlyAllow)
  16832. {
  16833. if (!methodDef->mName.IsEmpty())
  16834. {
  16835. auto refNode = methodDef->GetRefNode();
  16836. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16837. if (bfError != NULL)
  16838. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16839. }
  16840. }
  16841. }
  16842. }
  16843. }
  16844. }
  16845. }
  16846. // Virtual methods give their error while slotting
  16847. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16848. (!methodDef->mIsLocalMethod) &&
  16849. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16850. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16851. {
  16852. bool foundHiddenMethod = false;
  16853. auto baseType = typeInstance->mBaseType;
  16854. while (baseType != NULL)
  16855. {
  16856. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16857. auto baseTypeDef = baseType->mTypeDef;
  16858. baseTypeDef->PopulateMemberSets();
  16859. BfMethodDef* checkMethod = NULL;
  16860. BfMemberSetEntry* entry = NULL;
  16861. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16862. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16863. while (checkMethod != NULL)
  16864. {
  16865. if (checkMethod->mMethodDeclaration == NULL)
  16866. continue;
  16867. if (baseType->mMethodInstanceGroups.size() == 0)
  16868. {
  16869. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16870. break;
  16871. }
  16872. if (checkMethod == methodDef)
  16873. continue;
  16874. if (checkMethod->mName != methodDef->mName)
  16875. continue;
  16876. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16877. if (checkMethodInstance != NULL)
  16878. {
  16879. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16880. (checkMethod->mProtection != BfProtection_Private) &&
  16881. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16882. {
  16883. if (!methodDef->mIsNew)
  16884. {
  16885. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16886. if (refNode != NULL)
  16887. {
  16888. 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?
  16889. if (bfError != NULL)
  16890. bfError->mIsPersistent = true;
  16891. }
  16892. }
  16893. foundHiddenMethod = true;
  16894. break;
  16895. }
  16896. }
  16897. checkMethod = checkMethod->mNextWithSameName;
  16898. }
  16899. if (foundHiddenMethod)
  16900. break;
  16901. baseType = baseType->mBaseType;
  16902. }
  16903. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16904. {
  16905. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16906. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16907. methodDeclaration->mNewSpecifier;
  16908. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16909. }
  16910. }
  16911. }
  16912. mCompiler->mStats.mMethodDeclarations++;
  16913. mCompiler->UpdateCompletion();
  16914. }
  16915. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16916. {
  16917. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16918. auto typeInstance = mCurTypeInstance;
  16919. auto methodDef = methodInstance->mMethodDef;
  16920. int virtualMethodMatchIdx = -1;
  16921. if (typeInstance->mHotTypeData != NULL)
  16922. {
  16923. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16924. {
  16925. BF_ASSERT(mCompiler->IsHotCompile());
  16926. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16927. // may slot this override anyway (?)
  16928. int vTableStart = 0;
  16929. if (typeInstance->mBaseType != NULL)
  16930. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16931. StringT<128> mangledName;
  16932. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16933. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16934. {
  16935. // O(1) checking when virtual methods haven't changed
  16936. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16937. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16938. if (mangledName == entry.mFuncName)
  16939. {
  16940. virtualMethodMatchIdx = vTableStart + checkIdx;
  16941. break;
  16942. }
  16943. }
  16944. if (virtualMethodMatchIdx != -1)
  16945. {
  16946. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16947. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16948. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16949. }
  16950. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16951. }
  16952. }
  16953. if (virtualMethodMatchIdx == -1)
  16954. {
  16955. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16956. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16957. typeInstance->mVirtualMethodTable.push_back(entry);
  16958. }
  16959. }
  16960. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16961. {
  16962. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16963. {
  16964. // When we provide an extension override in the same project a root type override
  16965. isBetter = true;
  16966. isWorse = false;
  16967. }
  16968. else
  16969. {
  16970. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  16971. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  16972. }
  16973. }
  16974. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  16975. {
  16976. BP_ZONE("BfModule::SlotVirtualMethod");
  16977. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  16978. return false;
  16979. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  16980. {
  16981. if (!mCompiler->mOptions.mAllowHotSwapping)
  16982. return;
  16983. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  16984. return;
  16985. if (methodInstance->mHotMethod == NULL)
  16986. CheckHotMethod(methodInstance, "");
  16987. if (methodInstance->mHotMethod == NULL)
  16988. return;
  16989. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  16990. if (declMethodInstance->mHotMethod == NULL)
  16991. CheckHotMethod(declMethodInstance, "");
  16992. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  16993. virtualDecl->mRefCount++;
  16994. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  16995. };
  16996. auto typeInstance = mCurTypeInstance;
  16997. auto typeDef = typeInstance->mTypeDef;
  16998. auto methodDef = methodInstance->mMethodDef;
  16999. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17000. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17001. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17002. BfAstNode* declaringNode = methodDeclaration;
  17003. if (propertyMethodDeclaration != NULL)
  17004. declaringNode = propertyMethodDeclaration->mNameNode;
  17005. BfMethodInstance* methodOverriden = NULL;
  17006. bool usedMethod = false;
  17007. BfTokenNode* virtualToken = NULL;
  17008. if (propertyDeclaration != NULL)
  17009. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17010. else if (methodDeclaration != NULL)
  17011. virtualToken = methodDeclaration->mVirtualSpecifier;
  17012. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17013. {
  17014. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17015. }
  17016. else if (methodDef->mIsVirtual)
  17017. {
  17018. if (mCompiler->IsHotCompile())
  17019. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17020. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17021. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17022. BfTypeInstance* checkBase = typeInstance;
  17023. // If we are in an extension, look in ourselves first
  17024. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17025. checkBase = checkBase->mBaseType;
  17026. if (typeInstance->IsValueType())
  17027. {
  17028. if (typeInstance->mBaseType == NULL)
  17029. return false; // It's actually ValueType
  17030. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17031. if (!methodDef->mIsOverride)
  17032. {
  17033. Fail("Structs cannot have virtual methods", virtualToken, true);
  17034. return false;
  17035. }
  17036. checkBase = mContext->mBfObjectType;
  17037. if (checkBase->mVirtualMethodTableSize == 0)
  17038. PopulateType(checkBase, BfPopulateType_Full);
  17039. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17040. return false; // System circular ref, don't do struct checking on those
  17041. }
  17042. int virtualMethodMatchIdx = -1;
  17043. bool hadHidingError = false;
  17044. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17045. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17046. int bestOverrideMethodIdx = -1;
  17047. int ambiguousOverrideMethodIdx = -1;
  17048. if (checkBase != NULL)
  17049. {
  17050. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17051. auto lookupType = checkBase;
  17052. while (lookupType != NULL)
  17053. {
  17054. lookupType->mTypeDef->PopulateMemberSets();
  17055. BfMethodDef* nextMethodDef = NULL;
  17056. BfMemberSetEntry* entry;
  17057. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17058. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17059. while (nextMethodDef != NULL)
  17060. {
  17061. auto checkMethodDef = nextMethodDef;
  17062. nextMethodDef = nextMethodDef->mNextWithSameName;
  17063. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17064. continue;
  17065. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17066. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17067. continue;
  17068. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17069. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17070. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17071. {
  17072. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17073. continue;
  17074. }
  17075. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17076. if (baseMethodInstance == NULL)
  17077. {
  17078. AssertErrorState();
  17079. continue;
  17080. }
  17081. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17082. {
  17083. if (methodDef->mIsOverride)
  17084. {
  17085. BfMethodInstance* checkMethodInstance;
  17086. if (typeInstance->IsValueType())
  17087. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17088. else
  17089. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17090. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17091. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17092. continue;
  17093. if (bestOverrideMethodInstance != NULL)
  17094. {
  17095. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17096. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17097. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17098. if (isBetter == isWorse)
  17099. {
  17100. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17101. }
  17102. else
  17103. {
  17104. if (isWorse)
  17105. continue;
  17106. ambiguousOverrideMethodInstance = NULL;
  17107. }
  17108. }
  17109. bestOverrideMethodInstance = checkMethodInstance;
  17110. bestOverrideMethodIdx = checkMethodIdx;
  17111. }
  17112. else
  17113. {
  17114. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17115. {
  17116. if (!hadHidingError)
  17117. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17118. hadHidingError = true;
  17119. }
  17120. }
  17121. }
  17122. }
  17123. lookupType = lookupType->mBaseType;
  17124. }
  17125. }
  17126. //TODO:
  17127. if ((checkBase != NULL)
  17128. && (false)
  17129. )
  17130. {
  17131. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17132. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17133. {
  17134. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17135. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17136. {
  17137. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17138. continue;
  17139. }
  17140. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17141. if (baseMethodInstance == NULL)
  17142. {
  17143. AssertErrorState();
  17144. continue;
  17145. }
  17146. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17147. {
  17148. if (methodDef->mIsOverride)
  17149. {
  17150. BfMethodInstance* checkMethodInstance;
  17151. if (typeInstance->IsValueType())
  17152. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17153. else
  17154. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17155. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17156. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17157. continue;
  17158. if (bestOverrideMethodInstance != NULL)
  17159. {
  17160. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17161. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17162. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17163. if (isBetter == isWorse)
  17164. {
  17165. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17166. }
  17167. else
  17168. {
  17169. if (isWorse)
  17170. continue;
  17171. ambiguousOverrideMethodInstance = NULL;
  17172. }
  17173. }
  17174. bestOverrideMethodInstance = checkMethodInstance;
  17175. bestOverrideMethodIdx = checkMethodIdx;
  17176. }
  17177. else
  17178. {
  17179. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17180. {
  17181. if (!hadHidingError)
  17182. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17183. hadHidingError = true;
  17184. }
  17185. }
  17186. }
  17187. }
  17188. }
  17189. if (bestOverrideMethodInstance != NULL)
  17190. {
  17191. if (ambiguousOverrideMethodInstance != NULL)
  17192. {
  17193. bool allow = false;
  17194. // 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.
  17195. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17196. bool canSeeEachOther = false;
  17197. //
  17198. {
  17199. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17200. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17201. canSeeEachOther = true;
  17202. }
  17203. //
  17204. {
  17205. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17206. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17207. canSeeEachOther = true;
  17208. }
  17209. if (!canSeeEachOther)
  17210. {
  17211. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17212. }
  17213. else
  17214. {
  17215. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17216. if (error != NULL)
  17217. {
  17218. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17219. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17220. }
  17221. }
  17222. }
  17223. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17224. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17225. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17226. {
  17227. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17228. {
  17229. BfTypeReference* returnTypeRef;
  17230. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17231. {
  17232. returnTypeRef = propertyDeclaration->mTypeRef;
  17233. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17234. }
  17235. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17236. {
  17237. returnTypeRef = methodDeclaration->mReturnType;
  17238. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17239. }
  17240. else
  17241. {
  17242. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17243. }
  17244. return usedMethod;
  17245. }
  17246. }
  17247. if (methodDef->mIsOverride)
  17248. {
  17249. // We can have multiple matches when a virtual method is used to implement interface methods
  17250. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17251. // vtable entries for this method signature
  17252. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17253. if (!typeInstance->IsValueType())
  17254. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17255. if (typeInstance->IsValueType())
  17256. {
  17257. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17258. }
  17259. else
  17260. {
  17261. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17262. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17263. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17264. {
  17265. methodOverriden = overridenRef;
  17266. BfMethodInstance* setMethodInstance = methodInstance;
  17267. bool doOverride = true;
  17268. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17269. {
  17270. bool isBetter = false;
  17271. bool isWorse = false;
  17272. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17273. if (isBetter == isWorse)
  17274. {
  17275. // We have to resolve later per-project
  17276. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17277. {
  17278. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17279. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17280. }
  17281. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17282. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17283. doOverride = false;
  17284. }
  17285. else
  17286. {
  17287. if ((isBetter) && (ambiguityContext != NULL))
  17288. {
  17289. ambiguityContext->Remove(virtualMethodMatchIdx);
  17290. }
  17291. doOverride = isBetter;
  17292. }
  17293. }
  17294. if (doOverride)
  17295. {
  17296. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17297. _AddVirtualDecl(declMethodInstance);
  17298. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17299. }
  17300. }
  17301. }
  17302. if (methodOverriden != NULL)
  17303. {
  17304. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17305. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17306. {
  17307. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17308. BfAstNode* protectionRefNode = NULL;
  17309. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17310. {
  17311. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17312. if (protectionRefNode == NULL)
  17313. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17314. if (protectionRefNode == NULL)
  17315. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17316. }
  17317. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17318. {
  17319. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17320. if (protectionRefNode == NULL)
  17321. protectionRefNode = methodDeclaration->mNameNode;
  17322. }
  17323. if (protectionRefNode != NULL)
  17324. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17325. }
  17326. }
  17327. }
  17328. }
  17329. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17330. {
  17331. if (methodDef->mIsOverride)
  17332. {
  17333. BfTokenNode* overrideToken = NULL;
  17334. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17335. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17336. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17337. overrideToken = methodDeclaration->mVirtualSpecifier;
  17338. if (overrideToken != NULL)
  17339. {
  17340. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17341. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17342. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17343. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17344. else
  17345. Fail("No suitable method found to override", overrideToken, true);
  17346. }
  17347. return usedMethod;
  17348. }
  17349. UniqueSlotVirtualMethod(methodInstance);
  17350. }
  17351. else
  17352. usedMethod = true;
  17353. if (typeInstance->IsValueType())
  17354. return usedMethod;
  17355. }
  17356. bool foundInterface = false;
  17357. bool hadAnyMatch = false;
  17358. // See if this method matches interfaces
  17359. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17360. {
  17361. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17362. if (ifaceInst->IsIncomplete())
  17363. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17364. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17365. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17366. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17367. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17368. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17369. continue;
  17370. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17371. continue;
  17372. bool hadMatch = false;
  17373. bool hadNameMatch = false;
  17374. BfType* expectedReturnType = NULL;
  17375. bool showedError = false;
  17376. // We go through our VTable looking for NULL entries within the interface sections
  17377. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17378. // because a normal method declared in this type could have matched earlier
  17379. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17380. ifaceInst->mTypeDef->PopulateMemberSets();
  17381. BfMethodDef* checkMethodDef = NULL;
  17382. BfMemberSetEntry* entry;
  17383. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17384. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17385. while (checkMethodDef != NULL)
  17386. {
  17387. int iMethodIdx = checkMethodDef->mIdx;
  17388. int iTableIdx = iMethodIdx + startIdx;
  17389. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17390. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17391. bool storeIFaceMethod = false;
  17392. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17393. continue;
  17394. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17395. auto iMethodInst = iMethodGroup.mDefault;
  17396. if (iMethodInst == NULL)
  17397. {
  17398. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17399. AssertErrorState();
  17400. continue;
  17401. }
  17402. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17403. hadNameMatch = true;
  17404. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17405. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17406. {
  17407. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17408. }
  17409. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17410. {
  17411. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17412. {
  17413. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17414. {
  17415. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17416. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17417. if (error != NULL)
  17418. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17419. showedError = true;
  17420. }
  17421. }
  17422. }
  17423. if (doesMethodSignatureMatch)
  17424. {
  17425. usedMethod = true;
  17426. hadMatch = true;
  17427. hadAnyMatch = true;
  17428. storeIFaceMethod = true;
  17429. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17430. {
  17431. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17432. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17433. {
  17434. // When autocompletion regenerates a single method body but not the whole type then
  17435. // we will see ourselves in the vtable already
  17436. return usedMethod;
  17437. }
  17438. bool isBetter = false;
  17439. bool isWorse = false;
  17440. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17441. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17442. if (isBetter == isWorse)
  17443. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17444. if (isBetter == isWorse)
  17445. {
  17446. if (ambiguityContext != NULL)
  17447. {
  17448. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17449. }
  17450. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17451. storeIFaceMethod = true;
  17452. }
  17453. else
  17454. {
  17455. if ((isBetter) && (ambiguityContext != NULL))
  17456. ambiguityContext->Remove(~iTableIdx);
  17457. storeIFaceMethod = isBetter;
  17458. }
  17459. }
  17460. }
  17461. if (storeIFaceMethod)
  17462. {
  17463. _AddVirtualDecl(iMethodInst);
  17464. *iMethodPtr = methodInstance;
  17465. }
  17466. checkMethodDef = checkMethodDef->mNextWithSameName;
  17467. }
  17468. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17469. {
  17470. if (expectedReturnType != NULL)
  17471. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17472. else if (hadNameMatch)
  17473. Fail("Method parameters don't match interface method", declaringNode, true);
  17474. else
  17475. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17476. }
  17477. }
  17478. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17479. if (methodOverriden != NULL)
  17480. {
  17481. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17482. {
  17483. if (methodEntry.mMethodRef == methodOverriden)
  17484. methodEntry.mMethodRef = methodInstance;
  17485. }
  17486. }
  17487. return usedMethod;
  17488. }
  17489. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17490. {
  17491. auto typeInstance = mCurTypeInstance;
  17492. auto methodDef = methodInstance->mMethodDef;
  17493. if (methodDef->mMethodType == BfMethodType_Ctor)
  17494. return true;
  17495. bool foundOverride = false;
  17496. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17497. {
  17498. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17499. }
  17500. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17501. {
  17502. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17503. }
  17504. BfAstNode* declaringNode = methodDef->GetRefNode();
  17505. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17506. {
  17507. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17508. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17509. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17510. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17511. continue;
  17512. ifaceInst->mTypeDef->PopulateMemberSets();
  17513. BfMethodDef* nextMethod = NULL;
  17514. BfMemberSetEntry* entry = NULL;
  17515. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17516. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17517. while (nextMethod != NULL)
  17518. {
  17519. auto checkMethod = nextMethod;
  17520. nextMethod = nextMethod->mNextWithSameName;
  17521. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17522. if (ifaceMethod == NULL)
  17523. continue;
  17524. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17525. {
  17526. if (methodDef->mIsOverride)
  17527. {
  17528. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17529. {
  17530. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17531. if (error != NULL)
  17532. {
  17533. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17534. }
  17535. }
  17536. foundOverride = true;
  17537. }
  17538. else if (!methodDef->mIsNew)
  17539. {
  17540. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17541. }
  17542. }
  17543. }
  17544. }
  17545. if ((methodDef->mIsOverride) && (!foundOverride))
  17546. {
  17547. // This allows us to declare a method in the base definition or in an extension and then provide
  17548. // an implementation in a more-specific extension
  17549. typeInstance->mTypeDef->PopulateMemberSets();
  17550. BfMethodDef* nextMethod = NULL;
  17551. BfMemberSetEntry* entry = NULL;
  17552. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17553. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17554. while (nextMethod != NULL)
  17555. {
  17556. auto checkMethod = nextMethod;
  17557. nextMethod = nextMethod->mNextWithSameName;
  17558. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17559. if (ifaceMethod == NULL)
  17560. continue;
  17561. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17562. continue;
  17563. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17564. {
  17565. foundOverride = true;
  17566. }
  17567. }
  17568. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17569. // {
  17570. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17571. // if (ifaceMethod == NULL)
  17572. // continue;
  17573. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17574. // continue;
  17575. //
  17576. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17577. // {
  17578. // foundOverride = true;
  17579. // }
  17580. // }
  17581. }
  17582. if (methodDef->mIsOverride)
  17583. {
  17584. if (!foundOverride)
  17585. {
  17586. BfTokenNode* overrideToken = NULL;
  17587. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17588. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17589. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17590. overrideToken = methodDeclaration->mVirtualSpecifier;
  17591. if (overrideToken != NULL)
  17592. {
  17593. Fail("No suitable method found to override", overrideToken, true);
  17594. }
  17595. else
  17596. {
  17597. // Possible cause - DTOR with params
  17598. AssertErrorState();
  17599. }
  17600. }
  17601. return true;
  17602. }
  17603. // Generic methods can't be called virtually
  17604. if (methodInstance->GetNumGenericParams() != 0)
  17605. return true;
  17606. // Only public methods can be called virtually
  17607. if (methodDef->mProtection != BfProtection_Public)
  17608. return true;
  17609. UniqueSlotVirtualMethod(methodInstance);
  17610. return true;
  17611. }
  17612. void BfModule::DbgFinish()
  17613. {
  17614. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17615. return;
  17616. if (mAwaitingInitFinish)
  17617. FinishInit();
  17618. if (mHasForceLinkMarker)
  17619. return;
  17620. String markerName;
  17621. BfIRValue linkMarker;
  17622. if (mBfIRBuilder->DbgHasInfo())
  17623. {
  17624. bool needForceLinking = false;
  17625. for (auto& ownedType : mOwnedTypeInstances)
  17626. {
  17627. bool hasConfirmedReference = false;
  17628. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17629. {
  17630. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17631. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17632. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17633. {
  17634. hasConfirmedReference = true;
  17635. }
  17636. }
  17637. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17638. needForceLinking = true;
  17639. }
  17640. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17641. {
  17642. BfMethodState methodState;
  17643. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17644. methodState.mTempKind = BfMethodState::TempKind_Static;
  17645. mHasForceLinkMarker = true;
  17646. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17647. SizedArray<BfIRType, 0> paramTypes;
  17648. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17649. String linkName = "FORCELINKMOD_" + mModuleName;
  17650. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17651. mBfIRBuilder->SetActiveFunction(func);
  17652. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17653. mBfIRBuilder->SetInsertPoint(entryBlock);
  17654. auto firstType = mOwnedTypeInstances[0];
  17655. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17656. SizedArray<BfIRMDNode, 1> diParamTypes;
  17657. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17658. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17659. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17660. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17661. methodState.mCurScope->mDIScope = diScope;
  17662. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17663. SizedArray<BfIRValue, 8> args;
  17664. BfExprEvaluator exprEvaluator(this);
  17665. for (auto& ownedType : mOwnedTypeInstances)
  17666. {
  17667. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17668. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17669. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17670. }
  17671. mBfIRBuilder->CreateRetVoid();
  17672. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17673. }
  17674. }
  17675. }
  17676. bool BfModule::Finish()
  17677. {
  17678. BP_ZONE("BfModule::Finish");
  17679. BfLogSysM("BfModule finish: %p\n", this);
  17680. if (mHadBuildError)
  17681. {
  17682. // Don't AssertErrorState here, this current pass may not have failed but
  17683. // the module was still queued in mFinishedModuleWorkList
  17684. ClearModule();
  17685. return true;
  17686. }
  17687. if (mUsedSlotCount != -1)
  17688. {
  17689. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17690. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17691. }
  17692. BF_ASSERT(mAddedToCount);
  17693. mAddedToCount = false;
  17694. mAwaitingFinish = false;
  17695. mCompiler->mStats.mModulesFinished++;
  17696. if (HasCompiledOutput())
  17697. {
  17698. DbgFinish();
  17699. if (mAwaitingInitFinish)
  17700. FinishInit();
  17701. for (auto ownedTypeInst : mOwnedTypeInstances)
  17702. {
  17703. // Generate dbg info and add global variables if we haven't already
  17704. mBfIRBuilder->PopulateType(ownedTypeInst);
  17705. }
  17706. if (mBfIRBuilder->DbgHasInfo())
  17707. {
  17708. mBfIRBuilder->DbgFinalize();
  17709. }
  17710. String objOutputPath;
  17711. String irOutputPath;
  17712. mIsModuleMutable = false;
  17713. //mOutFileNames.Clear();
  17714. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17715. bool writeModule = mBfIRBuilder->HasExports();
  17716. String outputPath;
  17717. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17718. auto& compilerOpts = mCompiler->mOptions;
  17719. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17720. auto moduleOptions = GetModuleOptions();
  17721. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17722. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17723. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17724. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17725. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  17726. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17727. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17728. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17729. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17730. bool allowWriteToLib = true;
  17731. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17732. {
  17733. codeGenOptions.mWriteToLib = true;
  17734. mWroteToLib = true;
  17735. }
  17736. else
  17737. {
  17738. mWroteToLib = false;
  17739. }
  17740. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17741. {
  17742. outputPath = mModuleName;
  17743. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17744. BfModuleFileName moduleFileName;
  17745. if (mParentModule != NULL)
  17746. {
  17747. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17748. {
  17749. if (checkPair.mValue == this)
  17750. moduleFileName.mProjects = checkPair.mKey;
  17751. }
  17752. }
  17753. moduleFileName.mProjects.Add(mProject);
  17754. if (fileIdx > 0)
  17755. outputPath += StrFormat("@%d", fileIdx + 1);
  17756. if (mCompiler->mOptions.mWriteIR)
  17757. irOutputPath = outputPath + ".ll";
  17758. if (mCompiler->mOptions.mGenerateObj)
  17759. {
  17760. objOutputPath = outputPath + BF_OBJ_EXT;
  17761. moduleFileName.mFileName = objOutputPath;
  17762. }
  17763. else if (mCompiler->mOptions.mWriteIR)
  17764. {
  17765. moduleFileName.mFileName = irOutputPath;
  17766. }
  17767. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  17768. {
  17769. BF_FATAL("Neither obj nor IR specified");
  17770. }
  17771. moduleFileName.mModuleWritten = writeModule;
  17772. moduleFileName.mWroteToLib = mWroteToLib;
  17773. if (!mOutFileNames.Contains(moduleFileName))
  17774. mOutFileNames.Add(moduleFileName);
  17775. }
  17776. if (mCompiler->IsHotCompile())
  17777. {
  17778. codeGenOptions.mIsHotCompile = true;
  17779. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17780. // is required for rebuilding vdata after we hot create a vdata
  17781. //if (mWroteToLib)
  17782. {
  17783. if (mParentModule != NULL)
  17784. mParentModule->mHadHotObjectWrites = true;
  17785. mHadHotObjectWrites = true;
  17786. }
  17787. }
  17788. //TODO: Testing VDATA
  17789. /*if (mModuleName == "vdata")
  17790. {
  17791. codeGenOptions.mOptLevel = 4;
  17792. }*/
  17793. codeGenOptions.GenerateHash();
  17794. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17795. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17796. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17797. mLastModuleWrittenRevision = mCompiler->mRevision;
  17798. }
  17799. else
  17800. {
  17801. for (auto type : mOwnedTypeInstances)
  17802. {
  17803. BF_ASSERT(!type->IsIncomplete());
  17804. }
  17805. }
  17806. for (auto& specModulePair : mSpecializedMethodModules)
  17807. {
  17808. auto specModule = specModulePair.mValue;
  17809. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17810. {
  17811. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17812. }
  17813. }
  17814. CleanupFileInstances();
  17815. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17816. return true;
  17817. }
  17818. void BfModule::ReportMemory(MemReporter* memReporter)
  17819. {
  17820. memReporter->Add(sizeof(BfModule));
  17821. if (mBfIRBuilder != NULL)
  17822. {
  17823. memReporter->BeginSection("IRBuilder_ConstData");
  17824. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17825. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17826. memReporter->EndSection();
  17827. memReporter->BeginSection("IRBuilder_BFIR");
  17828. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17829. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17830. memReporter->EndSection();
  17831. memReporter->Add(sizeof(BfIRBuilder));
  17832. }
  17833. memReporter->BeginSection("FileInstanceMap");
  17834. memReporter->AddMap(mFileInstanceMap);
  17835. memReporter->AddMap(mNamedFileInstanceMap);
  17836. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17837. memReporter->EndSection();
  17838. memReporter->AddVec(mOwnedTypeInstances, false);
  17839. memReporter->AddVec(mSpecializedMethodModules, false);
  17840. memReporter->AddVec(mOutFileNames, false);
  17841. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17842. memReporter->AddMap(mInterfaceSlotRefs, false);
  17843. memReporter->AddMap(mStaticFieldRefs, false);
  17844. memReporter->AddMap(mClassVDataRefs, false);
  17845. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17846. memReporter->AddMap(mTypeDataRefs, false);
  17847. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17848. memReporter->AddMap(mDeferredMethodCallData, false);
  17849. memReporter->AddHashSet(mDeferredMethodIds, false);
  17850. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17851. }
  17852. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17853. // be transient through the next compile
  17854. void BfModule::ClearModuleData()
  17855. {
  17856. BfLogSysM("ClearModuleData %p\n", this);
  17857. if (mAddedToCount)
  17858. {
  17859. mCompiler->mStats.mModulesFinished++;
  17860. mAddedToCount = false;
  17861. }
  17862. mDICompileUnit = BfIRMDNode();
  17863. mIsModuleMutable = false;
  17864. mIncompleteMethodCount = 0;
  17865. mHasGenericMethods = false;
  17866. // We don't want to clear these because we want it to persist through module extensions-
  17867. // otherwise we may think an extension succeeds even though the base module failed
  17868. //mHadBuildError = false;
  17869. //mHadBuildWarning = false;
  17870. mClassVDataRefs.Clear();
  17871. mClassVDataExtRefs.Clear();
  17872. for (auto& kv : mTypeDataRefs)
  17873. kv.mValue = BfIRValue();
  17874. mStringCharPtrPool.Clear();
  17875. mStringObjectPool.Clear();
  17876. mStaticFieldRefs.Clear();
  17877. BF_ASSERT(!mIgnoreErrors);
  17878. for (auto prevIRBuilder : mPrevIRBuilders)
  17879. delete prevIRBuilder;
  17880. mPrevIRBuilders.Clear();
  17881. for (auto& specPair : mSpecializedMethodModules)
  17882. {
  17883. auto specModule = specPair.mValue;
  17884. specModule->ClearModuleData();
  17885. }
  17886. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17887. mBuiltInFuncs[i] = BfIRFunction();
  17888. if (mNextAltModule != NULL)
  17889. mNextAltModule->ClearModuleData();
  17890. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17891. delete mBfIRBuilder;
  17892. mBfIRBuilder = NULL;
  17893. mWantsIRIgnoreWrites = false;
  17894. }
  17895. void BfModule::DisownMethods()
  17896. {
  17897. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17898. mBuiltInFuncs[i] = BfIRFunction();
  17899. BfModule* methodModule = this;
  17900. if (mParentModule != NULL)
  17901. methodModule = mParentModule;
  17902. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17903. {
  17904. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17905. {
  17906. if (methodGroup.mDefault != NULL)
  17907. {
  17908. if (methodGroup.mDefault->mIRFunction)
  17909. {
  17910. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  17911. if (methodGroup.mDefault->mDeclModule == this)
  17912. {
  17913. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17914. }
  17915. }
  17916. }
  17917. if (methodGroup.mMethodSpecializationMap != NULL)
  17918. {
  17919. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17920. {
  17921. auto methodInstance = mapPair.mValue;
  17922. if (methodInstance->mDeclModule == this)
  17923. {
  17924. methodInstance->mIRFunction = BfIRFunction();
  17925. }
  17926. }
  17927. }
  17928. }
  17929. }
  17930. }
  17931. void BfModule::ClearModule()
  17932. {
  17933. ClearModuleData();
  17934. DisownMethods();
  17935. for (auto& specPair : mSpecializedMethodModules)
  17936. {
  17937. auto specModule = specPair.mValue;
  17938. specModule->ClearModule();
  17939. }
  17940. if (mNextAltModule != NULL)
  17941. mNextAltModule->ClearModule();
  17942. }