BfStmtEvaluator.cpp 259 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097
  1. #include "BfCompiler.h"
  2. #include "BfSystem.h"
  3. #include "BfParser.h"
  4. #include "BfCodeGen.h"
  5. #include "BfExprEvaluator.h"
  6. #include <fcntl.h>
  7. #include "BfConstResolver.h"
  8. #include "BfMangler.h"
  9. #include "BeefySysLib/util/PerfTimer.h"
  10. #include "BeefySysLib/util/BeefPerf.h"
  11. #include "BeefySysLib/util/StackHelper.h"
  12. #include "BfSourceClassifier.h"
  13. #include "BfAutoComplete.h"
  14. #include "BfDemangler.h"
  15. #include "BfResolvePass.h"
  16. #include "BfFixits.h"
  17. #include "BfIRCodeGen.h"
  18. #include "BfDefBuilder.h"
  19. #pragma warning(push)
  20. #pragma warning(disable:4141)
  21. #pragma warning(disable:4146)
  22. #pragma warning(disable:4291)
  23. #pragma warning(disable:4244)
  24. #pragma warning(disable:4267)
  25. #pragma warning(disable:4624)
  26. #pragma warning(disable:4800)
  27. #pragma warning(disable:4996)
  28. #include "llvm/IR/DIBuilder.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/GlobalValue.h"
  32. #include "llvm/IR/GlobalVariable.h"
  33. #include "llvm/ADT/ArrayRef.h"
  34. #include "llvm/IR/InlineAsm.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "BeefySysLib/util/AllocDebug.h"
  37. #pragma warning(pop)
  38. USING_NS_BF;
  39. bool BfModule::AddDeferredCallEntry(BfDeferredCallEntry* deferredCallEntry, BfScopeData* scopeData)
  40. {
  41. if ((((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)) ||
  42. (mBfIRBuilder->mIgnoreWrites)) && (deferredCallEntry->mDeferredBlock == NULL))
  43. {
  44. // For resolve entries, we only keep deferred blocks because we need to process them later so we can
  45. // resolve inside of them. This is also required for lambda bind scan-pass
  46. delete deferredCallEntry;
  47. return false;
  48. }
  49. if (mBfIRBuilder->mIgnoreWrites)
  50. {
  51. deferredCallEntry->mIgnored = true;
  52. scopeData->mDeferredCallEntries.PushBack(deferredCallEntry);
  53. return true;
  54. }
  55. // We don't need to do a "clear handlers" if we're just adding another dyn to an existing dyn list
  56. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  57. if (mCurMethodState->mPendingNullConditional != NULL)
  58. isDyn = true;
  59. deferredCallEntry->mOrigScopeArgs = deferredCallEntry->mScopeArgs;
  60. if (!isDyn)
  61. {
  62. mCurMethodState->mCurScope->ClearHandlers(scopeData);
  63. if (!mBfIRBuilder->mIgnoreWrites)
  64. {
  65. if ((IsTargetingBeefBackend()) && (deferredCallEntry->mModuleMethodInstance.mMethodInstance != NULL) &&
  66. (!mContext->IsSentinelMethod(deferredCallEntry->mModuleMethodInstance.mMethodInstance)))
  67. {
  68. SizedArray<BfIRType, 8> origParamTypes;
  69. BfIRType origReturnType;
  70. deferredCallEntry->mModuleMethodInstance.mMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  71. int sretIdx = deferredCallEntry->mModuleMethodInstance.mMethodInstance->GetStructRetIdx();
  72. BF_ASSERT(origParamTypes.size() == deferredCallEntry->mScopeArgs.size() + ((sretIdx != -1) ? 1 : 0));
  73. int argIdx = 0;
  74. int paramIdx = 0;
  75. for (int argIdx = 0; argIdx < (int)deferredCallEntry->mScopeArgs.size(); argIdx++, paramIdx++)
  76. {
  77. if (argIdx == sretIdx)
  78. paramIdx++;
  79. auto scopeArg = deferredCallEntry->mScopeArgs[argIdx];
  80. if ((scopeArg.IsConst()) || (scopeArg.IsFake()))
  81. continue;
  82. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  83. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  84. auto allocaInst = mBfIRBuilder->CreateAlloca(origParamTypes[paramIdx]);
  85. mBfIRBuilder->ClearDebugLocation_Last();
  86. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  87. if (WantsLifetimes())
  88. {
  89. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  90. mBfIRBuilder->ClearDebugLocation_Last();
  91. }
  92. mBfIRBuilder->CreateStore(scopeArg, allocaInst);
  93. mBfIRBuilder->ClearDebugLocation_Last();
  94. deferredCallEntry->mScopeArgs[argIdx] = allocaInst;
  95. if (WantsLifetimes())
  96. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  97. }
  98. deferredCallEntry->mArgsNeedLoad = true;
  99. }
  100. }
  101. scopeData->mDeferredCallEntries.PushFront(deferredCallEntry);
  102. return true;
  103. }
  104. bool isLooped = mCurMethodState->mCurScope->IsLooped(scopeData);
  105. BfDeferredCallEntry* listEntry = NULL;
  106. if (!scopeData->mDeferredCallEntries.IsEmpty())
  107. {
  108. listEntry = scopeData->mDeferredCallEntries.mHead;
  109. if (!listEntry->IsDynList())
  110. listEntry = NULL;
  111. }
  112. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  113. AddDependency(deferredCallEntryType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  114. mBfIRBuilder->PopulateType(deferredCallEntryType);
  115. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  116. UpdateSrcPos(mCurMethodInstance->mMethodDef->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  117. if (listEntry == NULL)
  118. {
  119. listEntry = new BfDeferredCallEntry();
  120. if (!mBfIRBuilder->mIgnoreWrites)
  121. {
  122. listEntry->mDynCallTail = CreateAlloca(deferredCallEntryTypePtr, false, "deferredCallTail");
  123. if (WantsLifetimes())
  124. scopeData->mDeferredLifetimeEnds.push_back(listEntry->mDynCallTail);
  125. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  126. mBfIRBuilder->SaveDebugLocation();
  127. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  128. auto scopeHead = &mCurMethodState->mHeadScope;
  129. if (scopeHead->mDIScope)
  130. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, scopeHead->mDIScope, BfIRMDNode());
  131. if (WantsLifetimes())
  132. mBfIRBuilder->CreateLifetimeStart(listEntry->mDynCallTail);
  133. auto storeInst = mBfIRBuilder->CreateStore(GetDefaultValue(deferredCallEntryTypePtr), listEntry->mDynCallTail);
  134. mBfIRBuilder->ClearDebugLocation(storeInst);
  135. if (WantsDebugInfo())
  136. {
  137. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  138. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  139. String varName = StrFormat("__deferred%d", mCurMethodState->mDeferredLoopListCount);
  140. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  141. if (scopeHead->mDIScope)
  142. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, scopeHead->mDIScope, BfIRMDNode());
  143. mBfIRBuilder->CreateStatementStart();
  144. //TODO: Make this work for LLVM - we need a proper debug location
  145. //if (IsTargetingBeefBackend())
  146. {
  147. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(scopeHead->mDIScope, varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(deferredCallEntryTypePtr));
  148. mBfIRBuilder->DbgInsertDeclare(listEntry->mDynCallTail, diVariable);
  149. }
  150. mCurMethodState->mDeferredLoopListCount++;
  151. }
  152. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  153. mBfIRBuilder->RestoreDebugLocation();
  154. }
  155. mCurMethodState->mCurScope->ClearHandlers(scopeData);
  156. scopeData->mDeferredCallEntries.PushFront(listEntry);
  157. }
  158. BfIRValue deferredAlloca;
  159. SizedArray<BfType*, 4> types;
  160. SizedArray<String, 8> memberNames;
  161. int instAlign = 1;
  162. int dataPos = 0;
  163. int instSize = 0;
  164. Array<int> memberPositions;
  165. String typeName;
  166. BfDeferredMethodCallData* deferredMethodCallData = NULL;
  167. if (deferredCallEntry->mDeferredBlock != NULL)
  168. {
  169. HashContext hashCtx;
  170. hashCtx.Mixin(deferredCallEntry->mDeferredBlock->GetSrcStart());
  171. auto parserData = deferredCallEntry->mDeferredBlock->GetParserData();
  172. if (parserData != NULL)
  173. hashCtx.MixinStr(parserData->mFileName);
  174. int64 blockId = BfDeferredMethodCallData::GenerateMethodId(this, hashCtx.Finish64());
  175. deferredCallEntry->mBlockId = blockId;
  176. auto deferType = deferredCallEntryType;
  177. BfIRType deferIRType;
  178. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  179. types.push_back(int64Type);
  180. memberNames.push_back("__methodId");
  181. types.push_back(deferredCallEntryTypePtr);
  182. memberNames.push_back("__next");
  183. for (auto& capture : deferredCallEntry->mCaptures)
  184. {
  185. BfType* type = capture.mValue.mType;
  186. types.push_back(type);
  187. memberNames.push_back(capture.mName);
  188. }
  189. SizedArray<BfIRType, 4> llvmTypes;
  190. SizedArray<BfIRMDNode, 8> diFieldTypes;
  191. typeName = StrFormat("_BF_DeferredData_%s", BfTypeUtils::HashEncode64(blockId).c_str());
  192. auto valueType = ResolveTypeDef(mCompiler->mValueTypeTypeDef);
  193. llvmTypes.push_back(mBfIRBuilder->MapType(valueType));
  194. //int dataPos = 0;
  195. for (int i = 0; i < (int)memberNames.size(); i++)
  196. {
  197. auto type = types[i];
  198. auto memberName = memberNames[i];
  199. if (!type->IsValuelessType())
  200. {
  201. llvmTypes.push_back(mBfIRBuilder->MapType(type));
  202. instAlign = BF_MAX(instAlign, (int)type->mAlign);
  203. int alignSize = (int)type->mAlign;
  204. int dataSize = type->mSize;
  205. if (alignSize > 1)
  206. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  207. memberPositions.push_back(dataPos);
  208. dataPos += type->mSize;
  209. }
  210. }
  211. instSize = dataPos;
  212. deferIRType = mBfIRBuilder->CreateStructType(typeName);
  213. mBfIRBuilder->StructSetBody(deferIRType, llvmTypes, instSize, instAlign, false);
  214. auto prevInsertPoint = mBfIRBuilder->GetInsertBlock();
  215. if (!isLooped)
  216. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  217. deferredAlloca = mBfIRBuilder->CreateAlloca(deferIRType);
  218. mBfIRBuilder->SetAllocaAlignment(deferredAlloca, instAlign);
  219. mBfIRBuilder->SetAllocaNoChkStkHint(deferredAlloca);
  220. if (!isLooped)
  221. mBfIRBuilder->SetInsertPoint(prevInsertPoint);
  222. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 2); // mNext
  223. auto prevVal = mBfIRBuilder->CreateLoad(listEntry->mDynCallTail);
  224. mBfIRBuilder->CreateStore(prevVal, gepInstance);
  225. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 1); // mMethodId
  226. mBfIRBuilder->CreateStore(GetConstValue64(blockId), gepInstance);
  227. if (!deferredCallEntry->mCaptures.empty())
  228. {
  229. int dataIdx = 3;
  230. for (int captureIdx = 0; captureIdx < (int)deferredCallEntry->mCaptures.size(); captureIdx++)
  231. {
  232. auto& capture = deferredCallEntry->mCaptures[captureIdx];
  233. if (!capture.mValue.mType->IsValuelessType())
  234. {
  235. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, dataIdx);
  236. mBfIRBuilder->CreateStore(capture.mValue.mValue, gepInstance);
  237. dataIdx++;
  238. }
  239. }
  240. }
  241. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateBitCast(deferredAlloca, mBfIRBuilder->MapType(deferredCallEntryTypePtr)), listEntry->mDynCallTail);
  242. deferredCallEntry->mDeferredAlloca = deferredAlloca;
  243. listEntry->mDynList.PushFront(deferredCallEntry);
  244. }
  245. else
  246. {
  247. auto& llvmArgs = deferredCallEntry->mScopeArgs;
  248. auto moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  249. auto methodInstance = moduleMethodInstance.mMethodInstance;
  250. auto methodDef = methodInstance->mMethodDef;
  251. auto owningType = methodInstance->mMethodInstanceGroup->mOwner;
  252. auto voidType = GetPrimitiveType(BfTypeCode_None);
  253. auto voidPtrType = CreatePointerType(voidType);
  254. BfDeferredMethodCallData** deferredMethodCallDataPtr = NULL;
  255. if (mDeferredMethodCallData.TryGetValue(methodInstance, &deferredMethodCallDataPtr))
  256. {
  257. deferredMethodCallData = *deferredMethodCallDataPtr;
  258. }
  259. else
  260. {
  261. deferredMethodCallData = new BfDeferredMethodCallData();
  262. mDeferredMethodCallData[methodInstance] = deferredMethodCallData;
  263. deferredMethodCallData->mMethodId = BfDeferredMethodCallData::GenerateMethodId(this, methodInstance->mIdHash);
  264. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  265. auto methodDef = moduleMethodInstance.mMethodInstance->mMethodDef;
  266. auto thisType = moduleMethodInstance.mMethodInstance->mMethodInstanceGroup->mOwner;
  267. types.push_back(int64Type);
  268. memberNames.push_back("__methodId");
  269. types.push_back(deferredCallEntryTypePtr);
  270. memberNames.push_back("__next");
  271. if (!methodDef->mIsStatic)
  272. {
  273. types.push_back(thisType);
  274. memberNames.push_back("__this");
  275. }
  276. for (int paramIdx = 0; paramIdx < (int)methodInstance->GetParamCount(); paramIdx++)
  277. {
  278. if (methodInstance->IsParamSkipped(paramIdx))
  279. paramIdx++;
  280. types.push_back(methodInstance->GetParamType(paramIdx));
  281. memberNames.push_back(methodInstance->GetParamName(paramIdx));
  282. }
  283. SizedArray<BfIRType, 4> llvmTypes;
  284. //String typeName;
  285. typeName += StrFormat("_BF_DeferredData_%s", BfTypeUtils::HashEncode64(deferredMethodCallData->mMethodId).c_str());
  286. BfLogSysM("Building type: %s from methodInstance:%p\n", typeName.c_str(), methodInstance);
  287. //Array<int> memberPositions;
  288. //int instAlign = 1;
  289. //int dataPos = 0;
  290. BF_ASSERT(types.size() == memberNames.size());
  291. for (int i = 0; i < (int)types.size(); i++)
  292. {
  293. auto type = types[i];
  294. auto memberName = memberNames[i];
  295. if (!type->IsValuelessType())
  296. {
  297. llvmTypes.push_back(mBfIRBuilder->MapType(type));
  298. instAlign = BF_MAX(instAlign, (int)type->mAlign);
  299. int alignSize = (int)type->mAlign;
  300. int dataSize = type->mSize;
  301. if (alignSize > 1)
  302. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  303. memberPositions.push_back(dataPos);
  304. dataPos += type->mSize;
  305. }
  306. }
  307. instSize = dataPos;
  308. deferredMethodCallData->mAlign = instAlign;
  309. deferredMethodCallData->mSize = instSize;
  310. deferredMethodCallData->mDeferType = mBfIRBuilder->CreateStructType(typeName);
  311. mBfIRBuilder->StructSetBody(deferredMethodCallData->mDeferType, llvmTypes, instSize, instAlign, false);
  312. deferredMethodCallData->mDeferTypePtr = mBfIRBuilder->GetPointerTo(deferredMethodCallData->mDeferType);
  313. }
  314. auto deferType = deferredMethodCallData->mDeferType;
  315. auto prevInsertPoint = mBfIRBuilder->GetInsertBlock();
  316. if (!isLooped)
  317. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  318. deferredAlloca = mBfIRBuilder->CreateAlloca(BfIRType(deferredMethodCallData->mDeferType));
  319. mBfIRBuilder->ClearDebugLocation(deferredAlloca);
  320. mBfIRBuilder->SetAllocaAlignment(deferredAlloca, deferredMethodCallData->mAlign);
  321. mBfIRBuilder->SetAllocaNoChkStkHint(deferredAlloca);
  322. if (!isLooped)
  323. mBfIRBuilder->SetInsertPoint(prevInsertPoint);
  324. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 1);
  325. auto prevVal = mBfIRBuilder->CreateLoad(listEntry->mDynCallTail);
  326. mBfIRBuilder->CreateStore(prevVal, gepInstance);
  327. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 0);
  328. mBfIRBuilder->CreateStore(GetConstValue64(deferredMethodCallData->mMethodId), gepInstance);
  329. int dataIdx = 2;
  330. int argIdx = 0;
  331. if ((!methodDef->mIsStatic) && (!owningType->IsValuelessType()))
  332. {
  333. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, 2);
  334. if (owningType->IsValueType())
  335. {
  336. if ((!methodDef->mIsMutating) && (owningType->IsSplattable()))
  337. {
  338. BfTypedValue splatVal(llvmArgs[0], owningType, BfTypedValueKind_ThisSplatHead);
  339. BfTypedValue aggVal = AggregateSplat(splatVal, &llvmArgs[0]);
  340. aggVal = LoadValue(aggVal);
  341. mBfIRBuilder->CreateStore(aggVal.mValue, gepInstance);
  342. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, owningType);
  343. }
  344. else
  345. {
  346. auto thisArg = mBfIRBuilder->CreateLoad(llvmArgs[0]);
  347. mBfIRBuilder->CreateStore(thisArg, gepInstance);
  348. argIdx++;
  349. }
  350. }
  351. else
  352. {
  353. mBfIRBuilder->CreateStore(llvmArgs[0], gepInstance);
  354. argIdx++;
  355. }
  356. dataIdx++;
  357. }
  358. for (int paramIdx = 0; paramIdx < (int)methodInstance->GetParamCount(); paramIdx++, dataIdx++)
  359. {
  360. if (methodInstance->IsParamSkipped(paramIdx))
  361. paramIdx++;
  362. auto paramType = methodInstance->GetParamType(paramIdx);
  363. bool paramIsSplat = methodInstance->GetParamIsSplat(paramIdx);
  364. gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredAlloca, 0, dataIdx/*, methodDef->mParams[paramIdx]->mName*/);
  365. if (paramType->IsStruct())
  366. {
  367. if (paramIsSplat)
  368. {
  369. BfTypedValue splatVal(llvmArgs[argIdx], paramType, BfTypedValueKind_SplatHead);
  370. BfTypedValue aggVal = AggregateSplat(splatVal, &llvmArgs[argIdx]);
  371. aggVal = LoadValue(aggVal);
  372. mBfIRBuilder->CreateStore(aggVal.mValue, gepInstance);
  373. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramType);
  374. }
  375. else
  376. {
  377. auto val = mBfIRBuilder->CreateLoad(llvmArgs[argIdx]);
  378. mBfIRBuilder->CreateStore(val, gepInstance);
  379. argIdx++;
  380. }
  381. }
  382. else
  383. {
  384. mBfIRBuilder->CreateStore(llvmArgs[argIdx], gepInstance);
  385. argIdx++;
  386. }
  387. }
  388. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateBitCast(deferredAlloca, mBfIRBuilder->MapType(deferredCallEntryTypePtr)), listEntry->mDynCallTail);
  389. deferredCallEntry->mDeferredAlloca = deferredAlloca;
  390. listEntry->mDynList.PushFront(deferredCallEntry);
  391. }
  392. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) && (mCompiler->mOptions.mEmitDebugInfo) && (mCurMethodState->mCurScope->mDIScope))
  393. {
  394. auto int64Type = GetPrimitiveType(BfTypeCode_Int64);
  395. auto moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  396. auto methodInstance = moduleMethodInstance.mMethodInstance;
  397. BfIRMDNode deferDIType;
  398. if ((deferredMethodCallData != NULL) && (deferredMethodCallData->mDeferDIType))
  399. {
  400. deferDIType = deferredMethodCallData->mDeferDIType;
  401. }
  402. else
  403. {
  404. BfIRMDNode diForwardDecl;
  405. SizedArray<BfIRMDNode, 8> diFieldTypes;
  406. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  407. {
  408. String dbgTypeName;
  409. if (mCompiler->mOptions.IsCodeView())
  410. dbgTypeName += "_bf::";
  411. dbgTypeName += typeName;
  412. diForwardDecl = mBfIRBuilder->DbgCreateReplaceableCompositeType(llvm::dwarf::DW_TAG_structure_type, dbgTypeName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mFileInstance->mDIFile,
  413. mCurFilePosition.mCurLine, instSize * 8, instAlign * 8);
  414. if (methodInstance != NULL)
  415. {
  416. // We make a fake member to get inserted into the DbgModule data so we can show what method this deferred call goes to
  417. StringT<128> mangledName;
  418. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  419. auto memberType = mBfIRBuilder->DbgCreateMemberType(diForwardDecl, mangledName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine,
  420. 0, 0, -1, 0, mBfIRBuilder->DbgGetType(int64Type));
  421. diFieldTypes.push_back(memberType);
  422. }
  423. }
  424. for (int i = 0; i < (int)types.size(); i++)
  425. {
  426. auto type = types[i];
  427. auto memberName = memberNames[i];
  428. if ((mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  429. {
  430. int memberFlags = 0;
  431. auto memberType = mBfIRBuilder->DbgCreateMemberType(diForwardDecl, memberName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine,
  432. type->mSize * 8, type->mAlign * 8, memberPositions[i] * 8, memberFlags, mBfIRBuilder->DbgGetType(type));
  433. diFieldTypes.push_back(memberType);
  434. }
  435. }
  436. int diFlags = 0;
  437. mBfIRBuilder->DbgMakePermanent(diForwardDecl, BfIRMDNode(), diFieldTypes);
  438. deferDIType = mBfIRBuilder->DbgCreatePointerType(diForwardDecl);
  439. if (deferredMethodCallData != NULL)
  440. deferredMethodCallData->mDeferDIType = deferDIType;
  441. }
  442. // We don't actually want to see this, and it doesn't emit properly in LLVM CodeView anyway - it only accepts static allocs,
  443. // not dynamic allocas
  444. String varName = StrFormat("$__deferredCall_%d", mCurMethodState->mDeferredLoopListEntryCount);
  445. mCurMethodState->mDeferredLoopListEntryCount++;
  446. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  447. varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, deferDIType);
  448. mBfIRBuilder->DbgInsertDeclare(deferredAlloca, diVariable);
  449. }
  450. return true;
  451. }
  452. BfDeferredCallEntry* BfModule::AddDeferredBlock(BfBlock* block, BfScopeData* scopeData, Array<BfDeferredCapture>* captures)
  453. {
  454. BfDeferredCallEntry* deferredCallEntry = new BfDeferredCallEntry();
  455. deferredCallEntry->mDeferredBlock = block;
  456. if (captures != NULL)
  457. deferredCallEntry->mCaptures = *captures;
  458. AddDeferredCallEntry(deferredCallEntry, scopeData);
  459. return deferredCallEntry;
  460. }
  461. BfDeferredCallEntry* BfModule::AddDeferredCall(const BfModuleMethodInstance& moduleMethodInstance, SizedArrayImpl<BfIRValue>& llvmArgs, BfScopeData* scopeData, BfAstNode* srcNode, bool bypassVirtual, bool doNullCheck)
  462. {
  463. BfDeferredCallEntry* deferredCallEntry = new BfDeferredCallEntry();
  464. BF_ASSERT(moduleMethodInstance);
  465. deferredCallEntry->mModuleMethodInstance = moduleMethodInstance;
  466. for (auto arg : llvmArgs)
  467. {
  468. deferredCallEntry->mScopeArgs.push_back(arg);
  469. }
  470. deferredCallEntry->mSrcNode = srcNode;
  471. deferredCallEntry->mBypassVirtual = bypassVirtual;
  472. deferredCallEntry->mDoNullCheck = doNullCheck;
  473. if (!AddDeferredCallEntry(deferredCallEntry, scopeData))
  474. return NULL;
  475. return deferredCallEntry;
  476. }
  477. void BfModule::EmitDeferredCall(BfModuleMethodInstance moduleMethodInstance, SizedArrayImpl<BfIRValue>& llvmArgs, BfDeferredBlockFlags flags)
  478. {
  479. if (moduleMethodInstance.mMethodInstance->GetOwner()->IsInstanceOf(mCompiler->mInternalTypeDef))
  480. {
  481. if (moduleMethodInstance.mMethodInstance->mMethodDef->mName.StartsWith("SetDeleted"))
  482. {
  483. intptr typeSize = 0;
  484. intptr typeAlign = 1;
  485. intptr clearSize = 0;
  486. bool isDynSize = false;
  487. bool mayBeZero = false;
  488. auto ptrValue = llvmArgs[0];
  489. BfIRValue arraySize;
  490. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted") ||
  491. (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeletedArray"))
  492. {
  493. auto constant = mBfIRBuilder->GetConstant(llvmArgs[1]);
  494. if (constant != NULL)
  495. typeSize = constant->mInt64;
  496. constant = mBfIRBuilder->GetConstant(llvmArgs[2]);
  497. if (constant != NULL)
  498. typeAlign = constant->mInt64;
  499. if (llvmArgs.size() >= 4)
  500. arraySize = llvmArgs[3];
  501. intptr allocSize = typeSize;
  502. if (arraySize)
  503. {
  504. allocSize = BF_ALIGN(typeSize, typeAlign);
  505. auto constant = mBfIRBuilder->GetConstant(arraySize);
  506. if (constant != NULL)
  507. allocSize = allocSize * (intptr)constant->mInt64;
  508. else
  509. {
  510. isDynSize = true;
  511. mayBeZero = true;
  512. }
  513. }
  514. clearSize = BF_MIN(allocSize, mSystem->mPtrSize);
  515. }
  516. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeletedX")
  517. {
  518. // Note: this infers that mayBeZero is false still, because the deferred call would not have
  519. // been added if the array size was zero
  520. typeSize = 1;
  521. clearSize = typeSize;
  522. arraySize = llvmArgs[1];
  523. isDynSize = true;
  524. }
  525. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted1")
  526. {
  527. clearSize = 1;
  528. }
  529. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted2")
  530. {
  531. clearSize = 2;
  532. }
  533. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted4")
  534. {
  535. clearSize = 4;
  536. }
  537. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted8")
  538. {
  539. clearSize = 8;
  540. }
  541. else if (moduleMethodInstance.mMethodInstance->mMethodDef->mName == "SetDeleted16")
  542. {
  543. clearSize = 16;
  544. }
  545. if (clearSize > 0)
  546. {
  547. BfTypeCode clearTypeCode = BfTypeCode_Int8;
  548. if (clearSize >= mSystem->mPtrSize)
  549. clearTypeCode = BfTypeCode_IntPtr;
  550. else if (clearSize >= 4)
  551. clearTypeCode = BfTypeCode_Int32;
  552. else if (clearSize >= 2)
  553. clearTypeCode = BfTypeCode_Int16;
  554. auto intType = GetPrimitiveType(clearTypeCode);
  555. auto intPtrType = CreatePointerType(intType);
  556. if (isDynSize)
  557. {
  558. if (clearSize >= mSystem->mPtrSize)
  559. {
  560. auto ddSize1Block = mBfIRBuilder->CreateBlock("DDSize1");
  561. auto ddDoneBlock = mBfIRBuilder->CreateBlock("DDDone");
  562. auto cmp = mBfIRBuilder->CreateCmpGT(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), true);
  563. mBfIRBuilder->CreateCondBr(cmp, ddSize1Block, ddDoneBlock);
  564. mBfIRBuilder->AddBlock(ddSize1Block);
  565. mBfIRBuilder->SetInsertPoint(ddSize1Block);
  566. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  567. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  568. mBfIRBuilder->CreateBr(ddDoneBlock);
  569. mBfIRBuilder->AddBlock(ddDoneBlock);
  570. mBfIRBuilder->SetInsertPoint(ddDoneBlock);
  571. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  572. {
  573. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSize1Block);
  574. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddDoneBlock);
  575. }
  576. }
  577. else
  578. {
  579. // If we allocate at least this many then we can do an IntPtr-sized marking, otherwise just one element's worth
  580. int intPtrCount = (int)((mSystem->mPtrSize + typeSize - 1) / typeSize);
  581. BfIRBlock ddSizePtrBlock = mBfIRBuilder->CreateBlock("DDSizePtr");
  582. BfIRBlock ddCheck1Block = mBfIRBuilder->CreateBlock("DDCheck1");
  583. BfIRBlock ddSize1Block;
  584. if (mayBeZero)
  585. ddSize1Block = mBfIRBuilder->CreateBlock("DDSize1");
  586. BfIRBlock ddDoneBlock = mBfIRBuilder->CreateBlock("DDDone");
  587. auto intptrType = GetPrimitiveType(BfTypeCode_IntPtr);
  588. auto intptrPtrType = CreatePointerType(intptrType);
  589. auto cmpPtr = mBfIRBuilder->CreateCmpGTE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, intPtrCount), true);
  590. mBfIRBuilder->CreateCondBr(cmpPtr, ddSizePtrBlock, ddCheck1Block);
  591. mBfIRBuilder->AddBlock(ddSizePtrBlock);
  592. mBfIRBuilder->SetInsertPoint(ddSizePtrBlock);
  593. auto intptrPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intptrPtrType));
  594. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)0xDDDDDDDDDDDDDDDDULL), intptrPtrVal);
  595. mBfIRBuilder->CreateBr(ddDoneBlock);
  596. mBfIRBuilder->AddBlock(ddCheck1Block);
  597. mBfIRBuilder->SetInsertPoint(ddCheck1Block);
  598. if (mayBeZero)
  599. {
  600. auto cmp1 = mBfIRBuilder->CreateCmpGT(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), true);
  601. mBfIRBuilder->CreateCondBr(cmp1, ddSize1Block, ddDoneBlock);
  602. mBfIRBuilder->AddBlock(ddSize1Block);
  603. mBfIRBuilder->SetInsertPoint(ddSize1Block);
  604. }
  605. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  606. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  607. mBfIRBuilder->CreateBr(ddDoneBlock);
  608. mBfIRBuilder->AddBlock(ddDoneBlock);
  609. mBfIRBuilder->SetInsertPoint(ddDoneBlock);
  610. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  611. {
  612. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSizePtrBlock);
  613. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddCheck1Block);
  614. if (mayBeZero)
  615. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddSize1Block);
  616. mCurMethodState->mCurScope->mAtEndBlocks.push_back(ddDoneBlock);
  617. }
  618. }
  619. }
  620. else
  621. {
  622. auto intPtrVal = mBfIRBuilder->CreateBitCast(ptrValue, mBfIRBuilder->MapType(intPtrType));
  623. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(clearTypeCode, (uint64)0xDDDDDDDDDDDDDDDDULL), intPtrVal);
  624. }
  625. }
  626. return;
  627. }
  628. }
  629. if (moduleMethodInstance.mMethodInstance == mContext->mValueTypeDeinitSentinel)
  630. {
  631. BF_ASSERT(llvmArgs.size() == 3);
  632. auto sizeConstant = mBfIRBuilder->GetConstant(llvmArgs[1]);
  633. int clearSize = BF_MIN(sizeConstant->mInt32, 32);
  634. auto alignConstant = mBfIRBuilder->GetConstant(llvmArgs[2]);
  635. int clearAlign = alignConstant->mInt32;
  636. mBfIRBuilder->CreateMemSet(llvmArgs[0], GetConstValue8(0xDD), GetConstValue(clearSize), clearAlign);
  637. return;
  638. }
  639. auto methodInstance = moduleMethodInstance.mMethodInstance;
  640. auto methodOwner = methodInstance->mMethodInstanceGroup->mOwner;
  641. bool isDtor = methodInstance->mMethodDef->mMethodType == BfMethodType_Dtor;
  642. bool isScopeDtor = isDtor && ((flags & BfDeferredBlockFlag_BypassVirtual) != 0);
  643. if ((isDtor) && (methodInstance->GetParamCount() != 0))
  644. {
  645. // Dtor declared with params
  646. AssertErrorState();
  647. return;
  648. }
  649. BfIRBlock nullLabel;
  650. BfIRBlock notNullLabel;
  651. if ((flags & BfDeferredBlockFlag_DoNullChecks) != 0)
  652. {
  653. nullLabel = mBfIRBuilder->CreateBlock("deferred.isNull");
  654. notNullLabel = mBfIRBuilder->CreateBlock("deferred.notNull");
  655. auto notNullVal = mBfIRBuilder->CreateIsNotNull(llvmArgs[0]);
  656. mBfIRBuilder->CreateCondBr(notNullVal, notNullLabel, nullLabel);
  657. mBfIRBuilder->AddBlock(notNullLabel);
  658. mBfIRBuilder->SetInsertPoint(notNullLabel);
  659. }
  660. bool skipAccessCheck = false;
  661. if ((flags & BfDeferredBlockFlag_SkipObjectAccessCheck) != 0)
  662. skipAccessCheck = true;
  663. if ((!methodInstance->mMethodDef->mIsStatic) && (methodOwner->IsObjectOrInterface()) && (!isScopeDtor) &&
  664. (!skipAccessCheck))
  665. {
  666. EmitObjectAccessCheck(BfTypedValue(llvmArgs[0], methodOwner));
  667. }
  668. BfExprEvaluator expressionEvaluator(this);
  669. expressionEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, ((flags & BfDeferredBlockFlag_BypassVirtual) != 0), llvmArgs);
  670. if ((flags & BfDeferredBlockFlag_DoNullChecks) != 0)
  671. {
  672. mBfIRBuilder->CreateBr(nullLabel);
  673. mBfIRBuilder->AddBlock(nullLabel);
  674. mBfIRBuilder->SetInsertPoint(nullLabel);
  675. if (!mBfIRBuilder->mIgnoreWrites)
  676. {
  677. if ((flags & BfDeferredBlockFlag_MoveNewBlocksToEnd) != 0)
  678. {
  679. mCurMethodState->mCurScope->mAtEndBlocks.push_back(notNullLabel);
  680. mCurMethodState->mCurScope->mAtEndBlocks.push_back(nullLabel);
  681. }
  682. }
  683. }
  684. }
  685. void BfModule::EmitDeferredCallProcessorInstances(BfScopeData* scopeData)
  686. {
  687. BF_ASSERT(scopeData->mDone);
  688. for (auto& deferredProcessor : scopeData->mDeferredCallProcessorInstances)
  689. {
  690. SetAndRestoreValue<bool> prevHadReturn(mCurMethodState->mHadReturn, false);
  691. SetAndRestoreValue<bool> prevInPostReturn(mCurMethodState->mInPostReturn, false);
  692. SetAndRestoreValue<bool> prevLeftBlockUncond(mCurMethodState->mLeftBlockUncond, false);
  693. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  694. mBfIRBuilder->AddBlock(deferredProcessor.mProcessorBlock);
  695. mBfIRBuilder->SetInsertPoint(deferredProcessor.mProcessorBlock);
  696. EmitDeferredCallProcessor(scopeData, deferredProcessor.mDeferredCallEntry->mDynList, deferredProcessor.mDeferredCallEntry->mDynCallTail);
  697. mBfIRBuilder->CreateBr(deferredProcessor.mContinueBlock);
  698. mBfIRBuilder->SetInsertPoint(prevBlock);
  699. }
  700. }
  701. void BfModule::EmitDeferredCall(BfScopeData* scopeData, BfDeferredCallEntry& deferredCallEntry, bool moveBlocks)
  702. {
  703. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (deferredCallEntry.mHandlerCount > 0))
  704. {
  705. // We only want to process deferred blocks once, otherwise it could significantly slow down autocompletion
  706. return;
  707. }
  708. deferredCallEntry.mHandlerCount++;
  709. if (deferredCallEntry.IsDynList())
  710. {
  711. if (scopeData->mDone)
  712. {
  713. EmitDeferredCallProcessor(scopeData, deferredCallEntry.mDynList, deferredCallEntry.mDynCallTail);
  714. }
  715. else
  716. {
  717. BfDeferredCallProcessorInstance deferredProcessor;
  718. deferredProcessor.mProcessorBlock = mBfIRBuilder->CreateBlock("dyn.processor");
  719. deferredProcessor.mContinueBlock = mBfIRBuilder->CreateBlock("dyn.continue");
  720. deferredProcessor.mDeferredCallEntry = &deferredCallEntry;
  721. scopeData->mDeferredCallProcessorInstances.Add(deferredProcessor);
  722. mBfIRBuilder->CreateBr(deferredProcessor.mProcessorBlock);
  723. mBfIRBuilder->AddBlock(deferredProcessor.mContinueBlock);
  724. mBfIRBuilder->SetInsertPoint(deferredProcessor.mContinueBlock);
  725. SetIllegalSrcPos();
  726. EmitEnsureInstructionAt();
  727. }
  728. return;
  729. }
  730. if (deferredCallEntry.mDeferredBlock != NULL)
  731. {
  732. // Only show warnings on the first pass
  733. // For errors, show on the first pass OR as long as we haven't gotten any errors within this method. I'm not sure if there's a case
  734. // where the first emission succeeds but a subsequent one would fail, but we leave this logic to handle that possibility
  735. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, (deferredCallEntry.mHandlerCount > 1) && (mCurMethodInstance->mHasFailed));
  736. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, (deferredCallEntry.mHandlerCount > 1));
  737. BfScopeData scopeData;
  738. mCurMethodState->AddScope(&scopeData);
  739. NewScopeState();
  740. for (auto& capture : deferredCallEntry.mCaptures)
  741. {
  742. BfLocalVariable* localVar = new BfLocalVariable();
  743. localVar->mIsReadOnly = true;
  744. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  745. localVar->mReadFromId = 0;
  746. localVar->mName = capture.mName;
  747. localVar->mValue = capture.mValue.mValue;
  748. localVar->mResolvedType = capture.mValue.mType;
  749. if ((mBfIRBuilder->DbgHasInfo()) && (!localVar->mResolvedType->IsValuelessType()))
  750. {
  751. auto addr = CreateAlloca(localVar->mResolvedType);
  752. mBfIRBuilder->CreateAlignedStore(localVar->mValue, addr, localVar->mResolvedType->mAlign);
  753. localVar->mAddr = addr;
  754. }
  755. AddLocalVariableDef(localVar, true);
  756. }
  757. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry.mEmitRefNode);
  758. VisitEmbeddedStatement(deferredCallEntry.mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  759. RestoreScopeState();
  760. return;
  761. }
  762. auto args = deferredCallEntry.mScopeArgs;
  763. if (deferredCallEntry.mArgsNeedLoad)
  764. {
  765. for (auto& arg : args)
  766. {
  767. if (!arg.IsConst())
  768. arg = mBfIRBuilder->CreateLoad(arg);
  769. }
  770. }
  771. if (deferredCallEntry.mCastThis)
  772. {
  773. args[0] = mBfIRBuilder->CreateBitCast(args[0], mBfIRBuilder->MapTypeInstPtr(deferredCallEntry.mModuleMethodInstance.mMethodInstance->GetOwner()));
  774. }
  775. BfDeferredBlockFlags flags = BfDeferredBlockFlag_None;
  776. if (deferredCallEntry.mBypassVirtual)
  777. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_BypassVirtual);
  778. if (deferredCallEntry.mDoNullCheck)
  779. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_DoNullChecks | BfDeferredBlockFlag_SkipObjectAccessCheck | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  780. if (moveBlocks)
  781. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  782. EmitDeferredCall(deferredCallEntry.mModuleMethodInstance, args, flags);
  783. }
  784. void BfModule::EmitDeferredCallProcessor(BfScopeData* scopeData, SLIList<BfDeferredCallEntry*>& callEntries, BfIRValue callTail)
  785. {
  786. int64 collisionId = 0;
  787. struct _CallInfo
  788. {
  789. BfModuleMethodInstance mModuleMethodInstance;
  790. bool mBypassVirtual;
  791. };
  792. //typedef std::map<int64, _CallInfo> MapType;
  793. //MapType methodInstanceMap;
  794. Dictionary<int64, _CallInfo> methodInstanceMap;
  795. int blockCount = 0;
  796. HashSet<BfMethodInstance*> nullCheckMethodSet;
  797. BfDeferredCallEntry* deferredCallEntry = callEntries.mHead;
  798. while (deferredCallEntry != NULL)
  799. {
  800. BfModuleMethodInstance moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  801. int64 methodId = 0;
  802. if (moduleMethodInstance.mMethodInstance != NULL)
  803. {
  804. int64 idHash = moduleMethodInstance.mMethodInstance->mIdHash;
  805. auto deferredMethodCallData = mDeferredMethodCallData[moduleMethodInstance.mMethodInstance];
  806. BF_ASSERT(deferredMethodCallData->mMethodId != 0);
  807. //methodInstanceMap[deferredMethodCallData->mMethodId] = moduleMethodInstance;
  808. _CallInfo* callInfo = NULL;
  809. if (methodInstanceMap.TryAdd(deferredMethodCallData->mMethodId, NULL, &callInfo))
  810. {
  811. callInfo->mModuleMethodInstance = moduleMethodInstance;
  812. callInfo->mBypassVirtual = deferredCallEntry->mBypassVirtual;
  813. }
  814. else
  815. {
  816. // Only bypass virtual if ALL these calls are devirtualized
  817. callInfo->mBypassVirtual &= deferredCallEntry->mBypassVirtual;
  818. }
  819. }
  820. else
  821. blockCount++;
  822. if (deferredCallEntry->mDoNullCheck)
  823. nullCheckMethodSet.Add(deferredCallEntry->mModuleMethodInstance.mMethodInstance);
  824. deferredCallEntry = deferredCallEntry->mNext;
  825. }
  826. bool moveBlocks = mCurMethodState->mCurScope != mCurMethodState->mTailScope;
  827. auto valueScopeStart = ValueScopeStart();
  828. if (valueScopeStart)
  829. mBfIRBuilder->SetName(valueScopeStart, "deferredScopeVal");
  830. BfIRBlock condBB = mBfIRBuilder->CreateBlock("deferCall.cond", true);
  831. if (moveBlocks)
  832. mCurMethodState->mCurScope->mAtEndBlocks.push_back(condBB);
  833. mBfIRBuilder->CreateBr(condBB);
  834. auto deferredCallEntryType = ResolveTypeDef(mCompiler->mDeferredCallTypeDef);
  835. auto deferredCallEntryTypePtr = CreatePointerType(deferredCallEntryType);
  836. BfIRBlock bodyBB = mBfIRBuilder->CreateBlock("deferCall.body");
  837. if (moveBlocks)
  838. mCurMethodState->mCurScope->mAtEndBlocks.push_back(bodyBB);
  839. BfIRBlock endBB = mBfIRBuilder->CreateBlock("deferCall.end");
  840. if (moveBlocks)
  841. mCurMethodState->mCurScope->mAtEndBlocks.push_back(endBB);
  842. BfIRBlock exitBB = endBB;
  843. BfIRValue deferredCallTail;
  844. mBfIRBuilder->SetInsertPoint(condBB);
  845. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  846. auto isNotNull = mBfIRBuilder->CreateIsNotNull(deferredCallTail);
  847. ValueScopeEnd(valueScopeStart);
  848. mBfIRBuilder->CreateCondBr(isNotNull, bodyBB, exitBB);
  849. mBfIRBuilder->AddBlock(bodyBB);
  850. mBfIRBuilder->SetInsertPoint(bodyBB);
  851. BfIRValue switchInst;
  852. bool wantsSwitch = ((int)methodInstanceMap.size() + blockCount) > 1;
  853. if (blockCount > 0)
  854. {
  855. // A block may embed a switch so we need a switch whenever we have blocks
  856. wantsSwitch = true;
  857. }
  858. if (mCurMethodState->mCancelledDeferredCall)
  859. wantsSwitch = true;
  860. if (wantsSwitch)
  861. {
  862. if (IsTargetingBeefBackend())
  863. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  864. auto idPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 1); // mMethodId
  865. auto id = mBfIRBuilder->CreateLoad(idPtr);
  866. switchInst = mBfIRBuilder->CreateSwitch(id, exitBB, (int)methodInstanceMap.size());
  867. ValueScopeEnd(valueScopeStart);
  868. }
  869. BfDeferredCallEntry* prevHead = callEntries.mHead;
  870. BfDeferredCallEntry* prevCallEntry = NULL;
  871. HashSet<BfDeferredCallEntry*> handledSet;
  872. deferredCallEntry = callEntries.mHead;
  873. while (deferredCallEntry != NULL)
  874. {
  875. auto block = deferredCallEntry->mDeferredBlock;
  876. if (block == NULL)
  877. {
  878. deferredCallEntry = deferredCallEntry->mNext;
  879. continue;
  880. }
  881. int64 blockId = deferredCallEntry->mBlockId;
  882. //auto itr = handledSet.insert(deferredCallEntry);
  883. //if (!itr.second)
  884. if (!handledSet.Add(deferredCallEntry))
  885. {
  886. // Already handled, can happen if we defer again within the block
  887. deferredCallEntry = deferredCallEntry->mNext;
  888. continue;
  889. }
  890. if (switchInst)
  891. {
  892. String caseName = StrFormat("deferCall.%s", BfTypeUtils::HashEncode64(blockId).c_str());
  893. auto caseBB = mBfIRBuilder->CreateBlock(caseName, true);
  894. if (moveBlocks)
  895. mCurMethodState->mCurScope->mAtEndBlocks.push_back(caseBB);
  896. mBfIRBuilder->AddSwitchCase(switchInst, GetConstValue64(blockId), caseBB);
  897. mBfIRBuilder->SetInsertPoint(caseBB);
  898. }
  899. // Update .mDeferredAlloca to use the deferredCallTail
  900. if (IsTargetingBeefBackend())
  901. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  902. auto nextPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 2); // mNext
  903. auto next = mBfIRBuilder->CreateLoad(nextPtr);
  904. mBfIRBuilder->CreateStore(next, callTail);
  905. deferredCallEntry->mDeferredAlloca = mBfIRBuilder->CreateBitCast(deferredCallTail, mBfIRBuilder->GetType(deferredCallEntry->mDeferredAlloca));
  906. int dataIdx = 3;
  907. // Update .mCaptures to contain the stored values at the time the defer occurred
  908. for (int captureIdx = 0; captureIdx < (int)deferredCallEntry->mCaptures.size(); captureIdx++)
  909. {
  910. auto& capture = deferredCallEntry->mCaptures[captureIdx];
  911. if (!capture.mValue.mType->IsValuelessType())
  912. {
  913. auto gepInstance = mBfIRBuilder->CreateInBoundsGEP(deferredCallEntry->mDeferredAlloca, 0, dataIdx);
  914. capture.mValue.mValue = mBfIRBuilder->CreateLoad(gepInstance);
  915. dataIdx++;
  916. }
  917. }
  918. auto prevHead = callEntries.mHead;
  919. EmitDeferredCall(scopeData, *deferredCallEntry, moveBlocks);
  920. ValueScopeEnd(valueScopeStart);
  921. mBfIRBuilder->CreateBr(condBB);
  922. if (prevHead != callEntries.mHead)
  923. {
  924. // The list changed, start over and ignore anything we've already handled
  925. deferredCallEntry = callEntries.mHead;
  926. }
  927. else
  928. deferredCallEntry = deferredCallEntry->mNext;
  929. }
  930. // Blocks may have added new method types, so rebuild map
  931. if (blockCount > 0)
  932. {
  933. deferredCallEntry = callEntries.mHead;
  934. while (deferredCallEntry != NULL)
  935. {
  936. BfModuleMethodInstance moduleMethodInstance = deferredCallEntry->mModuleMethodInstance;
  937. if (moduleMethodInstance.mMethodInstance != NULL)
  938. {
  939. auto deferredMethodCallData = mDeferredMethodCallData[moduleMethodInstance.mMethodInstance];
  940. //methodInstanceMap.insert(MapType::value_type(deferredMethodCallData->mMethodId, moduleMethodInstance));
  941. _CallInfo* callInfo = NULL;
  942. if (methodInstanceMap.TryAdd(deferredMethodCallData->mMethodId, NULL, &callInfo))
  943. {
  944. callInfo->mModuleMethodInstance = moduleMethodInstance;
  945. callInfo->mBypassVirtual = deferredCallEntry->mBypassVirtual;
  946. }
  947. }
  948. deferredCallEntry = deferredCallEntry->mNext;
  949. }
  950. }
  951. BfExprEvaluator exprEvaluator(this);
  952. //for (auto itr = methodInstanceMap.begin(); itr != methodInstanceMap.end(); ++itr)
  953. for (auto& callInfoKV : methodInstanceMap)
  954. {
  955. auto moduleMethodInstance = callInfoKV.mValue.mModuleMethodInstance;
  956. bool bypassVirtual = callInfoKV.mValue.mBypassVirtual;
  957. auto methodInstance = moduleMethodInstance.mMethodInstance;
  958. auto methodDef = methodInstance->mMethodDef;
  959. auto methodOwner = methodInstance->mMethodInstanceGroup->mOwner;
  960. BfIRValue deferredCallInst = deferredCallTail;
  961. auto deferredMethodCallData = mDeferredMethodCallData[methodInstance];
  962. int64 methodId = deferredMethodCallData->mMethodId;
  963. if (switchInst)
  964. {
  965. String caseName = StrFormat("deferCall.%s", BfTypeUtils::HashEncode64(methodId).c_str());
  966. auto caseBB = mBfIRBuilder->CreateBlock(caseName, true);
  967. if (moveBlocks)
  968. mCurMethodState->mCurScope->mAtEndBlocks.push_back(caseBB);
  969. mBfIRBuilder->AddSwitchCase(switchInst, GetConstValue64(methodId), caseBB);
  970. mBfIRBuilder->SetInsertPoint(caseBB);
  971. }
  972. if (IsTargetingBeefBackend())
  973. deferredCallTail = mBfIRBuilder->CreateLoad(callTail);
  974. auto nextPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallTail, 0, 2); // mNext
  975. auto next = mBfIRBuilder->CreateLoad(nextPtr);
  976. mBfIRBuilder->CreateStore(next, callTail);
  977. deferredCallInst = mBfIRBuilder->CreateBitCast(deferredCallTail, deferredMethodCallData->mDeferTypePtr);
  978. int paramIdx = 0;
  979. if (!methodDef->mIsStatic)
  980. paramIdx = -1;
  981. SizedArray<BfIRValue, 8> llvmArgs;
  982. for (int argIdx = 0; paramIdx < methodInstance->GetParamCount(); argIdx++, paramIdx++)
  983. {
  984. auto argPtr = mBfIRBuilder->CreateInBoundsGEP(deferredCallInst, 0, argIdx + 2);
  985. bool isStruct = false;
  986. bool doSplat = methodInstance->GetParamIsSplat(paramIdx);;
  987. BfTypedValue typedVal;
  988. if (paramIdx == -1)
  989. {
  990. typedVal = BfTypedValue(argPtr, methodOwner, true);
  991. }
  992. else
  993. {
  994. auto paramType = methodInstance->GetParamType(paramIdx);
  995. typedVal = BfTypedValue(argPtr, paramType, true);
  996. }
  997. if (doSplat)
  998. {
  999. exprEvaluator.SplatArgs(typedVal, llvmArgs);
  1000. continue;
  1001. }
  1002. if ((argIdx == 0) && (!methodDef->mIsStatic))
  1003. {
  1004. // 'this'
  1005. isStruct = methodOwner->IsValueType();
  1006. }
  1007. else
  1008. {
  1009. while (methodInstance->IsParamSkipped(paramIdx))
  1010. paramIdx++;
  1011. if (paramIdx >= methodInstance->GetParamCount())
  1012. break;
  1013. auto paramType = methodInstance->GetParamType(paramIdx);
  1014. isStruct = paramType->IsStruct();
  1015. }
  1016. if (isStruct)
  1017. {
  1018. llvmArgs.push_back(argPtr);
  1019. }
  1020. else
  1021. {
  1022. auto arg = mBfIRBuilder->CreateLoad(argPtr);
  1023. llvmArgs.push_back(arg);
  1024. }
  1025. }
  1026. BfDeferredBlockFlags flags = BfDeferredBlockFlag_None;
  1027. if (moveBlocks)
  1028. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_MoveNewBlocksToEnd);
  1029. if (nullCheckMethodSet.Contains(moduleMethodInstance.mMethodInstance))
  1030. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_DoNullChecks | BfDeferredBlockFlag_SkipObjectAccessCheck);
  1031. if (bypassVirtual)
  1032. flags = (BfDeferredBlockFlags)(flags | BfDeferredBlockFlag_BypassVirtual);
  1033. EmitDeferredCall(moduleMethodInstance, llvmArgs, flags);
  1034. ValueScopeEnd(valueScopeStart);
  1035. mBfIRBuilder->CreateBr(condBB);
  1036. }
  1037. if (endBB)
  1038. {
  1039. mBfIRBuilder->AddBlock(endBB);
  1040. mBfIRBuilder->SetInsertPoint(endBB);
  1041. }
  1042. }
  1043. void BfModule::TryInitVar(BfAstNode* checkNode, BfLocalVariable* localVar, BfTypedValue initValue, BfTypedValue& checkResult)
  1044. {
  1045. BF_ASSERT(!localVar->mAddr);
  1046. localVar->mAddr = AllocLocalVariable(localVar->mResolvedType, localVar->mName);
  1047. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1048. auto varType = localVar->mResolvedType;
  1049. AddDependency(varType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  1050. if (!initValue)
  1051. {
  1052. AssertErrorState();
  1053. checkResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  1054. return;
  1055. }
  1056. auto initType = initValue.mType;
  1057. bool isDynamicCast = false;
  1058. if (varType->IsGenericParam())
  1059. {
  1060. int pass = 0;
  1061. while (varType->IsGenericParam())
  1062. {
  1063. auto genericParamType = (BfGenericParamType*)varType;
  1064. auto genericParam = GetGenericParamInstance(genericParamType);
  1065. auto typeConstraint = genericParam->mTypeConstraint;
  1066. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  1067. typeConstraint = mContext->mBfObjectType;
  1068. if (typeConstraint != NULL)
  1069. varType = typeConstraint;
  1070. else
  1071. break;
  1072. if (++pass >= 100) // Sanity - but we should have caught circular error before
  1073. break;
  1074. }
  1075. initValue = GetDefaultTypedValue(varType, false, BfDefaultValueKind_Undef);
  1076. }
  1077. BfTypeInstance* srcTypeInstance = initValue.mType->ToTypeInstance();
  1078. BfTypeInstance* varTypeInstance = varType->ToTypeInstance();
  1079. if (CanCast(initValue, varType))
  1080. {
  1081. if ((!varType->IsPointer()) && (!varType->IsObjectOrInterface()) && (!varType->IsVar()))
  1082. {
  1083. if (!IsInSpecializedSection())
  1084. {
  1085. if (initValue.mType != varType)
  1086. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' because static cast cannot fail and a value of type '%s' can never be null",
  1087. TypeToString(varType).c_str()), checkNode);
  1088. else
  1089. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' because a value of type '%s' can never be null",
  1090. TypeToString(varType).c_str()), checkNode);
  1091. }
  1092. }
  1093. }
  1094. // else if ((initType->IsInterface()) || (initType == mContext->mBfObjectType))
  1095. // {
  1096. // // Interface or System.Object -> *
  1097. // isDynamicCast = true;
  1098. // }
  1099. // else if ((srcTypeInstance != NULL) && (varTypeInstance != NULL) &&
  1100. // ((srcTypeInstance->IsObject()) && (TypeIsSubTypeOf(varTypeInstance, srcTypeInstance))))
  1101. // {
  1102. // // Class downcast
  1103. // isDynamicCast = true;
  1104. // }
  1105. // else if ((!CanCast(GetFakeTypedValue(varType), initType)) && (!initType->IsGenericParam()))
  1106. // {
  1107. // if (!IsInSpecializedSection())
  1108. // {
  1109. // Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  1110. // TypeToString(initValue.mType).c_str(), TypeToString(varType).c_str()), checkNode);
  1111. // }
  1112. // }
  1113. if (!isDynamicCast)
  1114. {
  1115. //initValue = Cast(checkNode, initValue, varType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  1116. initValue = Cast(checkNode, initValue, varType);
  1117. if (!initValue)
  1118. {
  1119. checkResult = BfTypedValue(GetConstValue(0, boolType), boolType);
  1120. }
  1121. else
  1122. {
  1123. if (localVar->mAddr)
  1124. {
  1125. initValue = LoadValue(initValue);
  1126. if (!initValue.mType->IsVar())
  1127. mBfIRBuilder->CreateAlignedStore(initValue.mValue, localVar->mAddr, initValue.mType->mAlign);
  1128. }
  1129. if (varType->IsVar())
  1130. {
  1131. checkResult = GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  1132. }
  1133. else if ((varType->IsPointer()) || (varType->IsObjectOrInterface()))
  1134. {
  1135. checkResult = BfTypedValue(mBfIRBuilder->CreateIsNotNull(initValue.mValue), boolType);
  1136. }
  1137. else
  1138. {
  1139. checkResult = BfTypedValue(GetConstValue(1, boolType), boolType);
  1140. }
  1141. }
  1142. return;
  1143. }
  1144. if (mCompiler->IsAutocomplete())
  1145. {
  1146. auto allocaResult = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(boolType));
  1147. auto val = mBfIRBuilder->CreateLoad(allocaResult);
  1148. checkResult = BfTypedValue(val, boolType);
  1149. return;
  1150. }
  1151. int wantTypeId = 0;
  1152. if (!varType->IsGenericParam())
  1153. wantTypeId = varType->mTypeId;
  1154. auto objectType = mContext->mBfObjectType;
  1155. PopulateType(objectType, BfPopulateType_Full);
  1156. initValue = LoadValue(initValue);
  1157. auto prevBB = mBfIRBuilder->GetInsertBlock();
  1158. auto matchBB = mBfIRBuilder->CreateBlock("is.match");
  1159. auto endBB = mBfIRBuilder->CreateBlock("is.done");
  1160. BfIRValue boolResult = CreateAlloca(boolType);
  1161. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  1162. EmitDynamicCastCheck(initValue, varType, matchBB, endBB);
  1163. AddBasicBlock(matchBB);
  1164. mBfIRBuilder->CreateStore(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  1165. mBfIRBuilder->CreateBr(endBB);
  1166. AddBasicBlock(endBB);
  1167. checkResult = BfTypedValue(mBfIRBuilder->CreateLoad(boolResult), boolType);
  1168. }
  1169. BfLocalVariable* BfModule::HandleVariableDeclaration(BfVariableDeclaration* varDecl, BfExprEvaluator* exprEvaluator)
  1170. {
  1171. if (mCurMethodState == NULL)
  1172. {
  1173. Fail("Invalid variable declaration", varDecl);
  1174. return NULL;
  1175. }
  1176. BfAutoComplete* bfAutocomplete = NULL;
  1177. // Just a check
  1178. mBfIRBuilder->GetInsertBlock();
  1179. if (mCompiler->mResolvePassData != NULL)
  1180. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  1181. if (bfAutocomplete != NULL)
  1182. bfAutocomplete->CheckTypeRef(varDecl->mTypeRef, true, true);
  1183. bool isConst = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Const);
  1184. bool isReadOnly = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_ReadOnly);
  1185. bool isStatic = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Static);
  1186. BfLocalVariable* localDef = new BfLocalVariable();
  1187. if (varDecl->mNameNode != NULL)
  1188. {
  1189. varDecl->mNameNode->ToString(localDef->mName);
  1190. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  1191. }
  1192. else
  1193. {
  1194. localDef->mName = "val";
  1195. }
  1196. localDef->mIsStatic = isStatic;
  1197. bool handledExprBoolResult = false;
  1198. bool handledVarInit = false;
  1199. bool handledVarStore = false;
  1200. BfType* unresolvedType = NULL;
  1201. BfType* resolvedType = NULL;
  1202. BfTypedValue initValue;
  1203. bool hadVarType = false;
  1204. bool isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  1205. bool initHandled = false;
  1206. auto _DoConditionalInit = [&](BfType* expectedType)
  1207. {
  1208. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1209. auto _EmitCond = [&](BfIRValue condVal, BfTypedValue initValue)
  1210. {
  1211. initValue = Cast(varDecl->mInitializer, initValue, expectedType);
  1212. if (!initValue)
  1213. return;
  1214. initHandled = true;
  1215. if (localDef->mIsReadOnly)
  1216. {
  1217. if ((initValue.IsReadOnly()) ||
  1218. (initValue.mKind == BfTypedValueKind_TempAddr))
  1219. {
  1220. localDef->mAddr = initValue.mValue;
  1221. exprEvaluator->mResult = BfTypedValue(condVal, boolType);
  1222. return;
  1223. }
  1224. }
  1225. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1226. auto doAssignBlock = mBfIRBuilder->CreateBlock("assign");
  1227. auto skipAssignBlock = mBfIRBuilder->CreateBlock("skipAssign");
  1228. auto insertBlock = mBfIRBuilder->GetInsertBlock();
  1229. mBfIRBuilder->CreateCondBr(condVal, doAssignBlock, skipAssignBlock);
  1230. mBfIRBuilder->AddBlock(doAssignBlock);
  1231. mBfIRBuilder->SetInsertPoint(doAssignBlock);
  1232. initValue = LoadValue(initValue);
  1233. mBfIRBuilder->CreateStore(initValue.mValue, localDef->mAddr);
  1234. mBfIRBuilder->CreateBr(skipAssignBlock);
  1235. mBfIRBuilder->AddBlock(skipAssignBlock);
  1236. mBfIRBuilder->SetInsertPoint(skipAssignBlock);
  1237. auto phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  1238. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), insertBlock);
  1239. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), doAssignBlock);
  1240. exprEvaluator->mResult = BfTypedValue(phiVal, boolType);
  1241. };
  1242. bool handled = false;
  1243. if ((initValue) && (initValue.mType->IsPayloadEnum()))
  1244. {
  1245. auto typeInst = initValue.mType->ToTypeInstance();
  1246. PopulateType(typeInst);
  1247. BfType* outType = NULL;
  1248. int tagId = -1;
  1249. if (typeInst->GetResultInfo(outType, tagId))
  1250. {
  1251. int dscDataIdx = -1;
  1252. auto dscType = typeInst->GetDiscriminatorType(&dscDataIdx);
  1253. BfIRValue dscVal = ExtractValue(initValue, dscDataIdx);
  1254. auto eqVal = mBfIRBuilder->CreateCmpEQ(dscVal, GetConstValue(tagId, dscType));
  1255. exprEvaluator->mResult = BfTypedValue(eqVal, boolType);
  1256. PopulateType(outType);
  1257. if (!outType->IsValuelessType())
  1258. {
  1259. auto outPtrType = CreatePointerType(outType);
  1260. initValue = MakeAddressable(initValue);
  1261. auto payloadVal = mBfIRBuilder->CreateBitCast(initValue.mValue, mBfIRBuilder->MapType(outPtrType));
  1262. auto payload = BfTypedValue(payloadVal, outType, true);
  1263. if ((initValue.mKind == BfTypedValueKind_ReadOnlyAddr) ||
  1264. (initValue.mKind == BfTypedValueKind_TempAddr) ||
  1265. (initValue.mKind == BfTypedValueKind_ReadOnlyTempAddr))
  1266. payload.mKind = initValue.mKind;
  1267. _EmitCond(eqVal, payload);
  1268. }
  1269. handled = true;
  1270. }
  1271. }
  1272. if (handled)
  1273. {
  1274. handledExprBoolResult = true;
  1275. handledVarInit = true;
  1276. handledVarStore = true;
  1277. }
  1278. else if ((initValue) && (initValue.mType->IsNullable()))
  1279. {
  1280. auto underlyingType = initValue.mType->GetUnderlyingType();
  1281. exprEvaluator->mResult = BfTypedValue(ExtractValue(initValue, 2), boolType);
  1282. handledExprBoolResult = true;
  1283. if (!resolvedType->IsNullable())
  1284. {
  1285. if (initValue.IsAddr())
  1286. initValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(initValue.mValue, 0, 1), initValue.mType->GetUnderlyingType(), true);
  1287. else
  1288. initValue = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 1), initValue.mType->GetUnderlyingType());
  1289. }
  1290. if ((initValue) && (!initValue.mType->IsValuelessType()))
  1291. {
  1292. _EmitCond(exprEvaluator->mResult.mValue, initValue);
  1293. handledVarStore = true;
  1294. }
  1295. handledVarInit = true;
  1296. }
  1297. else if (initValue)
  1298. {
  1299. BfAstNode* refNode = varDecl;
  1300. if (varDecl->mInitializer != NULL)
  1301. refNode = varDecl->mInitializer;
  1302. TryInitVar(refNode, localDef, initValue, exprEvaluator->mResult);
  1303. handledExprBoolResult = true;
  1304. handledVarInit = true;
  1305. handledVarStore = true;
  1306. }
  1307. };
  1308. if ((varDecl->mTypeRef->IsA<BfVarTypeReference>()) || (isLet))
  1309. {
  1310. hadVarType = true;
  1311. if (varDecl->mInitializer == NULL)
  1312. {
  1313. if (!isLet)
  1314. {
  1315. BfLocalVarEntry* shadowEntry;
  1316. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localDef), &shadowEntry))
  1317. {
  1318. auto prevLocal = shadowEntry->mLocalVar;
  1319. if (prevLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx())
  1320. {
  1321. BfExprEvaluator exprEvaluator(this);
  1322. initValue = exprEvaluator.LoadLocal(prevLocal);
  1323. resolvedType = initValue.mType;
  1324. unresolvedType = resolvedType;
  1325. localDef->mLocalVarId = prevLocal->mLocalVarId;
  1326. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1327. localDef->mIsShadow = true;
  1328. exprEvaluator.mResultLocalVarRefNode = varDecl->mNameNode;
  1329. exprEvaluator.mResultLocalVar = prevLocal;
  1330. exprEvaluator.CheckResultForReading(initValue);
  1331. if (bfAutocomplete != NULL)
  1332. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, resolvedType);
  1333. }
  1334. }
  1335. }
  1336. if (!initValue)
  1337. {
  1338. Fail("Implicitly-typed variables must be initialized", varDecl);
  1339. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  1340. }
  1341. }
  1342. else
  1343. {
  1344. if (isConst)
  1345. {
  1346. BfConstResolver constResolver(this);
  1347. initValue = constResolver.Resolve(varDecl->mInitializer);
  1348. }
  1349. else
  1350. {
  1351. BfExprEvaluator valExprEvaluator(this);
  1352. valExprEvaluator.mAllowReadOnlyReference = isLet;
  1353. initValue = CreateValueFromExpression(valExprEvaluator, varDecl->mInitializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_VariableDeclaration));
  1354. if ((exprEvaluator != NULL) && (initValue))
  1355. {
  1356. if (initValue.mType->IsNullable())
  1357. {
  1358. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1359. initValue = LoadValue(initValue);
  1360. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 2), boolType);
  1361. handledExprBoolResult = true;
  1362. initValue = BfTypedValue(mBfIRBuilder->CreateExtractValue(initValue.mValue, 1), initValue.mType->GetUnderlyingType());
  1363. }
  1364. else
  1365. {
  1366. auto typeInst = initValue.mType->ToTypeInstance();
  1367. if (typeInst != NULL)
  1368. {
  1369. PopulateType(typeInst);
  1370. BfType* outType = NULL;
  1371. int tagId = -1;
  1372. if (typeInst->GetResultInfo(outType, tagId))
  1373. {
  1374. handledExprBoolResult = true;
  1375. unresolvedType = outType;
  1376. resolvedType = outType;
  1377. isReadOnly = isLet;
  1378. localDef->mIsReadOnly = isLet;
  1379. _DoConditionalInit(outType);
  1380. }
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. if (!initValue)
  1387. {
  1388. initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Var));
  1389. }
  1390. if (initValue.mType->IsNull())
  1391. {
  1392. Fail("Implicitly-typed variables cannot be initialized to 'null'", varDecl->mInitializer);
  1393. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  1394. }
  1395. if (unresolvedType == NULL)
  1396. unresolvedType = initValue.mType;
  1397. resolvedType = unresolvedType;
  1398. if ((initValue.IsTempAddr()) && (!localDef->mAddr) && (initValue.mType == resolvedType))
  1399. {
  1400. // Take over value
  1401. localDef->mAddr = initValue.mValue;
  1402. handledVarInit = true;
  1403. if (isLet)
  1404. {
  1405. localDef->mValue = mBfIRBuilder->CreateLoad(localDef->mAddr);
  1406. }
  1407. }
  1408. if (bfAutocomplete != NULL)
  1409. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, resolvedType);
  1410. }
  1411. else
  1412. {
  1413. BfTypeState typeState;
  1414. typeState.mCurVarInitializer = varDecl->mInitializer;
  1415. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1416. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef);
  1417. if (varDecl->mInitializer != NULL)
  1418. flags = (BfResolveTypeRefFlags)(flags | BfResolveTypeRefFlag_AllowInferredSizedArray);
  1419. unresolvedType = ResolveTypeRef(varDecl->mTypeRef, BfPopulateType_Data, flags);
  1420. if (unresolvedType == NULL)
  1421. unresolvedType = GetPrimitiveType(BfTypeCode_Var);
  1422. resolvedType = unresolvedType;
  1423. }
  1424. auto _CheckConst = [&]
  1425. {
  1426. if (initValue.IsAddr())
  1427. {
  1428. isConst = false;
  1429. }
  1430. else if (initValue.mValue.IsConst())
  1431. {
  1432. auto constant = mBfIRBuilder->GetConstant(initValue.mValue);
  1433. // NullPtr is stand-in for GlobalVar during autocomplete
  1434. if ((constant->mConstType == BfConstType_GlobalVar) ||
  1435. (constant->mTypeCode == BfTypeCode_NullPtr))
  1436. {
  1437. // Not really constant
  1438. // localNeedsAddr = false;
  1439. // isConst = false;
  1440. // initHandled = true;
  1441. // localDef->mValue = initValue.mValue;
  1442. if (GetStringPoolIdx(initValue.mValue, mBfIRBuilder) == -1)
  1443. isConst = false;
  1444. }
  1445. }
  1446. };
  1447. localDef->mResolvedType = resolvedType;
  1448. localDef->mIsReadOnly = isReadOnly;
  1449. if (!initHandled)
  1450. {
  1451. if (isLet)
  1452. {
  1453. localDef->mIsReadOnly = true;
  1454. if (initValue)
  1455. {
  1456. if ((initValue.mValue) && (initValue.mValue.IsConst()))
  1457. {
  1458. isConst = true;
  1459. }
  1460. }
  1461. }
  1462. }
  1463. _CheckConst();
  1464. bool localNeedsAddr = false;
  1465. bool allowValueAccess = true;
  1466. if (mHasFullDebugInfo)
  1467. {
  1468. //if (!IsTargetingBeefBackend())
  1469. if (!isConst)
  1470. localNeedsAddr = true;
  1471. /*if (mCurMethodInstance->mMethodDef->mName != "Boop2")
  1472. dbgNeedsAddr = true;*/
  1473. }
  1474. // This is required because of lifetime and LLVM domination rules for certain instances of variable declarations in binary conditionals.
  1475. // IE: if ((something) && (let a = somethingElse))
  1476. if ((exprEvaluator != NULL) && (!isConst))
  1477. {
  1478. localNeedsAddr = true;
  1479. allowValueAccess = false;
  1480. }
  1481. if ((varDecl->mEqualsNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!initHandled))
  1482. {
  1483. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(varDecl->mEqualsNode, resolvedType);
  1484. }
  1485. BfIRInitType initType = BfIRInitType_NotSet;
  1486. if (varDecl->mInitializer != NULL)
  1487. {
  1488. initType = BfIRInitType_NotNeeded_AliveOnDecl;
  1489. if ((!initValue) && (!initHandled))
  1490. {
  1491. if ((isConst) || (isStatic))
  1492. {
  1493. BfConstResolver constResolver(this);
  1494. initValue = constResolver.Resolve(varDecl->mInitializer, resolvedType, BfConstResolveFlag_ActualizeValues);
  1495. if (!initValue)
  1496. initValue = GetDefaultTypedValue(resolvedType);
  1497. }
  1498. else if (varDecl->mInitializer->IsA<BfUninitializedExpression>())
  1499. {
  1500. // Fake 'is assigned'
  1501. }
  1502. else
  1503. { //
  1504. auto expectedType = resolvedType;
  1505. if (expectedType->IsRef())
  1506. expectedType = expectedType->GetUnderlyingType();
  1507. BfExprEvaluator valExprEvaluator(this);
  1508. valExprEvaluator.mAllowReadOnlyReference = isReadOnly;
  1509. initValue = CreateValueFromExpression(valExprEvaluator, varDecl->mInitializer, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_VariableDeclaration));
  1510. if ((initValue) && (resolvedType->IsUndefSizedArray()))
  1511. {
  1512. int stringId = GetStringPoolIdx(initValue.mValue, mBfIRBuilder);
  1513. if (stringId >= 0)
  1514. {
  1515. BfStringPoolEntry* entry = NULL;
  1516. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  1517. resolvedType = CreateSizedArrayType(((BfSizedArrayType*)resolvedType)->mElementType, entry->mString.mLength);
  1518. }
  1519. }
  1520. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1521. if (exprEvaluator != NULL)
  1522. _DoConditionalInit(expectedType);
  1523. if ((!handledVarInit) && (initValue))
  1524. initValue = Cast(varDecl->mInitializer, initValue, resolvedType, BfCastFlags_PreferAddr);
  1525. }
  1526. if ((initValue) && (resolvedType->IsUndefSizedArray()))
  1527. {
  1528. resolvedType = initValue.mType;
  1529. unresolvedType = resolvedType;
  1530. }
  1531. if (auto autoComplete = mCompiler->GetAutoComplete())
  1532. {
  1533. autoComplete->CheckResult(varDecl->mInitializer, initValue);
  1534. }
  1535. }
  1536. if ((!handledVarInit) && (!isConst))
  1537. {
  1538. if (initValue)
  1539. {
  1540. // Handled later
  1541. }
  1542. else if (varDecl->mInitializer->IsA<BfUninitializedExpression>())
  1543. {
  1544. // Fake 'is assigned'
  1545. initType = BfIRInitType_Uninitialized;
  1546. }
  1547. else
  1548. {
  1549. AssertErrorState();
  1550. }
  1551. }
  1552. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1553. }
  1554. else
  1555. {
  1556. if (isConst)
  1557. {
  1558. Fail("Const locals must be initialized", varDecl->mModSpecifier);
  1559. initValue = GetDefaultTypedValue(resolvedType, true);
  1560. }
  1561. else if (isReadOnly)
  1562. {
  1563. Fail("Readonly locals must be initialized", varDecl->mModSpecifier);
  1564. initValue = GetDefaultTypedValue(resolvedType, true);
  1565. }
  1566. else if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(varDecl->mTypeRef))
  1567. {
  1568. Fail("Ref locals must be initialized", refTypeRef->mRefToken);
  1569. }
  1570. else
  1571. {
  1572. BF_ASSERT(!resolvedType->IsRef());
  1573. }
  1574. }
  1575. PopulateType(resolvedType);
  1576. AddDependency(resolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  1577. localDef->mResolvedType = resolvedType;
  1578. _CheckConst();
  1579. if ((initValue.mKind == BfTypedValueKind_TempAddr) && (!initHandled))
  1580. {
  1581. BF_ASSERT(initValue.IsAddr());
  1582. BF_ASSERT(initValue.mType->IsComposite());
  1583. handledVarInit = true;
  1584. handledVarStore = true;
  1585. if (!localDef->mAddr)
  1586. {
  1587. localDef->mAddr = initValue.mValue;
  1588. if (localDef->mIsReadOnly)
  1589. localDef->mValue = mBfIRBuilder->CreateLoad(localDef->mAddr);
  1590. }
  1591. if (WantsLifetimes())
  1592. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(localDef->mAddr);
  1593. }
  1594. if ((!localDef->mAddr) && (!isConst) && (!isStatic) && ((!localDef->mIsReadOnly) || (localNeedsAddr)))
  1595. {
  1596. if ((exprEvaluator != NULL) && (exprEvaluator->mResultIsTempComposite))
  1597. {
  1598. //TODO: Can we remove this one?
  1599. BF_ASSERT(initValue.IsAddr());
  1600. BF_ASSERT(initValue.mType->IsComposite());
  1601. localDef->mAddr = initValue.mValue;
  1602. }
  1603. else
  1604. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1605. }
  1606. if (isStatic)
  1607. {
  1608. String name = mModuleName + "_" + mCurMethodInstance->mMethodDef->mName + "_" + localDef->mName;
  1609. HashContext closureHashCtx;
  1610. closureHashCtx.Mixin(varDecl->mSrcStart);
  1611. uint64 closureHash = closureHashCtx.Finish64();
  1612. name += "$";
  1613. name += BfTypeUtils::HashEncode64(closureHash);
  1614. initValue = LoadValue(initValue);
  1615. if ((initValue) && (!initValue.mValue.IsConst()))
  1616. {
  1617. Fail("Static local variables can only be initialized with a const value", varDecl->mInitializer);
  1618. initValue = BfTypedValue();
  1619. }
  1620. if (!initValue)
  1621. initValue = GetDefaultTypedValue(localDef->mResolvedType);
  1622. if (!localDef->mResolvedType->IsValuelessType())
  1623. localDef->mAddr = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(localDef->mResolvedType), false, BfIRLinkageType_Internal, initValue.mValue, name);;
  1624. initHandled = true;
  1625. }
  1626. bool wantsStore = false;
  1627. if ((initValue) && (!handledVarStore) && (!isConst) && (!initHandled))
  1628. {
  1629. initValue = LoadValue(initValue);
  1630. if (initValue.IsSplat())
  1631. {
  1632. BF_ASSERT(!mIsComptimeModule);
  1633. if (!localDef->mAddr)
  1634. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1635. AggregateSplatIntoAddr(initValue, localDef->mAddr);
  1636. initHandled = true;
  1637. }
  1638. else
  1639. {
  1640. initValue = AggregateSplat(initValue);
  1641. localDef->mValue = initValue.mValue;
  1642. if ((localDef->mAddr) && (!localDef->mResolvedType->IsValuelessType()))
  1643. {
  1644. if ((!initValue.mType->IsVar()) && (!initValue.mType->IsValuelessType()))
  1645. wantsStore = true;
  1646. }
  1647. else
  1648. {
  1649. BF_ASSERT(isReadOnly || isLet || initValue.mType->IsValuelessType() || (mBfIRBuilder->mIgnoreWrites));
  1650. }
  1651. }
  1652. }
  1653. if ((localDef->mIsReadOnly) && (!isConst) && (!localDef->mValue) && (!initHandled))
  1654. {
  1655. if (!resolvedType->IsValuelessType())
  1656. {
  1657. AssertErrorState();
  1658. initValue = GetDefaultTypedValue(resolvedType, true, BfDefaultValueKind_Undef);
  1659. localDef->mValue = initValue.mValue;
  1660. }
  1661. }
  1662. if ((!localDef->mAddr) && (!isConst) && ((!localDef->mIsReadOnly) || (localNeedsAddr)))
  1663. {
  1664. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1665. }
  1666. if ((exprEvaluator != NULL) && (!handledExprBoolResult))
  1667. {
  1668. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  1669. if (!initValue)
  1670. {
  1671. AssertErrorState();
  1672. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  1673. }
  1674. else if ((resolvedType->IsPointer()) || (resolvedType->IsObjectOrInterface()))
  1675. {
  1676. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateIsNotNull(initValue.mValue), boolType);
  1677. }
  1678. else if (resolvedType->IsVar())
  1679. {
  1680. exprEvaluator->mResult = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Undef);
  1681. }
  1682. else
  1683. {
  1684. // Always true
  1685. if ((!IsInSpecializedSection()) && (!resolvedType->IsGenericParam()))
  1686. Warn(BfWarning_CS0472_ValueTypeNullCompare, StrFormat("Variable declaration is always 'true' since a value of type '%s' can never be null",
  1687. TypeToString(initValue.mType).c_str()), varDecl);
  1688. exprEvaluator->mResult = BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  1689. }
  1690. }
  1691. if ((unresolvedType->IsGenericParam()) && (resolvedType->IsValuelessType()) && (mHasFullDebugInfo))
  1692. {
  1693. // We do this in order to be able to bind to lines that contain valueless variable declarations in some generics
  1694. // We don't need to do this in non-generics because the breakpoint will just move to the next line that actually has instructions
  1695. EmitEnsureInstructionAt();
  1696. }
  1697. if ((resolvedType->IsVoid()) && (!IsInSpecializedSection()))
  1698. {
  1699. Warn(0, StrFormat("Variable '%s' is declared as 'void'", localDef->mName.c_str()), varDecl->mTypeRef);
  1700. }
  1701. if ((!handledVarInit) && (isConst))
  1702. localDef->mConstValue = initValue.mValue;
  1703. if (!allowValueAccess)
  1704. localDef->mValue = BfIRValue();
  1705. if (!localDef->mIsShadow)
  1706. CheckVariableDef(localDef);
  1707. ValidateAllocation(localDef->mResolvedType, varDecl->mTypeRef);
  1708. if ((exprEvaluator == NULL) && (varDecl->GetSourceData() != NULL))
  1709. UpdateSrcPos(varDecl);
  1710. localDef->Init();
  1711. if (localDef->mConstValue)
  1712. initType = BfIRInitType_NotNeeded;
  1713. BfLocalVariable* localVar = AddLocalVariableDef(localDef, true, false, BfIRValue(), initType);
  1714. if (wantsStore)
  1715. mBfIRBuilder->CreateAlignedStore(initValue.mValue, localVar->mAddr, localVar->mResolvedType->mAlign);
  1716. if ((mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  1717. {
  1718. if (localDef->mValue.IsConst())
  1719. localDef->mConstValue = localDef->mValue;
  1720. }
  1721. return localVar;
  1722. }
  1723. BfLocalVariable* BfModule::HandleVariableDeclaration(BfType* type, BfAstNode* nameNode, BfTypedValue val, bool updateSrcLoc, bool forceAddr)
  1724. {
  1725. BfLocalVariable* localDef = new BfLocalVariable();
  1726. nameNode->ToString(localDef->mName);
  1727. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(nameNode);
  1728. localDef->mResolvedType = type;
  1729. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1730. localDef->mValue = val.mValue;
  1731. if ((!localDef->mIsReadOnly) || (mHasFullDebugInfo))
  1732. {
  1733. localDef->mAddr = AllocLocalVariable(localDef->mResolvedType, localDef->mName);
  1734. if ((val.mValue) && (!localDef->mResolvedType->IsValuelessType()) && (!localDef->mResolvedType->IsVar()))
  1735. {
  1736. if (localDef->mResolvedType->IsRef())
  1737. val = MakeAddressable(val, true, true);
  1738. if (val.IsSplat())
  1739. {
  1740. AggregateSplatIntoAddr(val, localDef->mAddr);
  1741. }
  1742. else
  1743. mBfIRBuilder->CreateAlignedStore(val.mValue, localDef->mAddr, localDef->mResolvedType->mAlign);
  1744. }
  1745. }
  1746. CheckVariableDef(localDef);
  1747. if (nameNode->GetSourceData() != NULL)
  1748. UpdateSrcPos(nameNode);
  1749. localDef->Init();
  1750. return AddLocalVariableDef(localDef, true);
  1751. }
  1752. BfLocalVariable* BfModule::HandleVariableDeclaration(BfVariableDeclaration* varDecl, BfTypedValue val, bool updateSrcLoc, bool forceAddr)
  1753. {
  1754. if (varDecl->mEqualsNode != NULL)
  1755. Fail("Unexpected initialization", varDecl->mEqualsNode);
  1756. if (varDecl->mInitializer != NULL)
  1757. CreateValueFromExpression(varDecl->mInitializer);
  1758. auto isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  1759. auto isVar = varDecl->mTypeRef->IsA<BfVarTypeReference>();
  1760. bool isRef = false;
  1761. if (auto varRefTypeReference = BfNodeDynCast<BfVarRefTypeReference>(varDecl->mTypeRef))
  1762. {
  1763. isRef = true;
  1764. isLet = varRefTypeReference->mVarToken->GetToken() == BfToken_Let;
  1765. isVar = varRefTypeReference->mVarToken->GetToken() == BfToken_Var;
  1766. }
  1767. else
  1768. {
  1769. BF_ASSERT(!val.IsAddr());
  1770. }
  1771. auto autoComplete = mCompiler->GetAutoComplete();
  1772. if ((autoComplete != NULL) && ((isLet) || (isVar)))
  1773. autoComplete->CheckVarResolution(varDecl->mTypeRef, val.mType);
  1774. // BfType* type = val.mType;
  1775. // if (type == NULL)
  1776. // {
  1777. // type = ResolveTypeRef(varDecl->mTypeRef);
  1778. // if (type == NULL)
  1779. // type = mContext->mBfObjectType;
  1780. // }
  1781. BfType* type = NULL;
  1782. if ((isLet) || (isVar))
  1783. {
  1784. type = val.mType;
  1785. }
  1786. else
  1787. {
  1788. type = ResolveTypeRef(varDecl->mTypeRef);
  1789. }
  1790. if (type == NULL)
  1791. {
  1792. type = GetPrimitiveType(BfTypeCode_Var);
  1793. val = GetDefaultTypedValue(type);
  1794. }
  1795. if ((type->IsVar()) || (type->IsLet()))
  1796. {
  1797. }
  1798. if (isRef)
  1799. {
  1800. type = CreateRefType(type);
  1801. }
  1802. BfLocalVariable* localDef = new BfLocalVariable();
  1803. if (varDecl->mNameNode != NULL)
  1804. varDecl->mNameNode->ToString(localDef->mName);
  1805. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  1806. localDef->mResolvedType = type;
  1807. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1808. localDef->mValue = val.mValue;
  1809. if (isLet)
  1810. {
  1811. localDef->mIsReadOnly = true;
  1812. }
  1813. if ((!localDef->mIsReadOnly) || (mHasFullDebugInfo) || (forceAddr))
  1814. {
  1815. localDef->mAddr = AllocLocalVariable(localDef->mResolvedType, localDef->mName);
  1816. if ((val.mValue) && (!localDef->mResolvedType->IsValuelessType()) && (!localDef->mResolvedType->IsVar()))
  1817. {
  1818. if (localDef->mResolvedType->IsRef())
  1819. val = MakeAddressable(val, true, true);
  1820. if (val.IsSplat())
  1821. {
  1822. AggregateSplatIntoAddr(val, localDef->mAddr);
  1823. }
  1824. else
  1825. mBfIRBuilder->CreateAlignedStore(val.mValue, localDef->mAddr, localDef->mResolvedType->mAlign);
  1826. }
  1827. if (forceAddr)
  1828. localDef->mValue = BfIRValue();
  1829. }
  1830. CheckVariableDef(localDef);
  1831. if ((updateSrcLoc) && (varDecl->GetSourceData() != NULL))
  1832. UpdateSrcPos(varDecl);
  1833. localDef->Init();
  1834. return AddLocalVariableDef(localDef, true);
  1835. }
  1836. void BfModule::CheckTupleVariableDeclaration(BfTupleExpression* tupleExpr, BfType* initType)
  1837. {
  1838. if (initType == NULL)
  1839. return;
  1840. BfTypeInstance* initTupleType = NULL;
  1841. if ((initType != NULL) && (initType->IsTuple()))
  1842. initTupleType = (BfTypeInstance*)initType;
  1843. if (initTupleType != NULL)
  1844. {
  1845. mBfIRBuilder->PopulateType(initTupleType);
  1846. AddDependency(initTupleType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  1847. int paramCountDiff = (int)tupleExpr->mValues.size() - (int)initTupleType->mFieldInstances.size();
  1848. if (paramCountDiff > 0)
  1849. {
  1850. Fail(StrFormat("Too many variable names, expected %d fewer.", paramCountDiff), tupleExpr->mValues[(int)initTupleType->mFieldInstances.size()]);
  1851. }
  1852. else if (paramCountDiff < 0)
  1853. {
  1854. BfAstNode* refNode = tupleExpr->mCloseParen;
  1855. if (refNode == NULL)
  1856. refNode = tupleExpr;
  1857. Fail(StrFormat("Too few variable names, expected %d more.", -paramCountDiff), refNode);
  1858. }
  1859. }
  1860. else
  1861. {
  1862. Fail(StrFormat("Value result type '%s' must be a tuple type to be applicable for tuple decomposition", TypeToString(initType).c_str()), tupleExpr);
  1863. }
  1864. }
  1865. void BfModule::HandleTupleVariableDeclaration(BfVariableDeclaration* varDecl, BfTupleExpression* tupleExpr, BfTypedValue initTupleValue, bool isReadOnly, bool isConst, bool forceAddr, BfIRBlock* declBlock)
  1866. {
  1867. BfTypeInstance* initTupleType = NULL;
  1868. if ((initTupleValue) && (initTupleValue.mType->IsTuple()))
  1869. initTupleType = (BfTypeInstance*)initTupleValue.mType;
  1870. CheckTupleVariableDeclaration(tupleExpr, initTupleValue.mType);
  1871. mBfIRBuilder->PopulateType(initTupleValue.mType);
  1872. for (int varIdx = 0; varIdx < (int)tupleExpr->mValues.size(); varIdx++)
  1873. {
  1874. BfType* resolvedType = NULL;
  1875. BfTypedValue initValue;
  1876. if ((initTupleType != NULL) && (varIdx < (int)initTupleType->mFieldInstances.size()))
  1877. {
  1878. auto fieldInstance = &initTupleType->mFieldInstances[varIdx];
  1879. auto fieldDef = fieldInstance->GetFieldDef();
  1880. resolvedType = fieldInstance->GetResolvedType();
  1881. if (fieldInstance->mDataIdx != -1)
  1882. {
  1883. if (initTupleValue.IsAddr())
  1884. {
  1885. initValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(initTupleValue.mValue, 0, fieldInstance->mDataIdx), resolvedType, true);
  1886. initValue = LoadValue(initValue);
  1887. }
  1888. else
  1889. initValue = ExtractValue(initTupleValue, fieldInstance, fieldInstance->mDataIdx);
  1890. }
  1891. BfTupleNameNode* tupleNameNode = NULL;
  1892. if (varIdx < (int)tupleExpr->mNames.size())
  1893. tupleNameNode = tupleExpr->mNames[varIdx];
  1894. if (!fieldDef->IsUnnamedTupleField())
  1895. {
  1896. if (tupleNameNode != NULL)
  1897. {
  1898. if (fieldDef->mName != tupleNameNode->mNameNode->ToString())
  1899. {
  1900. Fail(StrFormat("Mismatched tuple field name, expected '%s'", fieldDef->mName.c_str()), tupleNameNode->mNameNode);
  1901. }
  1902. }
  1903. }
  1904. else if ((tupleNameNode != NULL) && (tupleNameNode->mNameNode != NULL))
  1905. {
  1906. Fail(StrFormat("Unexpected tuple field name, expected unnamed tuple field", fieldDef->mName.c_str()), tupleNameNode->mNameNode);
  1907. }
  1908. }
  1909. else
  1910. {
  1911. resolvedType = mContext->mBfObjectType;
  1912. initValue = GetDefaultTypedValue(resolvedType);
  1913. }
  1914. BfExpression* varNameNode = tupleExpr->mValues[varIdx];
  1915. if (!varNameNode->IsExact<BfIdentifierNode>())
  1916. {
  1917. if (BfTupleExpression* innerTupleExpr = BfNodeDynCast<BfTupleExpression>(varNameNode))
  1918. {
  1919. HandleTupleVariableDeclaration(varDecl, innerTupleExpr, initValue, isReadOnly, isConst, false, declBlock);
  1920. }
  1921. else if (!varNameNode->IsExact<BfUninitializedExpression>())
  1922. Fail("Variable name expected", varNameNode);
  1923. continue;
  1924. }
  1925. bool initHandled = false;
  1926. BfLocalVariable* localDef = new BfLocalVariable();
  1927. varNameNode->ToString(localDef->mName);
  1928. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varNameNode);
  1929. localDef->mResolvedType = resolvedType;
  1930. localDef->mReadFromId = 0; // Don't give usage errors for binds
  1931. if (isReadOnly)
  1932. {
  1933. localDef->mIsReadOnly = true;
  1934. if ((initValue) && (initValue.mValue.IsConst()))
  1935. {
  1936. isConst = true;
  1937. }
  1938. }
  1939. CheckVariableDef(localDef);
  1940. if ((!isConst) && ((forceAddr) || (!localDef->mIsReadOnly) || (mHasFullDebugInfo)))
  1941. {
  1942. localDef->mAddr = AllocLocalVariable(resolvedType, localDef->mName);
  1943. }
  1944. if ((varDecl != NULL) && (varDecl->mEqualsNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!initHandled))
  1945. {
  1946. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(varDecl->mEqualsNode, resolvedType);
  1947. }
  1948. if ((varDecl == NULL) || (varDecl->mInitializer != NULL))
  1949. {
  1950. if ((!isConst) && (!initHandled))
  1951. {
  1952. if (initValue)
  1953. {
  1954. if (!forceAddr)
  1955. localDef->mValue = initValue.mValue;
  1956. if (localDef->mAddr)
  1957. {
  1958. mBfIRBuilder->CreateStore(initValue.mValue, localDef->mAddr);
  1959. }
  1960. }
  1961. else if ((varDecl == NULL) || (varDecl->mInitializer->IsA<BfUninitializedExpression>()))
  1962. {
  1963. // Fake 'is assigned'
  1964. }
  1965. else
  1966. {
  1967. AssertErrorState();
  1968. }
  1969. }
  1970. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1971. }
  1972. else if ((varDecl != NULL) && (varDecl->mInitializer == NULL))
  1973. {
  1974. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(varDecl->mTypeRef))
  1975. {
  1976. Fail("Ref variables must be initialized", refTypeRef->mRefToken);
  1977. }
  1978. else
  1979. {
  1980. BF_ASSERT(!localDef->mResolvedType->IsRef());
  1981. }
  1982. }
  1983. if (isConst)
  1984. localDef->mConstValue = initValue.mValue;
  1985. CheckVariableDef(localDef);
  1986. if ((varDecl != NULL) && (varDecl->GetSourceData() != NULL))
  1987. UpdateSrcPos(varDecl);
  1988. localDef->Init();
  1989. auto defBlock = mBfIRBuilder->GetInsertBlock();
  1990. if (declBlock != NULL)
  1991. mBfIRBuilder->SetInsertPoint(*declBlock);
  1992. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded);
  1993. if (declBlock != NULL)
  1994. mBfIRBuilder->SetInsertPoint(defBlock);
  1995. }
  1996. }
  1997. void BfModule::HandleTupleVariableDeclaration(BfVariableDeclaration* varDecl)
  1998. {
  1999. BfAutoComplete* bfAutocomplete = mCompiler->GetAutoComplete();
  2000. if (bfAutocomplete != NULL)
  2001. bfAutocomplete->CheckTypeRef(varDecl->mTypeRef, true);
  2002. BfTupleExpression* tupleExpr = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  2003. bool isConst = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_Const);
  2004. bool isReadOnly = (varDecl->mModSpecifier != NULL) && (varDecl->mModSpecifier->GetToken() == BfToken_ReadOnly);
  2005. BfTypedValue initTupleValue;
  2006. bool hadVarType = false;
  2007. bool isLet = varDecl->mTypeRef->IsA<BfLetTypeReference>();
  2008. bool isVar = varDecl->mTypeRef->IsA<BfVarTypeReference>();
  2009. bool wasVarOrLet = isVar || isLet;
  2010. if ((!isLet) && (!isVar))
  2011. {
  2012. ResolveTypeRef(varDecl->mTypeRef);
  2013. Fail("'var' or 'let' expected", varDecl->mTypeRef);
  2014. isVar = true;
  2015. }
  2016. if ((isVar) || (isLet))
  2017. {
  2018. hadVarType = true;
  2019. if (varDecl->mInitializer == NULL)
  2020. {
  2021. Fail("Implicitly-typed variables must be initialized", varDecl);
  2022. initTupleValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2023. }
  2024. else
  2025. {
  2026. if (isConst)
  2027. {
  2028. BfConstResolver constResolver(this);
  2029. initTupleValue = constResolver.Resolve(varDecl->mInitializer);
  2030. }
  2031. else
  2032. {
  2033. initTupleValue = CreateValueFromExpression(varDecl->mInitializer, NULL);
  2034. }
  2035. }
  2036. initTupleValue = LoadValue(initTupleValue);
  2037. if ((bfAutocomplete != NULL) && (wasVarOrLet))
  2038. bfAutocomplete->CheckVarResolution(varDecl->mTypeRef, initTupleValue.mType);
  2039. }
  2040. bool isCompatible = false;
  2041. if (initTupleValue)
  2042. HandleTupleVariableDeclaration(varDecl, tupleExpr, initTupleValue, isLet || isReadOnly, isConst, false);
  2043. else
  2044. AssertErrorState();
  2045. }
  2046. void BfModule::HandleCaseEnumMatch_Tuple(BfTypedValue tupleVal, const BfSizedArray<BfExpression*>& arguments, BfAstNode* tooFewRef, BfIRValue phiVal, BfIRBlock& matchedBlockStart, BfIRBlock& matchedBlockEnd, BfIRBlock& falseBlockStart, BfIRBlock& falseBlockEnd, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2047. {
  2048. SetAndRestoreValue<bool> prevInCondBlock(mCurMethodState->mInConditionalBlock);
  2049. auto tupleType = tupleVal.mType->ToTypeInstance();
  2050. struct DeferredAssign
  2051. {
  2052. BfExpression* mExpr;
  2053. BfTypedValue mArgValue;
  2054. BfTypedValue mTupleElement;
  2055. int mFieldIdx;
  2056. bool mIsOut;
  2057. };
  2058. Array<DeferredAssign> deferredAssigns;
  2059. auto autoComplete = mCompiler->GetAutoComplete();
  2060. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  2061. {
  2062. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  2063. if (tupleFieldIdx >= arguments.size())
  2064. {
  2065. BfError* error = Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)arguments.size()), tooFewRef);
  2066. break;
  2067. }
  2068. BfTypedValue tupleElement;
  2069. if (tupleFieldInstance->mDataIdx >= 0)
  2070. {
  2071. tupleElement = ExtractValue(tupleVal, tupleFieldInstance, tupleFieldInstance->mDataIdx);
  2072. }
  2073. else
  2074. tupleElement = GetDefaultTypedValue(tupleFieldInstance->GetResolvedType());
  2075. auto expr = BfNodeDynCast<BfExpression>(arguments[tupleFieldIdx]);
  2076. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2077. {
  2078. bool isVarOrLet = (varDecl->mTypeRef->IsExact<BfLetTypeReference>()) || (varDecl->mTypeRef->IsExact<BfVarTypeReference>());
  2079. bool isRef = false;
  2080. if (varDecl->mTypeRef->IsExact<BfVarRefTypeReference>())
  2081. {
  2082. isVarOrLet = true;
  2083. isRef = true;
  2084. }
  2085. if (!isVarOrLet)
  2086. {
  2087. auto wantType = ResolveTypeRef(varDecl->mTypeRef);
  2088. if (wantType == NULL)
  2089. wantType = mContext->mBfObjectType;
  2090. if (wantType != NULL)
  2091. tupleElement = Cast(varDecl->mTypeRef, tupleElement, wantType);
  2092. if (!tupleElement)
  2093. tupleElement = GetDefaultTypedValue(wantType);
  2094. }
  2095. PopulateType(tupleElement.mType);
  2096. if (!isRef)
  2097. tupleElement = LoadValue(tupleElement);
  2098. if (prevHadFallthrough)
  2099. Fail("Destructuring cannot be used when the previous case contains a fallthrough", expr);
  2100. auto localVar = HandleVariableDeclaration(varDecl, tupleElement, false, true);
  2101. localVar->mReadFromId = 0; // Don't give usage errors for binds
  2102. continue;
  2103. }
  2104. if (auto binOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(expr))
  2105. {
  2106. if (binOpExpr->mOp == BfBinaryOp_Multiply)
  2107. {
  2108. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  2109. auto resolvedType = ResolveTypeRef(binOpExpr->mLeft, NULL);
  2110. prevIgnoreError.Restore();
  2111. if (resolvedType != NULL)
  2112. {
  2113. resolvedType = CreatePointerType(resolvedType);
  2114. PopulateType(tupleElement.mType);
  2115. tupleElement = LoadValue(tupleElement);
  2116. tupleElement = Cast(binOpExpr->mLeft, tupleElement, resolvedType);
  2117. if (prevHadFallthrough)
  2118. Fail("Destructuring cannot be used when the previous case contains a fallthrough", expr);
  2119. auto localVar = HandleVariableDeclaration(resolvedType, binOpExpr->mRight, tupleElement, false, true);
  2120. localVar->mReadFromId = 0; // Don't give usage errors for binds
  2121. continue;
  2122. }
  2123. }
  2124. }
  2125. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  2126. {
  2127. continue;
  2128. }
  2129. if (tupleFieldInstance->mDataIdx >= 0)
  2130. {
  2131. if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  2132. {
  2133. if (tupleElement.mType->IsTuple())
  2134. {
  2135. BfAstNode* tooFewRef = tupleExpr->mCloseParen;
  2136. if (tupleExpr->mValues.size() > 0)
  2137. tooFewRef = tupleExpr->mValues[tupleExpr->mValues.size() - 1];
  2138. if (tooFewRef == NULL)
  2139. tooFewRef = tupleExpr->mOpenParen;
  2140. HandleCaseEnumMatch_Tuple(tupleElement, tupleExpr->mValues, tooFewRef, phiVal, matchedBlockStart, matchedBlockEnd, falseBlockStart, falseBlockEnd, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2141. continue;
  2142. }
  2143. }
  2144. }
  2145. if (expr == NULL)
  2146. {
  2147. // Error would have occured in the parser
  2148. //AssertErrorState();
  2149. }
  2150. else
  2151. {
  2152. mCurMethodState->mInConditionalBlock = true;
  2153. auto tupleElementAddr = tupleElement;
  2154. BfTypedValue exprResult;
  2155. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(expr))
  2156. {
  2157. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  2158. {
  2159. if (memberRefExpr->mTarget == NULL)
  2160. {
  2161. if (tupleElement.mType->IsPayloadEnum())
  2162. {
  2163. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  2164. BfTypedValue enumTagVal;
  2165. if (tupleElement.IsAddr())
  2166. {
  2167. enumTagVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(tupleElement.mValue, 0, 2), intType, true);
  2168. enumTagVal = LoadValue(enumTagVal);
  2169. }
  2170. else
  2171. enumTagVal = BfTypedValue(mBfIRBuilder->CreateExtractValue(tupleElement.mValue, 2), intType, false);
  2172. int uncondTagId = -1;
  2173. bool hadConditional = false;
  2174. exprResult = TryCaseEnumMatch(tupleElementAddr, enumTagVal, expr, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2175. }
  2176. }
  2177. }
  2178. }
  2179. if (!exprResult)
  2180. {
  2181. tupleElement = LoadValue(tupleElement);
  2182. bool isMatchedBlockEnd = matchedBlockEnd == mBfIRBuilder->GetInsertBlock();
  2183. bool isFalseBlockEnd = falseBlockEnd == mBfIRBuilder->GetInsertBlock();
  2184. BfExprEvaluator exprEvaluator(this);
  2185. exprEvaluator.mExpectingType = tupleFieldInstance->GetResolvedType();
  2186. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowOutExpr | BfEvalExprFlags_AllowRefExpr);
  2187. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  2188. {
  2189. SetAndRestoreValue<bool> prevIsIfCondition(mCurMethodState->mDeferredLocalAssignData->mIsIfCondition, true);
  2190. SetAndRestoreValue<bool> prevIfMayBeSkipped(mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped, true);
  2191. exprEvaluator.Evaluate(expr);
  2192. }
  2193. else
  2194. {
  2195. exprEvaluator.Evaluate(expr);
  2196. }
  2197. if (isMatchedBlockEnd)
  2198. matchedBlockEnd = mBfIRBuilder->GetInsertBlock();
  2199. if (isFalseBlockEnd)
  2200. falseBlockEnd = mBfIRBuilder->GetInsertBlock();
  2201. auto argValue = exprEvaluator.mResult;
  2202. if (!argValue)
  2203. continue;
  2204. if (argValue.mType->IsRef())
  2205. {
  2206. auto refType = (BfRefType*)argValue.mType;
  2207. bool isOut = refType->mRefKind == BfRefType::RefKind_Out;
  2208. if ((refType->mRefKind != BfRefType::RefKind_Out) && (refType->mRefKind != BfRefType::RefKind_Ref))
  2209. {
  2210. BfAstNode* refNode = expr;
  2211. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(expr))
  2212. refNode = unaryOperatorExpr->mOpToken;
  2213. Fail("Invalid ref type", refNode);
  2214. }
  2215. DeferredAssign deferredAssign = { expr, argValue, tupleElement, tupleFieldIdx, isOut };
  2216. deferredAssigns.push_back(deferredAssign);
  2217. if (isOut)
  2218. {
  2219. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  2220. {
  2221. SetAndRestoreValue<bool> prevIsIfCondition(mCurMethodState->mDeferredLocalAssignData->mIsIfCondition, true);
  2222. SetAndRestoreValue<bool> prevIfMayBeSkipped(mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped, true);
  2223. exprEvaluator.MarkResultAssigned();
  2224. }
  2225. else
  2226. {
  2227. exprEvaluator.MarkResultAssigned();
  2228. }
  2229. }
  2230. continue;
  2231. }
  2232. if (!argValue.mType->IsValueType())
  2233. argValue = LoadValue(argValue);
  2234. argValue = Cast(expr, argValue, tupleFieldInstance->GetResolvedType());
  2235. if (!argValue)
  2236. continue;
  2237. exprEvaluator.PerformBinaryOperation(expr, expr, BfBinaryOp_Equality, expr, BfBinOpFlag_NoClassify, tupleElement, argValue);
  2238. exprResult = exprEvaluator.mResult;
  2239. }
  2240. if (exprResult)
  2241. {
  2242. hadConditional = true;
  2243. if (phiVal)
  2244. {
  2245. auto insertBlock = mBfIRBuilder->GetInsertBlock();
  2246. mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), insertBlock);
  2247. }
  2248. matchedBlockStart = matchedBlockEnd = mBfIRBuilder->CreateBlock("match", false);
  2249. mBfIRBuilder->CreateCondBr(exprResult.mValue, matchedBlockStart, falseBlockStart);
  2250. mBfIRBuilder->AddBlock(matchedBlockStart);
  2251. mBfIRBuilder->SetInsertPoint(matchedBlockStart);
  2252. }
  2253. }
  2254. }
  2255. if (!deferredAssigns.empty())
  2256. mBfIRBuilder->SetInsertPoint(matchedBlockEnd);
  2257. // We assign these only after the value checks succeed
  2258. for (auto& deferredAssign : deferredAssigns)
  2259. {
  2260. auto argValue = RemoveRef(deferredAssign.mArgValue);
  2261. auto tupleElement = Cast(deferredAssign.mExpr, deferredAssign.mTupleElement, argValue.mType);
  2262. if (!tupleElement)
  2263. continue;
  2264. tupleElement = LoadOrAggregateValue(tupleElement);
  2265. if (!tupleElement.mType->IsValuelessType())
  2266. mBfIRBuilder->CreateStore(tupleElement.mValue, argValue.mValue);
  2267. }
  2268. if ((clearOutOnMismatch) && (!deferredAssigns.IsEmpty()))
  2269. {
  2270. auto curInsertPoint = mBfIRBuilder->GetInsertBlock();
  2271. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2272. for (auto& deferredAssign : deferredAssigns)
  2273. {
  2274. if (!deferredAssign.mIsOut)
  2275. continue;
  2276. auto tupleFieldInstance = &tupleType->mFieldInstances[deferredAssign.mFieldIdx];
  2277. // We have to re-process the expr because we haven't done it in this branch, and then clear the result out
  2278. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, mHadBuildError); // Don't fail twice
  2279. BfExprEvaluator exprEvaluator(this);
  2280. exprEvaluator.mExpectingType = tupleFieldInstance->GetResolvedType();
  2281. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowOutExpr;
  2282. exprEvaluator.Evaluate(deferredAssign.mExpr);
  2283. auto argValue = exprEvaluator.mResult;
  2284. if (!argValue)
  2285. continue;
  2286. mBfIRBuilder->CreateMemSet(argValue.mValue, GetConstValue8(0), GetConstValue(argValue.mType->mSize), GetConstValue(argValue.mType->mAlign));
  2287. }
  2288. falseBlockEnd = mBfIRBuilder->GetInsertBlock();
  2289. mBfIRBuilder->SetInsertPoint(curInsertPoint);
  2290. }
  2291. if (arguments.size() > tupleType->mFieldInstances.size())
  2292. {
  2293. for (int i = (int)tupleType->mFieldInstances.size(); i < (int)arguments.size(); i++)
  2294. {
  2295. // For autocomplete and such
  2296. auto expr = arguments[i];
  2297. if (expr != NULL)
  2298. CreateValueFromExpression(expr);
  2299. }
  2300. BfAstNode* errorRef = arguments[(int)tupleType->mFieldInstances.size()];
  2301. BfError* error = Fail(StrFormat("Too many arguments, expected %d fewer.", arguments.size() - tupleType->mFieldInstances.size()), errorRef);
  2302. }
  2303. }
  2304. BfTypedValue BfModule::TryCaseTupleMatch(BfTypedValue tupleVal, BfTupleExpression* tupleExpr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2305. {
  2306. if (!tupleVal.mType->IsTuple())
  2307. return BfTypedValue();
  2308. auto tupleType = (BfTypeInstance*)tupleVal.mType;
  2309. BfAstNode* tooFewRef = tupleExpr->mCloseParen;
  2310. if ((tooFewRef == NULL) && (!tupleExpr->mCommas.IsEmpty()))
  2311. tooFewRef = tupleExpr->mCommas[tupleExpr->mCommas.size() - 1];
  2312. else if (tooFewRef == NULL)
  2313. tooFewRef = tupleExpr->mOpenParen;
  2314. ///
  2315. auto autoComplete = mCompiler->GetAutoComplete();
  2316. bool wasCapturingMethodInfo = false;
  2317. if (autoComplete != NULL)
  2318. {
  2319. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  2320. autoComplete->CheckInvocation(tupleExpr, tupleExpr->mOpenParen, tupleExpr->mCloseParen, tupleExpr->mCommas);
  2321. if (autoComplete->mIsCapturingMethodMatchInfo)
  2322. {
  2323. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  2324. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2325. // auto methodDef = tupleType->mTypeDef->mMethods[0];
  2326. //
  2327. // BfAutoComplete::MethodMatchEntry methodMatchEntry;
  2328. // methodMatchEntry.mMethodDef = methodDef;
  2329. // methodMatchEntry.mTypeInstance = tupleType;
  2330. // methodMatchEntry.mCurMethodInstance = mCurMethodInstance;
  2331. // //methodMatchEntry.mPayloadEnumField = fieldInstance;
  2332. //autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  2333. methodMatchInfo->mBestIdx = 0;
  2334. methodMatchInfo->mMostParamsMatched = 0;
  2335. int cursorIdx = tupleExpr->GetParser()->mCursorIdx;
  2336. if ((tupleExpr->mCloseParen == NULL) || (cursorIdx <= tupleExpr->mCloseParen->GetSrcStart()))
  2337. {
  2338. int paramIdx = 0;
  2339. for (int commaIdx = 0; commaIdx < (int)tupleExpr->mCommas.size(); commaIdx++)
  2340. {
  2341. auto commaNode = tupleExpr->mCommas[commaIdx];
  2342. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  2343. paramIdx = commaIdx + 1;
  2344. }
  2345. bool isEmpty = true;
  2346. if (paramIdx < (int)tupleExpr->mValues.size())
  2347. {
  2348. auto paramNode = tupleExpr->mValues[paramIdx];
  2349. if (paramNode != NULL)
  2350. isEmpty = false;
  2351. }
  2352. if (isEmpty)
  2353. {
  2354. if (paramIdx < (int)tupleType->mFieldInstances.size())
  2355. {
  2356. auto fieldDef = tupleType->mFieldInstances[paramIdx].GetFieldDef();
  2357. String insertStr;
  2358. if (fieldDef->IsUnnamedTupleField())
  2359. insertStr = "p";
  2360. insertStr += fieldDef->mName;
  2361. insertStr.Insert(0, "let ");
  2362. autoComplete->mEntriesSet.Clear();
  2363. autoComplete->AddEntry(AutoCompleteEntry("paramName", insertStr));
  2364. autoComplete->mInsertStartIdx = cursorIdx;
  2365. autoComplete->mInsertEndIdx = cursorIdx;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. defer
  2372. (
  2373. if (autoComplete != NULL)
  2374. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  2375. );
  2376. ///
  2377. //BfIRValue phiVal;
  2378. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2379. //phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  2380. auto startBlock = mBfIRBuilder->GetInsertBlock();
  2381. //auto dscrType = enumType->GetDiscriminatorType();
  2382. //BfIRValue eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagId));
  2383. BfIRBlock falseBlockStart;
  2384. BfIRBlock falseBlockEnd;
  2385. BfIRBlock doneBlockStart;
  2386. if (notEqBlock != NULL)
  2387. doneBlockStart = *notEqBlock;
  2388. else
  2389. doneBlockStart = mBfIRBuilder->CreateBlock("caseDone", false);
  2390. BfIRBlock doneBlockEnd = doneBlockStart;
  2391. if (clearOutOnMismatch)
  2392. {
  2393. falseBlockStart = falseBlockEnd = mBfIRBuilder->CreateBlock("caseNotEq", false);
  2394. mBfIRBuilder->AddBlock(falseBlockStart);
  2395. }
  2396. BfIRBlock matchedBlockStart = mBfIRBuilder->CreateBlock("caseMatch", false);
  2397. if (matchBlock != NULL)
  2398. *matchBlock = matchedBlockStart;
  2399. mBfIRBuilder->CreateBr(matchedBlockStart);
  2400. mBfIRBuilder->AddBlock(matchedBlockStart);
  2401. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2402. BfIRValue phiVal;
  2403. if (eqBlock == NULL)
  2404. phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 2);
  2405. mBfIRBuilder->SetInsertPoint(matchedBlockStart);
  2406. BfIRBlock matchedBlockEnd = matchedBlockStart;
  2407. HandleCaseEnumMatch_Tuple(tupleVal, tupleExpr->mValues, tooFewRef, falseBlockStart ? BfIRValue() : phiVal, matchedBlockStart, matchedBlockEnd,
  2408. falseBlockStart ? falseBlockStart : doneBlockStart, falseBlockEnd ? falseBlockEnd : doneBlockEnd, hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2409. if (phiVal)
  2410. {
  2411. auto falseVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2412. if (falseBlockEnd)
  2413. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, falseBlockEnd);
  2414. auto trueVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1);
  2415. mBfIRBuilder->AddPhiIncoming(phiVal, trueVal, matchedBlockEnd);
  2416. }
  2417. if (eqBlock != NULL)
  2418. mBfIRBuilder->CreateBr(*eqBlock);
  2419. else
  2420. mBfIRBuilder->CreateBr(doneBlockStart);
  2421. if (falseBlockEnd)
  2422. {
  2423. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2424. mBfIRBuilder->CreateBr(doneBlockStart);
  2425. //mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), falseBlock);
  2426. }
  2427. mBfIRBuilder->AddBlock(doneBlockStart);
  2428. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2429. if (phiVal)
  2430. return BfTypedValue(phiVal, boolType);
  2431. else
  2432. return GetDefaultTypedValue(boolType);
  2433. }
  2434. BfTypedValue BfModule::TryCaseEnumMatch(BfTypedValue enumVal, BfTypedValue tagVal, BfExpression* expr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, int& tagId, bool& hadConditional, bool clearOutOnMismatch, bool prevHadFallthrough)
  2435. {
  2436. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(expr);
  2437. if (invocationExpr == NULL)
  2438. return BfTypedValue();
  2439. auto activeTypeDef = GetActiveTypeDef();
  2440. BfType* targetType = NULL;
  2441. BfIdentifierNode* nameNode = NULL;
  2442. BfTokenNode* dotNode = NULL;
  2443. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  2444. {
  2445. if (memberRefExpr->mTarget == NULL)
  2446. {
  2447. targetType = enumVal.mType;
  2448. }
  2449. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  2450. {
  2451. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2452. targetType = ResolveTypeRef(typeRef);
  2453. }
  2454. else if (auto identifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget))
  2455. {
  2456. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2457. targetType = ResolveTypeRef(identifier, NULL);
  2458. }
  2459. if (auto nameIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  2460. {
  2461. dotNode = memberRefExpr->mDotToken;
  2462. nameNode = nameIdentifier;
  2463. }
  2464. else
  2465. return BfTypedValue();
  2466. }
  2467. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(invocationExpr->mTarget))
  2468. {
  2469. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2470. targetType = ResolveTypeRef(qualifiedNameNode->mLeft, NULL);
  2471. nameNode = qualifiedNameNode->mRight;
  2472. }
  2473. else if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(invocationExpr->mTarget))
  2474. {
  2475. targetType = mCurTypeInstance;
  2476. nameNode = identiferNode;
  2477. }
  2478. else
  2479. return BfTypedValue();
  2480. // These may have been colorized as methods, so change that
  2481. SetElementType(nameNode, BfSourceElementType_Normal);
  2482. if ((targetType == NULL) || (!targetType->IsPayloadEnum()))
  2483. return BfTypedValue();
  2484. auto enumType = targetType->ToTypeInstance();
  2485. PopulateType(enumType);
  2486. StringT<128> enumCaseName;
  2487. if (nameNode != NULL)
  2488. nameNode->ToString(enumCaseName);
  2489. auto tagType = GetPrimitiveType(BfTypeCode_Int32);
  2490. if (enumVal.mType != enumType)
  2491. {
  2492. Fail(StrFormat("Cannot match enum type '%s' with type '%s'",
  2493. TypeToString(enumVal.mType).c_str(), TypeToString(enumType).c_str()));
  2494. enumVal = GetDefaultTypedValue(enumType);
  2495. tagVal = GetDefaultTypedValue(tagType);
  2496. }
  2497. BfIRValue eqResult;
  2498. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  2499. {
  2500. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  2501. auto fieldDef = fieldInstance->GetFieldDef();
  2502. if (fieldDef == NULL)
  2503. continue;
  2504. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == enumCaseName))
  2505. {
  2506. if (!IsInSpecializedSection())
  2507. {
  2508. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, this)) ||
  2509. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  2510. continue;
  2511. }
  2512. auto resolvePassData = mCompiler->mResolvePassData;
  2513. if (resolvePassData != NULL)
  2514. {
  2515. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  2516. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  2517. String filter;
  2518. auto autoComplete = resolvePassData->mAutoComplete;
  2519. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  2520. autoComplete->AddEnumTypeMembers(enumType, enumCaseName, false, enumType == mCurTypeInstance);
  2521. }
  2522. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  2523. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  2524. PopulateType(tupleType);
  2525. mBfIRBuilder->PopulateType(tupleType);
  2526. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2527. tagId = -fieldInstance->mDataIdx - 1;
  2528. auto startBlock = mBfIRBuilder->GetInsertBlock();
  2529. auto dscrType = enumType->GetDiscriminatorType();
  2530. BfIRValue eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagId));
  2531. bool isConstMatch = false;
  2532. bool isConstIgnore = false;
  2533. if (auto constant = mBfIRBuilder->GetConstant(eqResult))
  2534. {
  2535. isConstMatch = constant->mBool;
  2536. isConstIgnore = !constant->mBool;
  2537. }
  2538. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites);
  2539. if (isConstIgnore)
  2540. mBfIRBuilder->mIgnoreWrites = true;
  2541. BfIRBlock falseBlockStart;
  2542. BfIRBlock falseBlockEnd;
  2543. BfIRBlock doneBlockStart;
  2544. BfIRBlock doneBlockEnd;
  2545. if (notEqBlock != NULL)
  2546. doneBlockStart = doneBlockEnd = *notEqBlock;
  2547. else
  2548. doneBlockStart = doneBlockEnd = mBfIRBuilder->CreateBlock("caseDone", false);
  2549. if (clearOutOnMismatch)
  2550. {
  2551. falseBlockStart = falseBlockEnd = mBfIRBuilder->CreateBlock("caseNotEq", false);
  2552. mBfIRBuilder->AddBlock(falseBlockStart);
  2553. }
  2554. BfIRBlock matchedBlockStart = mBfIRBuilder->CreateBlock("caseMatch", false);
  2555. BfIRBlock matchedBlockEnd = matchedBlockStart;
  2556. if (matchBlock != NULL)
  2557. *matchBlock = matchedBlockStart;
  2558. if (isConstMatch)
  2559. mBfIRBuilder->CreateBr(matchedBlockStart);
  2560. else
  2561. mBfIRBuilder->CreateCondBr(eqResult, matchedBlockStart, falseBlockStart ? falseBlockStart : doneBlockStart);
  2562. mBfIRBuilder->AddBlock(matchedBlockStart);
  2563. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2564. BfIRValue phiVal;
  2565. if ((eqBlock == NULL) && (!isConstIgnore) && (!isConstMatch))
  2566. phiVal = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(boolType), 1 + (int)tupleType->mFieldInstances.size());
  2567. mBfIRBuilder->SetInsertPoint(matchedBlockEnd);
  2568. BfTypedValue tupleVal;
  2569. if (!enumVal.IsAddr())
  2570. {
  2571. auto unionInnerType = enumType->GetUnionInnerType();
  2572. if (unionInnerType == tupleType)
  2573. {
  2574. tupleVal = ExtractValue(enumVal, NULL, 1);
  2575. }
  2576. }
  2577. if (!tupleVal)
  2578. {
  2579. if (!tupleType->IsValuelessType())
  2580. {
  2581. tupleVal = ExtractValue(enumVal, NULL, 1);
  2582. tupleVal = Cast(NULL, tupleVal, tupleType, BfCastFlags_Force);
  2583. }
  2584. else
  2585. tupleVal = GetDefaultTypedValue(tupleType);
  2586. }
  2587. ////
  2588. BfAstNode* tooFewRef = invocationExpr->mCloseParen;
  2589. if ((tooFewRef == NULL) && (!invocationExpr->mCommas.IsEmpty()))
  2590. tooFewRef = invocationExpr->mCommas[invocationExpr->mCommas.size() - 1];
  2591. else if (tooFewRef == NULL)
  2592. tooFewRef = invocationExpr->mOpenParen;
  2593. ///
  2594. auto autoComplete = mCompiler->GetAutoComplete();
  2595. bool wasCapturingMethodInfo = false;
  2596. if (autoComplete != NULL)
  2597. {
  2598. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  2599. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  2600. if (autoComplete->mIsCapturingMethodMatchInfo)
  2601. {
  2602. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  2603. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2604. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  2605. methodMatchEntry.mTypeInstance = enumType;
  2606. methodMatchEntry.mCurMethodInstance = mCurMethodInstance;
  2607. methodMatchEntry.mPayloadEnumField = fieldInstance;
  2608. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  2609. methodMatchInfo->mBestIdx = 0;
  2610. methodMatchInfo->mMostParamsMatched = 0;
  2611. int cursorIdx = invocationExpr->GetParser()->mCursorIdx;
  2612. if ((invocationExpr->mCloseParen == NULL) || (cursorIdx <= invocationExpr->mCloseParen->GetSrcStart()))
  2613. {
  2614. int paramIdx = 0;
  2615. for (int commaIdx = 0; commaIdx < (int)invocationExpr->mCommas.size(); commaIdx++)
  2616. {
  2617. auto commaNode = invocationExpr->mCommas[commaIdx];
  2618. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  2619. paramIdx = commaIdx + 1;
  2620. }
  2621. bool isEmpty = true;
  2622. if (paramIdx < (int)invocationExpr->mArguments.size())
  2623. {
  2624. auto paramNode = invocationExpr->mArguments[paramIdx];
  2625. if (paramNode != NULL)
  2626. isEmpty = false;
  2627. }
  2628. if (isEmpty)
  2629. {
  2630. if (paramIdx < (int)tupleType->mFieldInstances.size())
  2631. {
  2632. auto fieldDef = tupleType->mFieldInstances[paramIdx].GetFieldDef();
  2633. String insertStr;
  2634. if (fieldDef->IsUnnamedTupleField())
  2635. insertStr = "p";
  2636. insertStr += fieldDef->mName;
  2637. insertStr.Insert(0, "let ");
  2638. autoComplete->mEntriesSet.Clear();
  2639. autoComplete->AddEntry(AutoCompleteEntry("paramName", insertStr));
  2640. autoComplete->mInsertStartIdx = cursorIdx;
  2641. autoComplete->mInsertEndIdx = cursorIdx;
  2642. }
  2643. }
  2644. }
  2645. }
  2646. }
  2647. defer
  2648. (
  2649. if (autoComplete != NULL)
  2650. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  2651. );
  2652. ///
  2653. HandleCaseEnumMatch_Tuple(tupleVal, invocationExpr->mArguments, tooFewRef, falseBlockStart ? BfIRValue() : phiVal, matchedBlockStart, matchedBlockEnd,
  2654. falseBlockStart ? falseBlockStart : doneBlockStart, falseBlockEnd ? falseBlockEnd : doneBlockEnd,
  2655. hadConditional, clearOutOnMismatch, prevHadFallthrough);
  2656. ///////
  2657. if (phiVal)
  2658. {
  2659. auto falseVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2660. if (falseBlockEnd)
  2661. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, falseBlockEnd);
  2662. else
  2663. mBfIRBuilder->AddPhiIncoming(phiVal, falseVal, startBlock);
  2664. auto trueVal = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1);
  2665. mBfIRBuilder->AddPhiIncoming(phiVal, trueVal, matchedBlockEnd);
  2666. }
  2667. if (eqBlock != NULL)
  2668. mBfIRBuilder->CreateBr(*eqBlock);
  2669. else
  2670. mBfIRBuilder->CreateBr(doneBlockStart);
  2671. if (falseBlockEnd)
  2672. {
  2673. mBfIRBuilder->SetInsertPoint(falseBlockEnd);
  2674. mBfIRBuilder->CreateBr(doneBlockStart);
  2675. //mBfIRBuilder->AddPhiIncoming(phiVal, mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), falseBlock);
  2676. }
  2677. mBfIRBuilder->AddBlock(doneBlockStart);
  2678. mBfIRBuilder->SetInsertPoint(doneBlockEnd);
  2679. if (phiVal)
  2680. return BfTypedValue(phiVal, boolType);
  2681. else if (eqResult)
  2682. return BfTypedValue(eqResult, boolType);
  2683. else
  2684. return GetDefaultTypedValue(boolType);
  2685. }
  2686. }
  2687. return BfTypedValue();
  2688. }
  2689. BfTypedValue BfModule::HandleCaseBind(BfTypedValue enumVal, const BfTypedValue& tagVal, BfEnumCaseBindExpression* bindExpr, BfIRBlock* eqBlock, BfIRBlock* notEqBlock, BfIRBlock* matchBlock, int* outEnumIdx)
  2690. {
  2691. BfTypeInstance* tupleType = NULL;
  2692. auto activeTypeDef = GetActiveTypeDef();
  2693. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  2694. BfIRValue eqResult;
  2695. if (bindExpr->mEnumMemberExpr != NULL)
  2696. {
  2697. int enumIdx = -1;
  2698. String findName;
  2699. BfType* type = NULL;
  2700. BfAstNode* targetNode = NULL;
  2701. BfAstNode* nameNode = NULL;
  2702. BfAstNode* dotNode = NULL;
  2703. if (auto memberExpr = BfNodeDynCast<BfMemberReferenceExpression>(bindExpr->mEnumMemberExpr))
  2704. {
  2705. dotNode = memberExpr->mDotToken;
  2706. if (memberExpr->mMemberName != NULL)
  2707. {
  2708. nameNode = memberExpr->mMemberName;
  2709. findName = memberExpr->mMemberName->ToString();
  2710. if (memberExpr->mTarget == NULL)
  2711. {
  2712. type = enumVal.mType;
  2713. }
  2714. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberExpr->mTarget))
  2715. {
  2716. type = ResolveTypeRef(typeRef);
  2717. }
  2718. }
  2719. targetNode = memberExpr->mTarget;
  2720. }
  2721. else if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(bindExpr->mEnumMemberExpr))
  2722. {
  2723. if (mCurTypeInstance->IsPayloadEnum())
  2724. {
  2725. nameNode = identiferNode;
  2726. findName = nameNode->ToString();
  2727. targetNode = identiferNode;
  2728. type = mCurTypeInstance;
  2729. }
  2730. else
  2731. {
  2732. Fail("Expected a qualified enum case name. Consider prefixing name with a dot to infer enum type name.", bindExpr->mEnumMemberExpr);
  2733. }
  2734. }
  2735. if (!findName.empty())
  2736. {
  2737. if (type != NULL)
  2738. {
  2739. if (type != enumVal.mType)
  2740. {
  2741. Fail(StrFormat("Enum case type '%s' does not match compared value of type '%s'",
  2742. TypeToString(enumVal.mType).c_str(), TypeToString(type).c_str()), targetNode);
  2743. }
  2744. if (type->IsEnum())
  2745. {
  2746. auto enumType = (BfTypeInstance*)type;
  2747. for (auto& fieldInstance : enumType->mFieldInstances)
  2748. {
  2749. auto fieldDef = fieldInstance.GetFieldDef();
  2750. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()) && (fieldDef->mName == findName))
  2751. {
  2752. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, this)) ||
  2753. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  2754. continue;
  2755. auto resolvePassData = mCompiler->mResolvePassData;
  2756. if (resolvePassData != NULL)
  2757. {
  2758. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  2759. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  2760. String filter;
  2761. auto autoComplete = resolvePassData->mAutoComplete;
  2762. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  2763. autoComplete->AddEnumTypeMembers(enumType, findName, false, enumType == mCurTypeInstance);
  2764. }
  2765. enumIdx = -fieldInstance.mDataIdx - 1;
  2766. if (outEnumIdx != NULL)
  2767. *outEnumIdx = enumIdx;
  2768. if (fieldInstance.mIsEnumPayloadCase)
  2769. tupleType = fieldInstance.mResolvedType->ToTypeInstance();
  2770. }
  2771. }
  2772. if (enumIdx == -1)
  2773. {
  2774. Fail("Enum case not found", nameNode);
  2775. }
  2776. }
  2777. else
  2778. {
  2779. Fail(StrFormat("Type '%s' is not an enum type", TypeToString(type).c_str()), targetNode);
  2780. }
  2781. }
  2782. }
  2783. BF_ASSERT(tagVal.mType->IsPrimitiveType());
  2784. eqResult = mBfIRBuilder->CreateCmpEQ(tagVal.mValue, mBfIRBuilder->CreateConst(((BfPrimitiveType*)tagVal.mType)->mTypeDef->mTypeCode, enumIdx));
  2785. }
  2786. else
  2787. {
  2788. eqResult = mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0);
  2789. }
  2790. BfIRBlock falseBlock;
  2791. if (notEqBlock != NULL)
  2792. {
  2793. falseBlock = *notEqBlock;
  2794. }
  2795. else
  2796. {
  2797. falseBlock = mBfIRBuilder->CreateBlock("notEqBlock", false);
  2798. }
  2799. auto mainBlock = mBfIRBuilder->GetInsertBlock();
  2800. BfIRBlock trueBlock = mBfIRBuilder->CreateBlock("eqBlock", false);
  2801. if (matchBlock != NULL)
  2802. *matchBlock = trueBlock;
  2803. mBfIRBuilder->AddBlock(trueBlock);
  2804. mBfIRBuilder->SetInsertPoint(trueBlock);
  2805. if ((tupleType != NULL) && (bindExpr->mBindNames != NULL))
  2806. {
  2807. BfIRValue valueScopeStart;
  2808. if (IsTargetingBeefBackend())
  2809. valueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  2810. bool isVar = bindExpr->mBindToken->GetToken() == BfToken_Var;
  2811. bool isLet = bindExpr->mBindToken->GetToken() == BfToken_Let;
  2812. BfTypedValue tupleVal;
  2813. if (enumVal.IsAddr())
  2814. {
  2815. auto ptrVal = mBfIRBuilder->CreateInBoundsGEP(enumVal.mValue, 0, 1);
  2816. tupleVal = BfTypedValue(mBfIRBuilder->CreateBitCast(ptrVal, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, true);
  2817. }
  2818. else
  2819. {
  2820. auto unionInnerType = enumVal.mType->ToTypeInstance()->GetUnionInnerType();
  2821. tupleVal = ExtractValue(enumVal, NULL, 1);
  2822. if (unionInnerType != tupleType)
  2823. {
  2824. tupleVal = MakeAddressable(tupleVal);
  2825. tupleVal = BfTypedValue(mBfIRBuilder->CreateBitCast(tupleVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, true);
  2826. }
  2827. }
  2828. HandleTupleVariableDeclaration(NULL, bindExpr->mBindNames, tupleVal, isLet, false, true /*, &mainBlock*/);
  2829. auto autoComplete = mCompiler->GetAutoComplete();
  2830. if ((autoComplete != NULL) && ((isVar || isLet)))
  2831. autoComplete->CheckVarResolution(bindExpr->mBindToken, tupleType);
  2832. if (valueScopeStart)
  2833. mBfIRBuilder->CreateValueScopeSoftEnd(valueScopeStart);
  2834. }
  2835. if (eqBlock != NULL)
  2836. mBfIRBuilder->CreateBr(*eqBlock);
  2837. else
  2838. mBfIRBuilder->CreateBr(falseBlock);
  2839. // Don't create the condBr until now, so HandleTupleVariableDeclaration can create the variable declarations in mainBlock--
  2840. // we need them there since the code that uses the new variables is created outside the eqBlock
  2841. mBfIRBuilder->SetInsertPoint(mainBlock);
  2842. mBfIRBuilder->CreateCondBr(eqResult, trueBlock, falseBlock);
  2843. mBfIRBuilder->AddBlock(falseBlock);
  2844. mBfIRBuilder->SetInsertPoint(falseBlock);
  2845. return BfTypedValue(eqResult, boolType);
  2846. }
  2847. void BfModule::AddBasicBlock(BfIRBlock bb, bool activate)
  2848. {
  2849. mBfIRBuilder->AddBlock(bb);
  2850. if (activate)
  2851. mBfIRBuilder->SetInsertPoint(bb);
  2852. }
  2853. void BfModule::VisitEmbeddedStatement(BfAstNode* stmt, BfExprEvaluator* exprEvaluator, BfEmbeddedStatementFlags flags)
  2854. {
  2855. if ((flags & BfEmbeddedStatementFlags_CheckStack) != 0)
  2856. {
  2857. BP_ZONE("BfModule.VisitEmbeddedStatement");
  2858. StackHelper stackHelper;
  2859. if (!stackHelper.CanStackExpand(64 * 1024))
  2860. {
  2861. if (!stackHelper.Execute([&]()
  2862. {
  2863. VisitEmbeddedStatement(stmt, exprEvaluator, flags);
  2864. }))
  2865. {
  2866. Fail("Statement too complex to parse", stmt);
  2867. }
  2868. return;
  2869. }
  2870. }
  2871. auto block = BfNodeDynCast<BfBlock>(stmt);
  2872. BfLabelNode* labelNode = NULL;
  2873. if (block == NULL)
  2874. {
  2875. auto labeledBlock = BfNodeDynCast<BfLabeledBlock>(stmt);
  2876. if (labeledBlock != NULL)
  2877. {
  2878. block = labeledBlock->mBlock;
  2879. labelNode = labeledBlock->mLabelNode;
  2880. }
  2881. }
  2882. BfAstNode* openBrace = NULL;
  2883. BfAstNode* closeBrace = NULL;
  2884. if (block != NULL)
  2885. {
  2886. openBrace = block->mOpenBrace;
  2887. closeBrace = block->mCloseBrace;
  2888. if (openBrace == NULL)
  2889. {
  2890. auto checkScope = mCurMethodState->mCurScope;
  2891. while ((checkScope != NULL) && (closeBrace == NULL))
  2892. {
  2893. closeBrace = checkScope->mCloseNode;
  2894. checkScope = checkScope->mPrevScope;
  2895. }
  2896. BF_ASSERT(closeBrace != NULL);
  2897. }
  2898. }
  2899. if ((block != NULL) && (openBrace != NULL))
  2900. UpdateSrcPos(openBrace);
  2901. if ((flags & BfEmbeddedStatementFlags_Unscoped) != 0)
  2902. {
  2903. SetAndRestoreValue<BfExprEvaluator*> prevExprEvaluator(mCurMethodState->mCurScope->mExprEvaluator, exprEvaluator);
  2904. SetAndRestoreValue<bool> prevAllowReturn(mCurMethodState->mDisableReturns, true);
  2905. VisitCodeBlock(block);
  2906. }
  2907. else if (mCurMethodState != NULL)
  2908. {
  2909. bool isIgnore = mBfIRBuilder->mIgnoreWrites;
  2910. mCurMethodState->mInHeadScope = false;
  2911. BfScopeData scopeData;
  2912. if (IsTargetingBeefBackend())
  2913. scopeData.mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  2914. mCurMethodState->AddScope(&scopeData);
  2915. if (block != NULL)
  2916. {
  2917. mCurMethodState->mCurScope->mAstBlock = block;
  2918. mCurMethodState->mCurScope->mCloseNode = closeBrace;
  2919. }
  2920. if (labelNode != NULL)
  2921. scopeData.mLabelNode = labelNode->mLabel;
  2922. NewScopeState(block != NULL);
  2923. mCurMethodState->mCurScope->mOuterIsConditional = (flags & BfEmbeddedStatementFlags_IsConditional) != 0;
  2924. mCurMethodState->mCurScope->mIsDeferredBlock = (flags & BfEmbeddedStatementFlags_IsDeferredBlock) != 0;
  2925. mCurMethodState->mCurScope->mExprEvaluator = exprEvaluator;
  2926. //
  2927. {
  2928. SetAndRestoreValue<bool> inDeferredBlock(mCurMethodState->mInDeferredBlock, mCurMethodState->mInDeferredBlock || mCurMethodState->mCurScope->mIsDeferredBlock);
  2929. if (block != NULL)
  2930. {
  2931. if (labelNode != NULL)
  2932. VisitCodeBlock(block, BfIRBlock(), BfIRBlock(), BfIRBlock(), false, NULL, labelNode);
  2933. else
  2934. VisitCodeBlock(block);
  2935. }
  2936. else
  2937. {
  2938. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(stmt))
  2939. {
  2940. Fail("Variable declarations must be wrapped in a block statement", varDecl);
  2941. }
  2942. VisitChild(stmt);
  2943. }
  2944. }
  2945. if ((block != NULL) && (closeBrace != NULL))
  2946. {
  2947. UpdateSrcPos(closeBrace);
  2948. if (!mCurMethodState->mLeftBlockUncond)
  2949. EmitEnsureInstructionAt();
  2950. }
  2951. if (block != NULL)
  2952. {
  2953. BfAutoParentNodeEntry autoParentNodeEntry(this, block);
  2954. RestoreScopeState();
  2955. }
  2956. else
  2957. RestoreScopeState();
  2958. BF_ASSERT(isIgnore == mBfIRBuilder->mIgnoreWrites);
  2959. }
  2960. else
  2961. {
  2962. if (block != NULL)
  2963. VisitCodeBlock(block);
  2964. else
  2965. VisitChild(stmt);
  2966. }
  2967. }
  2968. void BfModule::VisitCodeBlock(BfBlock* block, BfIRBlock continueBlock, BfIRBlock breakBlock, BfIRBlock fallthroughBlock, bool defaultBreak, bool* hadReturn, BfLabelNode* labelNode, bool closeScope, BfEmbeddedStatementFlags flags)
  2969. {
  2970. BfBreakData breakData;
  2971. breakData.mIRContinueBlock = continueBlock;
  2972. breakData.mIRBreakBlock = breakBlock;
  2973. breakData.mIRFallthroughBlock = fallthroughBlock;
  2974. breakData.mScope = mCurMethodState->mCurScope;
  2975. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  2976. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  2977. VisitEmbeddedStatement(block, NULL, flags);
  2978. if (closeScope)
  2979. RestoreScopeState();
  2980. if ((!mCurMethodState->mLeftBlockUncond) && (defaultBreak))
  2981. {
  2982. mBfIRBuilder->CreateBr(breakBlock);
  2983. }
  2984. if (hadReturn != NULL)
  2985. {
  2986. *hadReturn = mCurMethodState->mHadReturn;
  2987. mCurMethodState->SetHadReturn(false);
  2988. mCurMethodState->mLeftBlockUncond = false;
  2989. }
  2990. }
  2991. void BfModule::VisitCodeBlock(BfBlock* block)
  2992. {
  2993. //BP_ZONE("BfModule::VisitCodeBlock");
  2994. BfAutoParentNodeEntry autoParentNodeEntry(this, block);
  2995. BfIRBlock prevInsertBlock;
  2996. bool hadReturn = false;
  2997. int startLocalMethod = 0; // was -1
  2998. auto rootMethodState = mCurMethodState->GetRootMethodState();
  2999. BfIRBlock startInsertBlock = mBfIRBuilder->GetInsertBlock();
  3000. bool allowLocalMethods = mCurMethodInstance != NULL;
  3001. //int startDeferredLocalIdx = (int)rootMethodState->mDeferredLocalMethods.size();
  3002. int curLocalMethodIdx = -1;
  3003. // Scan for any local method declarations
  3004. if (allowLocalMethods)
  3005. {
  3006. startLocalMethod = (int)mCurMethodState->mLocalMethods.size();
  3007. curLocalMethodIdx = startLocalMethod;
  3008. auto itr = block->begin();
  3009. while (itr != block->end())
  3010. {
  3011. BfAstNode* child = *itr;
  3012. if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(child))
  3013. {
  3014. BfLocalMethod* localMethod;
  3015. auto rootMethodState = mCurMethodState->GetRootMethodState();
  3016. String methodName;
  3017. if (localMethodDecl->mMethodDeclaration->mNameNode != NULL)
  3018. {
  3019. methodName = GetLocalMethodName(localMethodDecl->mMethodDeclaration->mNameNode->ToString(), localMethodDecl->mMethodDeclaration->mOpenParen, mCurMethodState, mCurMethodState->mMixinState);
  3020. BfLocalMethod** localMethodPtr = NULL;
  3021. if (rootMethodState->mLocalMethodCache.TryGetValue(methodName, &localMethodPtr))
  3022. {
  3023. localMethod = *localMethodPtr;
  3024. }
  3025. else
  3026. {
  3027. localMethod = new BfLocalMethod();
  3028. localMethod->mSystem = mSystem;
  3029. localMethod->mModule = this;
  3030. localMethod->mMethodDeclaration = localMethodDecl->mMethodDeclaration;
  3031. localMethod->mSource = mCurTypeInstance->mTypeDef->mSource;
  3032. localMethod->mSource->mRefCount++;
  3033. if (mCurMethodState->mClosureState != NULL)
  3034. localMethod->mOuterLocalMethod = mCurMethodState->mClosureState->mLocalMethod;
  3035. auto autoComplete = mCompiler->GetAutoComplete();
  3036. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_Autocomplete))
  3037. {
  3038. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  3039. if (!autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration))
  3040. localMethod->mDeclOnly = true;
  3041. }
  3042. if (localMethod->mMethodDeclaration->mNameNode != NULL)
  3043. localMethod->mMethodName = localMethod->mMethodDeclaration->mNameNode->ToString();
  3044. localMethod->mExpectedFullName = methodName;
  3045. rootMethodState->mLocalMethodCache[methodName] = localMethod;
  3046. mContext->mLocalMethodGraveyard.push_back(localMethod);
  3047. }
  3048. BF_ASSERT(mCurMethodState->mCurScope != NULL);
  3049. localMethod->mDeclDIScope = mCurMethodState->mCurScope->mDIScope;
  3050. localMethod->mDeclMethodState = mCurMethodState;
  3051. localMethod->mDeclMixinState = mCurMethodState->mMixinState;
  3052. if (localMethod->mDeclMixinState != NULL)
  3053. localMethod->mDeclMixinState->mHasDeferredUsage = true;
  3054. mCurMethodState->mLocalMethods.push_back(localMethod);
  3055. String* namePtr;
  3056. if (!mCurMethodState->mLocalMethodMap.TryAdd(localMethod->mMethodName, &namePtr, &localMethodPtr))
  3057. {
  3058. BF_ASSERT(localMethod != *localMethodPtr);
  3059. localMethod->mNextWithSameName = *localMethodPtr;
  3060. }
  3061. *localMethodPtr = localMethod;
  3062. }
  3063. }
  3064. ++itr;
  3065. }
  3066. }
  3067. bool wantsAllLocalMethods = true;
  3068. auto autoComplete = mCompiler->GetAutoComplete();
  3069. if (autoComplete != NULL)
  3070. {
  3071. // If we only need reasoning "at the cursor" then we don't need all local methods
  3072. if ((!autoComplete->mIsAutoComplete) ||
  3073. (autoComplete->mResolveType == BfResolveType_GetCurrentLocation) ||
  3074. (autoComplete->mResolveType == BfResolveType_GetFixits) ||
  3075. (autoComplete->mResolveType == BfResolveType_GetResultString) ||
  3076. (autoComplete->mResolveType == BfResolveType_GetSymbolInfo) ||
  3077. (autoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  3078. wantsAllLocalMethods = false;
  3079. }
  3080. /*if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType == BfResolveType_ShowFileSymbolReferences))
  3081. {
  3082. if (mCompiler->mResolvePassData->mSymbolReferenceLocalIdx != -1)
  3083. {
  3084. // We need to reproduce the behavior when we found the symbol - only process autocomplete nodes, otherwise local method ids will be wrong
  3085. // when we have local methods that were skipped the first time but not the second
  3086. wantsAllLocalMethods = false;
  3087. }
  3088. }*/
  3089. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites);
  3090. bool hadUnreachableCode = false;
  3091. // Handle statements
  3092. auto itr = block->begin();
  3093. while (itr != block->end())
  3094. {
  3095. BfAstNode* child = *itr;
  3096. if (auto localMethodDecl = BfNodeDynCastExact<BfLocalMethodDeclaration>(child))
  3097. {
  3098. /*if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3099. Fail("Mixins cannot contain local methods", child);*/
  3100. if (!allowLocalMethods)
  3101. {
  3102. Fail("Invalid use of local methods", child);
  3103. }
  3104. else if (localMethodDecl->mMethodDeclaration->mNameNode != NULL)
  3105. {
  3106. BfLocalMethod* localMethod = mCurMethodState->mLocalMethods[curLocalMethodIdx];
  3107. BF_ASSERT(localMethod->mMethodDeclaration == localMethodDecl->mMethodDeclaration);
  3108. bool wantsLocalMethod = (wantsAllLocalMethods) || (autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration));
  3109. if ((!wantsLocalMethod) && (mCurMethodInstance->mMethodDef->mIsLocalMethod))
  3110. wantsLocalMethod = true;
  3111. if (wantsLocalMethod)
  3112. {
  3113. if (!mCurMethodInstance->IsSpecializedGenericMethodOrType())
  3114. GetLocalMethodInstance(localMethod, BfTypeVector(), NULL, true); // Only necessary on unspecialized pass
  3115. }
  3116. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3117. mCompiler->mResolvePassData->mAutoComplete->CheckMethod(localMethod->mMethodDeclaration, true);
  3118. curLocalMethodIdx++;
  3119. }
  3120. ++itr;
  3121. continue;
  3122. }
  3123. if ((mCurMethodState != NULL) && (mCurMethodState->mLeftBlockUncond)) // mLeftBlock is cleared after conditional block is completed
  3124. {
  3125. if (mCurMethodState->mHadReturn)
  3126. hadReturn = true;
  3127. if ((!hadUnreachableCode) && (!mCurMethodState->mInPostReturn))
  3128. {
  3129. if ((mCurMethodState->mCurScope == NULL) || (!mCurMethodState->mCurScope->mSupressNextUnreachable))
  3130. Warn(BfWarning_CS0162_UnreachableCode, "Unreachable code", child);
  3131. hadUnreachableCode = true;
  3132. prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3133. mCurMethodState->mInPostReturn = true;
  3134. mBfIRBuilder->mIgnoreWrites = true;
  3135. }
  3136. }
  3137. if ((mCurMethodState != NULL) && (mCurMethodState->mCurScope != NULL))
  3138. mCurMethodState->mCurScope->mSupressNextUnreachable = false;
  3139. if (itr.IsLast())
  3140. {
  3141. if (auto expr = BfNodeDynCast<BfExpression>(child))
  3142. {
  3143. if (expr->IsExpression())
  3144. {
  3145. if (mCurMethodState != NULL)
  3146. {
  3147. if (mCurMethodState->mCurScope->mExprEvaluator != NULL)
  3148. {
  3149. if ((mAttributeState != NULL) &&
  3150. ((mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) == (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  3151. {
  3152. // Resolve as just 'false'
  3153. mCurMethodState->mCurScope->mExprEvaluator->mResult = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean));
  3154. }
  3155. else
  3156. {
  3157. auto exprEvaluator = mCurMethodState->mCurScope->mExprEvaluator;
  3158. // Evaluate last child as an expression
  3159. exprEvaluator->VisitChild(expr);
  3160. exprEvaluator->FinishExpressionResult();
  3161. if ((exprEvaluator->mResult) && (!exprEvaluator->mResult.mType->IsValuelessType()) && (!exprEvaluator->mResult.mValue.IsConst()) &&
  3162. (!exprEvaluator->mResult.IsAddr()) && (exprEvaluator->mResult.mValue) && (!exprEvaluator->mResult.mValue.IsFake()))
  3163. {
  3164. if ((mCurMethodState->mCurScope != NULL) && (mCurMethodState->mCurScope->mPrevScope != NULL))
  3165. {
  3166. // We need to make sure we don't retain any values through the scope's ValueScopeHardEnd - and extend alloca through previous scope
  3167. bool wasReadOnly = exprEvaluator->mResult.IsReadOnly();
  3168. FixIntUnknown(exprEvaluator->mResult, exprEvaluator->mExpectingType);
  3169. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3170. auto tempVar = CreateAlloca(exprEvaluator->mResult.mType, false, "blockExpr");
  3171. mBfIRBuilder->SetInsertPointAtStart(startInsertBlock);
  3172. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(tempVar);
  3173. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  3174. if ((!mBfIRBuilder->mIgnoreWrites) && (IsTargetingBeefBackend()))
  3175. mCurMethodState->mCurScope->mPrevScope->mDeferredLifetimeEnds.push_back(tempVar);
  3176. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3177. if (exprEvaluator->mResult.IsSplat())
  3178. AggregateSplatIntoAddr(exprEvaluator->mResult, tempVar);
  3179. else if (!exprEvaluator->mResult.mType->IsValuelessType())
  3180. mBfIRBuilder->CreateAlignedStore(exprEvaluator->mResult.mValue, tempVar, exprEvaluator->mResult.mType->mAlign);
  3181. exprEvaluator->mResult = BfTypedValue(tempVar, exprEvaluator->mResult.mType,
  3182. exprEvaluator->mResult.IsThis() ?
  3183. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  3184. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  3185. }
  3186. }
  3187. if (exprEvaluator->mResult.IsAddr())
  3188. {
  3189. if (mCurMethodState->mCurScope->ExtendLifetime(exprEvaluator->mResult.mValue))
  3190. mBfIRBuilder->CreateLifetimeSoftEnd(exprEvaluator->mResult.mValue);
  3191. }
  3192. }
  3193. break;
  3194. }
  3195. else if (mCurMethodState->InMainMixinScope())
  3196. {
  3197. mCurMethodState->mMixinState->mResultExpr = expr;
  3198. break;
  3199. }
  3200. else if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin()) && (mCurMethodState->mCurScope == &mCurMethodState->mHeadScope))
  3201. {
  3202. // Only in mixin definition - result ignored
  3203. CreateValueFromExpression(expr, NULL, BfEvalExprFlags_AllowRefExpr);
  3204. break;
  3205. }
  3206. else
  3207. {
  3208. FailAfter("Expression block cannot be used here. Consider adding semicolon if a statement was intended.", expr);
  3209. }
  3210. }
  3211. }
  3212. }
  3213. }
  3214. UpdateSrcPos(child);
  3215. BfAutoParentNodeEntry autoParentNode(this, child);
  3216. if ((mAttributeState != NULL) &&
  3217. ((mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) == (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  3218. {
  3219. // Ignore child
  3220. }
  3221. else
  3222. child->Accept(this);
  3223. mContext->CheckLockYield();
  3224. ++itr;
  3225. }
  3226. if (mCurMethodState != NULL)
  3227. {
  3228. // Any local method that hasn't been called needs to be processed now
  3229. for (int localMethodIdx = startLocalMethod; localMethodIdx < (int)mCurMethodState->mLocalMethods.size(); localMethodIdx++)
  3230. {
  3231. auto localMethod = mCurMethodState->mLocalMethods[localMethodIdx];
  3232. if ((wantsAllLocalMethods) || (autoComplete->IsAutocompleteNode(localMethod->mMethodDeclaration)))
  3233. {
  3234. //??
  3235. auto moduleMethodInstance = GetLocalMethodInstance(localMethod, BfTypeVector(), NULL, true);
  3236. }
  3237. mContext->CheckLockYield();
  3238. }
  3239. while ((int)mCurMethodState->mLocalMethods.size() > startLocalMethod)
  3240. {
  3241. auto localMethod = mCurMethodState->mLocalMethods.back();
  3242. #if _DEBUG
  3243. BfLocalMethod** localMethodPtr = NULL;
  3244. mCurMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &localMethodPtr);
  3245. BF_ASSERT(*localMethodPtr == localMethod);
  3246. #endif
  3247. if (localMethod->mNextWithSameName == NULL)
  3248. mCurMethodState->mLocalMethodMap.Remove(localMethod->mMethodName);
  3249. else
  3250. {
  3251. mCurMethodState->mLocalMethodMap[localMethod->mMethodName] = localMethod->mNextWithSameName;
  3252. localMethod->mNextWithSameName = NULL;
  3253. }
  3254. mCurMethodState->mLocalMethods.pop_back();
  3255. }
  3256. if (hadUnreachableCode)
  3257. {
  3258. if (hadReturn)
  3259. mCurMethodState->SetHadReturn(true);
  3260. mCurMethodState->mLeftBlockUncond = true;
  3261. mCurMethodState->mInPostReturn = false;
  3262. if (prevInsertBlock)
  3263. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3264. }
  3265. }
  3266. }
  3267. void BfModule::Visit(BfAstNode* astNode)
  3268. {
  3269. AssertErrorState();
  3270. }
  3271. void BfModule::Visit(BfIdentifierNode* identifierNode)
  3272. {
  3273. Visit((BfExpression*)identifierNode);
  3274. }
  3275. void BfModule::Visit(BfTypeReference* typeRef)
  3276. {
  3277. Visit((BfAstNode*)typeRef);
  3278. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3279. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(typeRef, true);
  3280. }
  3281. void BfModule::Visit(BfEmptyStatement* astNode)
  3282. {
  3283. }
  3284. void BfModule::Visit(BfTryStatement* tryStmt)
  3285. {
  3286. Fail("Exceptions not supported", tryStmt->mTryToken);
  3287. VisitChild(tryStmt->mStatement);
  3288. }
  3289. void BfModule::Visit(BfCatchStatement* catchStmt)
  3290. {
  3291. Fail("Exceptions not supported", catchStmt->mCatchToken);
  3292. }
  3293. void BfModule::Visit(BfFinallyStatement* finallyStmt)
  3294. {
  3295. Fail("Exceptions not supported", finallyStmt->mFinallyToken);
  3296. VisitChild(finallyStmt->mStatement);
  3297. }
  3298. void BfModule::Visit(BfCheckedStatement* checkedStmt)
  3299. {
  3300. Fail("'checked' not supported", checkedStmt->mCheckedToken);
  3301. VisitChild(checkedStmt->mStatement);
  3302. }
  3303. void BfModule::Visit(BfUncheckedStatement* uncheckedStmt)
  3304. {
  3305. VisitChild(uncheckedStmt->mStatement);
  3306. }
  3307. void BfModule::DoIfStatement(BfIfStatement* ifStmt, bool includeTrueStmt, bool includeFalseStmt)
  3308. {
  3309. auto autoComplete = mCompiler->GetAutoComplete();
  3310. if (autoComplete != NULL)
  3311. autoComplete->CheckIdentifier(ifStmt->mIfToken, true);
  3312. if (ifStmt->mCondition == NULL)
  3313. {
  3314. AssertErrorState();
  3315. return;
  3316. }
  3317. //TODO: Only conditionally create the scopeData here if we create a variable inside the condition statement
  3318. UpdateSrcPos(ifStmt);
  3319. BfScopeData newScope;
  3320. newScope.mOuterIsConditional = true;
  3321. newScope.mScopeKind = BfScopeKind_StatementTarget;
  3322. if (ifStmt->mLabelNode != NULL)
  3323. newScope.mLabelNode = ifStmt->mLabelNode->mLabel;
  3324. mCurMethodState->AddScope(&newScope);
  3325. NewScopeState();
  3326. BfBreakData breakData;
  3327. breakData.mScope = &newScope;
  3328. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  3329. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  3330. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3331. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  3332. deferredLocalAssignData.mIsIfCondition = true;
  3333. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, true);
  3334. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3335. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  3336. BfAutoParentNodeEntry autoParentNodeEntry(this, ifStmt);
  3337. BfTypedValue condValue = CreateValueFromExpression(ifStmt->mCondition, boolType);
  3338. newScope.mScopeKind = BfScopeKind_Normal;
  3339. deferredLocalAssignData.mIsIfCondition = false;
  3340. // The "extend chain" is only valid for the conditional -- since that expression may contain unconditionally executed and
  3341. // conditionally executed code (in the case of "(GetVal(out a) && GetVal(out b))" for example
  3342. mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  3343. if (!condValue)
  3344. {
  3345. AssertErrorState();
  3346. condValue = BfTypedValue(GetDefaultValue(boolType), boolType);
  3347. }
  3348. BfIRBlock trueBB;
  3349. BfIRBlock falseBB;
  3350. bool isConstBranch = false;
  3351. bool constResult = false;
  3352. if (condValue.mValue.IsConst())
  3353. {
  3354. auto constant = mBfIRBuilder->GetConstant(condValue.mValue);
  3355. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_Boolean))
  3356. {
  3357. isConstBranch = true;
  3358. constResult = constant->mBool;
  3359. }
  3360. }
  3361. if (!isConstBranch)
  3362. {
  3363. trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  3364. falseBB = (ifStmt->mFalseStatement == NULL) ? BfIRBlock() : mBfIRBuilder->CreateBlock("if.else");
  3365. }
  3366. else
  3367. EmitEnsureInstructionAt();
  3368. auto contBB = mBfIRBuilder->CreateBlock("if.end");
  3369. if (!isConstBranch)
  3370. {
  3371. mBfIRBuilder->CreateCondBr(condValue.mValue, trueBB, (falseBB) ? falseBB : contBB);
  3372. }
  3373. // TRUE statement
  3374. bool ignoredLastBlock = true;
  3375. if (includeTrueStmt)
  3376. {
  3377. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  3378. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore);
  3379. if (trueBB)
  3380. mBfIRBuilder->SetInsertPoint(trueBB);
  3381. if ((isConstBranch) && (constResult != true))
  3382. {
  3383. mBfIRBuilder->mIgnoreWrites = true;
  3384. mCurMethodState->mCurScope->mInConstIgnore = true;
  3385. }
  3386. else
  3387. ignoredLastBlock = false;
  3388. VisitEmbeddedStatement(ifStmt->mTrueStatement);
  3389. }
  3390. prevDLA.Restore();
  3391. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  3392. mCurMethodState->mDeferredLocalAssignData->mHadBreak |= deferredLocalAssignData.mHadBreak;
  3393. bool trueHadReturn = mCurMethodState->mHadReturn;
  3394. // We restore the scopeData before the False block because we don't want variables created in the if condition to
  3395. // be visible in the false section
  3396. //RestoreScopeState();
  3397. RestoreScoreState_LocalVariables(mCurMethodState->mCurScope->mLocalVarStart);
  3398. if ((!mCurMethodState->mLeftBlockUncond) && (!ignoredLastBlock))
  3399. mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3400. if (mCurMethodState->mLeftBlockUncond)
  3401. {
  3402. deferredLocalAssignData.mLeftBlockUncond = true;
  3403. mCurMethodState->mLeftBlockCond = true;
  3404. }
  3405. mCurMethodState->mLeftBlockUncond = false;
  3406. mCurMethodState->SetHadReturn(false);
  3407. bool falseHadReturn = false;
  3408. if (ifStmt->mFalseStatement != NULL)
  3409. {
  3410. BfDeferredLocalAssignData falseDeferredLocalAssignData(&newScope);
  3411. falseDeferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3412. if (falseBB)
  3413. {
  3414. mBfIRBuilder->AddBlock(falseBB);
  3415. mBfIRBuilder->SetInsertPoint(falseBB);
  3416. }
  3417. ignoredLastBlock = true;
  3418. //
  3419. {
  3420. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  3421. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore);
  3422. if ((isConstBranch) && (constResult != false))
  3423. {
  3424. mBfIRBuilder->mIgnoreWrites = true;
  3425. mCurMethodState->mCurScope->mInConstIgnore = true;
  3426. }
  3427. else
  3428. ignoredLastBlock = false;
  3429. falseDeferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  3430. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &falseDeferredLocalAssignData);
  3431. if (includeFalseStmt)
  3432. VisitEmbeddedStatement(ifStmt->mFalseStatement, NULL, (BfEmbeddedStatementFlags)(BfEmbeddedStatementFlags_IsConditional | BfEmbeddedStatementFlags_CheckStack));
  3433. }
  3434. if ((!mCurMethodState->mLeftBlockUncond) && (!ignoredLastBlock))
  3435. {
  3436. if (IsTargetingBeefBackend())
  3437. {
  3438. // If we don't do this, then with:
  3439. // if (a) { } else if (b) { }
  3440. // Then we hit the closing second brace even if 'b' is false
  3441. //SetIllegalSrcPos();
  3442. //BfIRBuilder->ClearDebugLocation();
  3443. }
  3444. auto br = mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3445. //mBfIRBuilder->ClearDebugLocation(br);
  3446. }
  3447. falseHadReturn = mCurMethodState->mHadReturn;
  3448. if (mCurMethodState->mLeftBlockUncond)
  3449. {
  3450. falseDeferredLocalAssignData.mLeftBlockUncond = true;
  3451. mCurMethodState->mLeftBlockCond = true;
  3452. }
  3453. mCurMethodState->mLeftBlockUncond = false;
  3454. mCurMethodState->SetHadReturn(false);
  3455. deferredLocalAssignData.SetIntersection(falseDeferredLocalAssignData);
  3456. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  3457. }
  3458. else
  3459. {
  3460. // If we had a const-ignored if statement with no else
  3461. if (ignoredLastBlock)
  3462. {
  3463. if (!mCurMethodState->mLeftBlockUncond)
  3464. mBfIRBuilder->CreateBr_NoCollapse(contBB);
  3465. }
  3466. }
  3467. mBfIRBuilder->AddBlock(contBB);
  3468. mBfIRBuilder->SetInsertPoint(contBB);
  3469. if (isConstBranch)
  3470. mCurMethodState->SetHadReturn(constResult ? trueHadReturn : falseHadReturn);
  3471. else
  3472. mCurMethodState->SetHadReturn(trueHadReturn && falseHadReturn);
  3473. mCurMethodState->mLeftBlockUncond = mCurMethodState->mHadReturn;
  3474. if (mCurMethodState->mHadReturn)
  3475. {
  3476. mBfIRBuilder->EraseFromParent(contBB);
  3477. }
  3478. else
  3479. {
  3480. mBfIRBuilder->SetInsertPoint(contBB);
  3481. }
  3482. RestoreScopeState();
  3483. }
  3484. void BfModule::Visit(BfIfStatement* ifStmt)
  3485. {
  3486. DoIfStatement(ifStmt, true, true);
  3487. }
  3488. void BfModule::Visit(BfVariableDeclaration* varDecl)
  3489. {
  3490. //BP_ZONE("BfModule::Visit(BfVariableDeclaration)");
  3491. UpdateSrcPos(varDecl);
  3492. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  3493. if (tupleVariableDeclaration != NULL)
  3494. {
  3495. HandleTupleVariableDeclaration(varDecl);
  3496. }
  3497. else
  3498. HandleVariableDeclaration(varDecl);
  3499. }
  3500. void BfModule::Visit(BfLocalMethodDeclaration* methodDecl)
  3501. {
  3502. Fail("Local method declarations must be wrapped in a block statement", methodDecl->mMethodDeclaration->mNameNode);
  3503. }
  3504. void BfModule::Visit(BfAttributedStatement* attribStmt)
  3505. {
  3506. BfAttributeState attributeState;
  3507. attributeState.mSrc = attribStmt->mAttributes;
  3508. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  3509. if (auto block = BfNodeDynCast<BfBlock>(attribStmt->mStatement))
  3510. attributeState.mTarget = BfAttributeTargets_Block;
  3511. attributeState.mCustomAttributes = GetCustomAttributes(attribStmt->mAttributes, attributeState.mTarget);
  3512. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  3513. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mCompiler->mIgnoreErrorsAttributeTypeDef))
  3514. {
  3515. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  3516. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  3517. {
  3518. auto constant = mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  3519. if (constant->mBool)
  3520. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  3521. }
  3522. VisitChild(attribStmt->mStatement);
  3523. attributeState.mUsed = true;
  3524. }
  3525. else if (attributeState.mCustomAttributes->Contains(mCompiler->mConstSkipAttributeTypeDef))
  3526. {
  3527. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope == NULL) || (!mCurMethodState->mCurScope->mInConstIgnore))
  3528. {
  3529. VisitChild(attribStmt->mStatement);
  3530. }
  3531. else
  3532. {
  3533. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  3534. }
  3535. attributeState.mUsed = true;
  3536. }
  3537. else
  3538. {
  3539. VisitChild(attribStmt->mStatement);
  3540. }
  3541. FinishAttributeState(&attributeState);
  3542. }
  3543. void BfModule::Visit(BfExpression* expression)
  3544. {
  3545. UpdateSrcPos(expression);
  3546. BfExprEvaluator exprEvaluator(this);
  3547. exprEvaluator.mUsedAsStatement = true;
  3548. exprEvaluator.Evaluate(expression);
  3549. }
  3550. void BfModule::Visit(BfExpressionStatement* expressionStmt)
  3551. {
  3552. expressionStmt->mExpression->Accept(this);
  3553. }
  3554. void BfModule::Visit(BfThrowStatement* throwStmt)
  3555. {
  3556. if (throwStmt->mExpression == NULL)
  3557. {
  3558. AssertErrorState();
  3559. return;
  3560. }
  3561. UpdateSrcPos(throwStmt->mThrowToken);
  3562. auto throwValue = CreateValueFromExpression(throwStmt->mExpression);
  3563. Fail("Exceptions are not supported", throwStmt->mThrowToken);
  3564. if (mCurMethodInstance->mReturnType->IsVoid())
  3565. EmitReturn(BfTypedValue());
  3566. else
  3567. EmitReturn(GetDefaultTypedValue(mCurMethodInstance->mReturnType));
  3568. }
  3569. void BfModule::Visit(BfDeleteStatement* deleteStmt)
  3570. {
  3571. UpdateSrcPos(deleteStmt);
  3572. auto autoComplete = mCompiler->GetAutoComplete();
  3573. if (autoComplete != NULL)
  3574. autoComplete->CheckIdentifier(deleteStmt->mDeleteToken, true);
  3575. bool isAppendDelete = false;
  3576. BfTypedValue customAllocator;
  3577. if (deleteStmt->mAllocExpr != NULL)
  3578. {
  3579. if (auto expr = BfNodeDynCast<BfExpression>(deleteStmt->mAllocExpr))
  3580. customAllocator = CreateValueFromExpression(expr);
  3581. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(deleteStmt->mAllocExpr))
  3582. {
  3583. if (tokenNode->mToken == BfToken_Append)
  3584. isAppendDelete = true;
  3585. }
  3586. }
  3587. BfAttributeState attributeState;
  3588. attributeState.mTarget = BfAttributeTargets_Delete;
  3589. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  3590. attributeState.mCustomAttributes = GetCustomAttributes(deleteStmt->mAttributes, attributeState.mTarget);
  3591. if (deleteStmt->mExpression == NULL)
  3592. {
  3593. AssertErrorState();
  3594. return;
  3595. }
  3596. auto val = CreateValueFromExpression(deleteStmt->mExpression);
  3597. if (!val)
  3598. return;
  3599. auto checkType = val.mType;
  3600. for (int pass = 0; pass < 2; pass++)
  3601. {
  3602. BfGenericParamType* genericType = NULL;
  3603. if (checkType->IsGenericParam())
  3604. genericType = (BfGenericParamType*)checkType;
  3605. if ((checkType->IsPointer()) && (checkType->GetUnderlyingType()->IsGenericParam()))
  3606. genericType = (BfGenericParamType*)checkType->GetUnderlyingType();
  3607. if ((genericType != NULL) || (checkType->IsUnspecializedType()))
  3608. {
  3609. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  3610. BfType* typeConstraint = NULL;
  3611. BfGenericParamInstance* genericParam = NULL;
  3612. if (genericType != NULL)
  3613. genericParam = GetMergedGenericParamData(genericType, genericParamFlags, typeConstraint);
  3614. if (genericParam == NULL)
  3615. GetMergedGenericParamData(checkType, genericParamFlags, typeConstraint);
  3616. if (typeConstraint != NULL)
  3617. checkType = typeConstraint;
  3618. bool canAlwaysDelete = checkType->IsDelegate() || checkType->IsFunction() || checkType->IsArray();
  3619. if (auto checkTypeInst = checkType->ToTypeInstance())
  3620. {
  3621. if ((checkTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) ||
  3622. (checkTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  3623. canAlwaysDelete = true;
  3624. }
  3625. if (!canAlwaysDelete)
  3626. {
  3627. bool success = false;
  3628. if (genericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var))
  3629. success = true;
  3630. else if (genericParamFlags & BfGenericParamFlag_StructPtr)
  3631. success = true;
  3632. else if ((genericParamFlags & BfGenericParamFlag_Struct) && (checkType->IsPointer()))
  3633. success = true;
  3634. if (success)
  3635. {
  3636. if ((pass == 1) && (genericType != NULL))
  3637. {
  3638. auto genericParamInst = GetGenericParamInstance(genericType);
  3639. Warn(0, StrFormat("Must add 'where alloctype(%s) : delete' constraint to generic parameter to delete generic type '%s'",
  3640. genericParamInst->GetGenericParamDef()->mName.c_str(), TypeToString(val.mType).c_str()), deleteStmt->mExpression);
  3641. }
  3642. return;
  3643. }
  3644. if (genericType != NULL)
  3645. {
  3646. auto genericParamInst = GetGenericParamInstance(genericType);
  3647. Fail(StrFormat("Must add 'where %s : delete' constraint to generic parameter to delete generic type '%s'",
  3648. genericParamInst->GetGenericParamDef()->mName.c_str(), TypeToString(val.mType).c_str()), deleteStmt->mExpression);
  3649. return;
  3650. }
  3651. }
  3652. }
  3653. if (pass == 0)
  3654. {
  3655. if (checkType->IsAllocType())
  3656. checkType = checkType->GetUnderlyingType();
  3657. else
  3658. break;
  3659. }
  3660. }
  3661. if (checkType->IsVar())
  3662. {
  3663. // Mixin or unconstrained generic
  3664. return;
  3665. }
  3666. if ((!checkType->IsPointer()) && (!checkType->IsObjectOrInterface()))
  3667. {
  3668. Fail(StrFormat("Cannot delete a value of type '%s'", TypeToString(val.mType).c_str()), deleteStmt->mExpression);
  3669. return;
  3670. }
  3671. if (val.mType->IsGenericParam())
  3672. return;
  3673. auto bodyBB = mBfIRBuilder->CreateBlock("delete.body");
  3674. auto endBB = mBfIRBuilder->CreateBlock("delete.end");
  3675. bool mayBeSentinel = false;
  3676. if (checkType->IsPointer())
  3677. {
  3678. auto innerType = checkType->GetUnderlyingType();
  3679. PopulateType(innerType);
  3680. if (innerType->IsValuelessType())
  3681. mayBeSentinel = true;
  3682. }
  3683. BfIRValue isNotNull;
  3684. if (mayBeSentinel)
  3685. {
  3686. auto intVal = mBfIRBuilder->CreatePtrToInt(val.mValue, BfTypeCode_IntPtr);
  3687. isNotNull = mBfIRBuilder->CreateCmpGT(intVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), false);
  3688. }
  3689. else
  3690. {
  3691. isNotNull = mBfIRBuilder->CreateIsNotNull(val.mValue);
  3692. }
  3693. mBfIRBuilder->CreateCondBr(isNotNull, bodyBB, endBB);
  3694. mBfIRBuilder->AddBlock(bodyBB);
  3695. mBfIRBuilder->SetInsertPoint(bodyBB);
  3696. if (val.mType->IsObjectOrInterface())
  3697. {
  3698. EmitObjectAccessCheck(val);
  3699. }
  3700. SizedArray<BfIRValue, 4> llvmArgs;
  3701. auto bitAddr = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  3702. llvmArgs.push_back(bitAddr);
  3703. if (val.mType->IsObjectOrInterface())
  3704. {
  3705. auto objectType = mContext->mBfObjectType;
  3706. BfTypeInstance* checkTypeInst = val.mType->ToTypeInstance();
  3707. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  3708. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  3709. while (checkTypeInst != NULL)
  3710. {
  3711. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  3712. if (dtorMethodDef)
  3713. {
  3714. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  3715. {
  3716. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), deleteStmt->mExpression); // CS0122
  3717. }
  3718. }
  3719. checkTypeInst = checkTypeInst->mBaseType;
  3720. allowPrivate = false;
  3721. }
  3722. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  3723. {
  3724. auto preDelete = GetInternalMethod((deleteStmt->mTargetTypeToken != NULL) ? "Dbg_ObjectPreCustomDelete" : "Dbg_ObjectPreDelete");
  3725. SizedArray<BfIRValue, 4> llvmArgs;
  3726. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3727. mBfIRBuilder->CreateCall(preDelete.mFunc, llvmArgs);
  3728. }
  3729. // call dtor
  3730. BfExprEvaluator expressionEvaluator(this);
  3731. PopulateType(val.mType);
  3732. PopulateType(objectType, BfPopulateType_DataAndMethods);
  3733. if (objectType->mVirtualMethodTable.size() == 0)
  3734. {
  3735. if (!mCompiler->IsAutocomplete())
  3736. AssertErrorState();
  3737. }
  3738. else if (!IsSkippingExtraResolveChecks())
  3739. {
  3740. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3741. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  3742. SizedArray<BfIRValue, 4> llvmArgs;
  3743. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3744. expressionEvaluator.CreateCall(deleteStmt->mDeleteToken, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  3745. }
  3746. if ((deleteStmt->mTargetTypeToken != NULL) && (!isAppendDelete))
  3747. {
  3748. if (deleteStmt->mAllocExpr != NULL)
  3749. {
  3750. if (customAllocator)
  3751. {
  3752. auto customAllocTypeInst = customAllocator.mType->ToTypeInstance();
  3753. if (customAllocTypeInst != NULL)
  3754. {
  3755. if ((customAllocTypeInst != NULL) && (customAllocTypeInst->mTypeDef->GetMethodByName("FreeObject") != NULL))
  3756. {
  3757. BfTypedValueExpression typedValueExpr;
  3758. typedValueExpr.Init(val);
  3759. typedValueExpr.mRefNode = deleteStmt->mAllocExpr;
  3760. BfExprEvaluator exprEvaluator(this);
  3761. SizedArray<BfExpression*, 2> argExprs;
  3762. argExprs.push_back(&typedValueExpr);
  3763. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3764. BfResolvedArgs argValues(&sizedArgExprs);
  3765. exprEvaluator.ResolveArgValues(argValues);
  3766. exprEvaluator.mNoBind = true;
  3767. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, true, "FreeObject", argValues, BfMethodGenericArguments());
  3768. customAllocator = BfTypedValue();
  3769. }
  3770. }
  3771. }
  3772. }
  3773. }
  3774. else
  3775. {
  3776. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!mIsComptimeModule))
  3777. {
  3778. SizedArray<BfIRValue, 4> llvmArgs;
  3779. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  3780. auto moduleMethodInstance = GetInternalMethod("Dbg_MarkObjectDeleted");
  3781. mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  3782. }
  3783. else if (!isAppendDelete)
  3784. {
  3785. mBfIRBuilder->CreateCall(GetBuiltInFunc(BfBuiltInFuncType_Free), llvmArgs);
  3786. }
  3787. }
  3788. }
  3789. else
  3790. {
  3791. if ((isAppendDelete) || (customAllocator))
  3792. {
  3793. // Do nothing
  3794. }
  3795. else
  3796. {
  3797. auto func = GetBuiltInFunc(BfBuiltInFuncType_Free);
  3798. if (!func)
  3799. {
  3800. BF_ASSERT(mCompiler->mIsResolveOnly);
  3801. }
  3802. else
  3803. mBfIRBuilder->CreateCall(func, llvmArgs);
  3804. }
  3805. }
  3806. if (customAllocator.mType == GetPrimitiveType(BfTypeCode_NullPtr))
  3807. {
  3808. if (!checkType->IsObjectOrInterface())
  3809. Warn(0, "Type '%' has no destructor, so delete:null has no effect", deleteStmt->mExpression);
  3810. }
  3811. else if (customAllocator)
  3812. {
  3813. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3814. auto ptrValue = BfTypedValue(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(voidPtrType)), voidPtrType);
  3815. BfTypedValueExpression typedValueExpr;
  3816. typedValueExpr.Init(ptrValue);
  3817. BfExprEvaluator exprEvaluator(this);
  3818. SizedArray<BfExpression*, 2> argExprs;
  3819. argExprs.push_back(&typedValueExpr);
  3820. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3821. BfResolvedArgs argValues(&sizedArgExprs);
  3822. exprEvaluator.ResolveArgValues(argValues);
  3823. exprEvaluator.mNoBind = true;
  3824. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "Free", argValues, BfMethodGenericArguments());
  3825. }
  3826. mBfIRBuilder->CreateBr(endBB);
  3827. mBfIRBuilder->AddBlock(endBB);
  3828. mBfIRBuilder->SetInsertPoint(endBB);
  3829. }
  3830. void BfModule::Visit(BfSwitchStatement* switchStmt)
  3831. {
  3832. BfScopeData outerScope;
  3833. outerScope.mInnerIsConditional = false;
  3834. outerScope.mCloseNode = switchStmt;
  3835. if (switchStmt->mCloseBrace != NULL)
  3836. outerScope.mCloseNode = switchStmt->mCloseBrace;
  3837. mCurMethodState->AddScope(&outerScope);
  3838. NewScopeState();
  3839. auto valueScopeStartOuter = ValueScopeStart();
  3840. BfTypedValue switchValue;
  3841. if (switchStmt->mSwitchValue == NULL)
  3842. {
  3843. AssertErrorState();
  3844. UpdateSrcPos(switchStmt->mSwitchToken);
  3845. }
  3846. else
  3847. {
  3848. UpdateExprSrcPos(switchStmt->mSwitchValue);
  3849. BfEvalExprFlags flags = BfEvalExprFlags_None;
  3850. flags = BfEvalExprFlags_AllowSplat;
  3851. switchValue = CreateValueFromExpression(switchStmt->mSwitchValue, NULL, flags);
  3852. }
  3853. EmitEnsureInstructionAt();
  3854. if (!switchValue)
  3855. {
  3856. AssertErrorState();
  3857. switchValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3858. }
  3859. if (switchValue.mType->IsPointer())
  3860. {
  3861. auto underlyingType = switchValue.mType->GetUnderlyingType();
  3862. if (underlyingType->IsEnum())
  3863. {
  3864. switchValue = LoadValue(switchValue);
  3865. switchValue = BfTypedValue(switchValue.mValue, underlyingType, true);
  3866. }
  3867. }
  3868. // We make the switch value conditional, but all other uses of this scope is conditional since it's conditional on cases
  3869. BfScopeData newScope;
  3870. newScope.mInnerIsConditional = true;
  3871. newScope.mCloseNode = switchStmt;
  3872. if (switchStmt->mCloseBrace != NULL)
  3873. newScope.mCloseNode = switchStmt->mCloseBrace;
  3874. if (switchStmt->mLabelNode != NULL)
  3875. newScope.mLabelNode = switchStmt->mLabelNode->mLabel;
  3876. mCurMethodState->AddScope(&newScope);
  3877. NewScopeState();
  3878. BfTypedValue switchValueAddr = switchValue;
  3879. BfLocalVariable* localDef = new BfLocalVariable();
  3880. localDef->mName = "_";
  3881. localDef->mResolvedType = switchValueAddr.mType;
  3882. localDef->mIsReadOnly = true;
  3883. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  3884. if (switchValue.IsAddr())
  3885. {
  3886. localDef->mAddr = switchValue.mValue;
  3887. }
  3888. else
  3889. {
  3890. localDef->mValue = switchValue.mValue;
  3891. localDef->mIsSplat = switchValue.IsSplat();
  3892. }
  3893. bool wantsDebugInfo = mHasFullDebugInfo && !mBfIRBuilder->mIgnoreWrites;
  3894. bool tryExtendValue = false;
  3895. bool addDebugInfo = true;
  3896. if ((wantsDebugInfo) && (!switchValue.mType->IsValuelessType()) && (!switchValue.mType->IsVar()))
  3897. {
  3898. if (IsTargetingBeefBackend())
  3899. {
  3900. // We don't need to make a copy
  3901. if (switchValue.IsSplat())
  3902. {
  3903. localDef->mIsSplat = true;
  3904. if (WantsDebugInfo())
  3905. {
  3906. bool found = false;
  3907. String varName = "_";
  3908. for (auto dbgVar : mCurMethodState->mLocals)
  3909. {
  3910. if (dbgVar->mAddr == switchValue.mValue)
  3911. {
  3912. varName += "$a$" + dbgVar->mName;
  3913. found = true;
  3914. break;
  3915. }
  3916. }
  3917. if (found)
  3918. {
  3919. auto fakeVal = CreateAlloca(GetPrimitiveType(BfTypeCode_Int32), true, "_fake");
  3920. addDebugInfo = false;
  3921. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope, varName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(localDef->mResolvedType), BfIRInitType_NotNeeded_AliveOnDecl);
  3922. mBfIRBuilder->DbgInsertDeclare(fakeVal, diVariable);
  3923. }
  3924. }
  3925. }
  3926. else
  3927. {
  3928. // if (!localDef->mAddr)
  3929. // {
  3930. // BfIRValue value = localDef->mValue;
  3931. // if (newLocalVar->mConstValue)
  3932. // value = localDef->mConstValue;
  3933. // auto aliasValue = mBfIRBuilder->CreateAliasValue(value);
  3934. // mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  3935. // scopeData.mDeferredLifetimeEnds.push_back(aliasValue);
  3936. // }
  3937. tryExtendValue = true;
  3938. }
  3939. }
  3940. else if ((switchValue.mType->IsComposite()) && (switchValue.IsAddr()))
  3941. {
  3942. auto refType = CreateRefType(switchValue.mType);
  3943. auto allocaVal = CreateAlloca(refType);
  3944. mBfIRBuilder->CreateStore(switchValue.mValue, allocaVal);
  3945. auto diType = mBfIRBuilder->DbgGetType(refType);
  3946. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  3947. localDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  3948. mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  3949. addDebugInfo = false;
  3950. }
  3951. else
  3952. {
  3953. if (switchValueAddr.IsSplat())
  3954. {
  3955. auto addr = CreateAlloca(switchValue.mType);
  3956. if (switchValue.IsSplat())
  3957. AggregateSplatIntoAddr(switchValue, addr);
  3958. else
  3959. mBfIRBuilder->CreateStore(switchValue.mValue, addr);
  3960. localDef->mAddr = addr;
  3961. localDef->mValue = BfIRValue();
  3962. localDef->mIsSplat = false;
  3963. }
  3964. }
  3965. }
  3966. if (!localDef->mResolvedType->IsVar())
  3967. AddLocalVariableDef(localDef, addDebugInfo, true);
  3968. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  3969. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  3970. int numExpressions = 0;
  3971. SizedArray<BfIRBlock, 8> blocks;
  3972. SizedArray<BfWhenExpression*, 8> whenExprs;
  3973. SizedArray<BfIRBlock, 8> whenFailBlocks;
  3974. BfIRBlock defaultBlock;
  3975. auto endBlock = mBfIRBuilder->CreateBlock("switch.end");
  3976. for (BfSwitchCase* switchCase : switchStmt->mSwitchCases)
  3977. {
  3978. auto caseBlock = mBfIRBuilder->CreateBlock(StrFormat("switch.%d", blocks.size()));
  3979. blocks.push_back(caseBlock);
  3980. numExpressions += (int)switchCase->mCaseExpressions.size();
  3981. }
  3982. defaultBlock = mBfIRBuilder->CreateBlock("default");
  3983. bool hasDefaultCase = switchStmt->mDefaultCase != NULL;
  3984. if (hasDefaultCase)
  3985. blocks.push_back(defaultBlock);
  3986. SizedArray<BfDeferredLocalAssignData, 8> deferredLocalAssignDataVec;
  3987. deferredLocalAssignDataVec.resize(blocks.size());
  3988. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3989. BfTypedValue enumTagVal;
  3990. // Declare cases
  3991. int blockIdx = 0;
  3992. bool hadConstIntVals = false;
  3993. bool hadWhen = false;
  3994. BfIRValue switchStatement;
  3995. auto switchBlock = mBfIRBuilder->GetInsertBlock();
  3996. BfIRBlock noSwitchBlock = mBfIRBuilder->CreateBlock("noSwitch", true);
  3997. BfPrimitiveType* intCoercibleType = GetIntCoercibleType(switchValue.mType);
  3998. bool isConstSwitch = false;
  3999. if ((switchValue.mValue.IsConst()) || (switchValue.mType->IsValuelessType()))
  4000. {
  4001. isConstSwitch = true;
  4002. }
  4003. if (switchValue.mValue)
  4004. {
  4005. mBfIRBuilder->PopulateType(switchValue.mType);
  4006. if (intCoercibleType != NULL)
  4007. {
  4008. auto intValue = GetIntCoercible(switchValue);
  4009. switchStatement = mBfIRBuilder->CreateSwitch(intValue.mValue, noSwitchBlock, numExpressions);
  4010. }
  4011. else if (switchValue.mType->IsPayloadEnum())
  4012. {
  4013. enumTagVal = ExtractValue(switchValue, NULL, 2);
  4014. enumTagVal = LoadValue(enumTagVal);
  4015. switchStatement = mBfIRBuilder->CreateSwitch(enumTagVal.mValue, noSwitchBlock, numExpressions);
  4016. }
  4017. else if ((!isConstSwitch) && (!switchValue.mType->IsVar()))
  4018. switchStatement = mBfIRBuilder->CreateSwitch(switchValue.mValue, noSwitchBlock, numExpressions);
  4019. }
  4020. auto valueScopeStartInner = ValueScopeStart();
  4021. mBfIRBuilder->SetInsertPoint(noSwitchBlock);
  4022. bool isPayloadEnum = switchValue.mType->IsPayloadEnum();
  4023. bool isTuple = switchValue.mType->IsTuple();
  4024. bool isIntegralSwitch = switchValue.mType->IsIntegral() || (intCoercibleType != NULL) || ((switchValue.mType->IsEnum()) && (!isPayloadEnum));
  4025. auto _ShowCaseError = [&] (int64 id, BfAstNode* errNode)
  4026. {
  4027. if (isPayloadEnum)
  4028. {
  4029. auto enumType = switchValue.mType->ToTypeInstance();
  4030. for (auto& fieldInstance : enumType->mFieldInstances)
  4031. {
  4032. auto fieldDef = fieldInstance.GetFieldDef();
  4033. if (fieldDef->IsEnumCaseEntry())
  4034. {
  4035. int enumIdx = -fieldInstance.mDataIdx - 1;
  4036. if (enumIdx == id)
  4037. {
  4038. Fail(StrFormat("The switch statement already contains a case for the the value '%s'", fieldDef->mName.c_str()), errNode);
  4039. return;
  4040. }
  4041. }
  4042. }
  4043. }
  4044. Fail(StrFormat("The switch statement already contains a case for the the value '%lld'", id), errNode);
  4045. };
  4046. int caseCount = 0;
  4047. bool allHadReturns = true;
  4048. bool hadCondCase = false;
  4049. BfIRBlock lastDefaultBlock;
  4050. struct _CaseState
  4051. {
  4052. BfIRBlock mCondBlock;
  4053. BfIRBlock mUncondBlock;
  4054. };
  4055. bool hadConstMatch = false;
  4056. auto startingLocalVarId = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  4057. bool prevHadFallthrough = false;
  4058. Dictionary<int64, _CaseState> handledCases;
  4059. HashSet<int64> condCases;
  4060. for (BfSwitchCase* switchCase : switchStmt->mSwitchCases)
  4061. {
  4062. deferredLocalAssignDataVec[blockIdx].mScopeData = mCurMethodState->mCurScope;
  4063. deferredLocalAssignDataVec[blockIdx].ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  4064. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignDataVec[blockIdx]);
  4065. mCurMethodState->mDeferredLocalAssignData->mVarIdBarrier = startingLocalVarId;
  4066. SetIllegalSrcPos();
  4067. auto caseBlock = blocks[blockIdx];
  4068. BfScopeData caseScopeData;
  4069. bool openedScope = false;
  4070. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4071. {
  4072. // This does the enum autocomplete popup
  4073. BfAstNode* checkNode = NULL;
  4074. int caseExprIdx = (int)switchCase->mCaseExpressions.size();
  4075. if (caseExprIdx == 0)
  4076. checkNode = switchCase->mCaseToken;
  4077. else if (caseExprIdx - 1 < (int)switchCase->mCaseCommas.size())
  4078. checkNode = switchCase->mCaseCommas[caseExprIdx - 1];
  4079. if (checkNode != NULL)
  4080. mCompiler->mResolvePassData->mAutoComplete->CheckEmptyStart(checkNode, switchValue.mType);
  4081. }
  4082. bool mayHaveMatch = false;
  4083. BfWhenExpression* whenExpr = NULL;
  4084. for (BfExpression* caseExpr : switchCase->mCaseExpressions)
  4085. {
  4086. if (auto checkWhenExpr = BfNodeDynCast<BfWhenExpression>(caseExpr))
  4087. {
  4088. hadWhen = true;
  4089. whenExpr = checkWhenExpr;
  4090. }
  4091. }
  4092. bool wantsOpenedScope = isPayloadEnum || isTuple;
  4093. BfIRBlock lastNotEqBlock;
  4094. for (BfExpression* caseExpr : switchCase->mCaseExpressions)
  4095. {
  4096. BfConstant* constantInt = NULL;
  4097. if (auto checkWhenExpr = BfNodeDynCast<BfWhenExpression>(caseExpr))
  4098. continue;
  4099. if ((!openedScope) && (wantsOpenedScope))
  4100. {
  4101. openedScope = true;
  4102. caseScopeData.mOuterIsConditional = true;
  4103. caseScopeData.mIsSharedTempBlock = true;
  4104. mCurMethodState->AddScope(&caseScopeData);
  4105. NewScopeState();
  4106. UpdateSrcPos(caseExpr);
  4107. SetIllegalSrcPos();
  4108. }
  4109. BfIRValue eqResult;
  4110. BfIRBlock notEqBB;
  4111. bool handled = false;
  4112. BfTypedValue caseValue;
  4113. BfIRBlock doBlock = caseBlock;
  4114. bool hadConditional = false;
  4115. bool isEnumDescValue = isPayloadEnum;
  4116. if (isPayloadEnum)
  4117. {
  4118. auto dscrType = switchValue.mType->ToTypeInstance()->GetDiscriminatorType();
  4119. if (!enumTagVal)
  4120. {
  4121. enumTagVal = ExtractValue(switchValue, NULL, 2);
  4122. enumTagVal = LoadValue(enumTagVal);
  4123. }
  4124. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx), false);
  4125. int tagId = -1;
  4126. BfIRBlock matchBlock;
  4127. BfTypedValue eqTypedResult;
  4128. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr))
  4129. {
  4130. eqTypedResult = HandleCaseBind(switchValueAddr, enumTagVal, bindExpr, &caseBlock, &notEqBB, &matchBlock, &tagId);
  4131. }
  4132. else
  4133. {
  4134. eqTypedResult = TryCaseEnumMatch(switchValueAddr, enumTagVal, caseExpr, &caseBlock, &notEqBB, &matchBlock, tagId, hadConditional, false, prevHadFallthrough);
  4135. if (auto constant = mBfIRBuilder->GetConstant(eqTypedResult.mValue))
  4136. {
  4137. if (constant->mBool)
  4138. mayHaveMatch = true;
  4139. }
  4140. if (hadConditional)
  4141. hadCondCase = true;
  4142. }
  4143. if (tagId != -1)
  4144. {
  4145. doBlock = matchBlock; // Jump to binds rather than just the code
  4146. caseValue = BfTypedValue(GetConstValue(tagId, GetPrimitiveType(dscrType->mTypeDef->mTypeCode)), dscrType);
  4147. }
  4148. else
  4149. hadCondCase = true;
  4150. if (eqTypedResult)
  4151. {
  4152. handled = true;
  4153. eqResult = eqTypedResult.mValue;
  4154. }
  4155. }
  4156. else if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr))
  4157. {
  4158. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx), false);
  4159. BfIRBlock matchBlock;
  4160. BfTypedValue eqTypedResult = TryCaseTupleMatch(switchValue, tupleExpr, &caseBlock, &notEqBB, &matchBlock, hadConditional, false, prevHadFallthrough);
  4161. if (hadConditional)
  4162. hadCondCase = true;
  4163. if (eqTypedResult)
  4164. {
  4165. mayHaveMatch = true;
  4166. handled = true;
  4167. eqResult = eqTypedResult.mValue;
  4168. }
  4169. }
  4170. if (!eqResult)
  4171. {
  4172. caseValue = CreateValueFromExpression(caseExpr, switchValue.mType, (BfEvalExprFlags)(BfEvalExprFlags_AllowEnumId | BfEvalExprFlags_NoCast));
  4173. if (!caseValue)
  4174. continue;
  4175. isEnumDescValue = false;
  4176. }
  4177. BfTypedValue caseIntVal = caseValue;
  4178. if ((isIntegralSwitch) || (isPayloadEnum))
  4179. {
  4180. if ((intCoercibleType != NULL) &&
  4181. (caseValue.mType == switchValue.mType) &&
  4182. (caseValue.mValue.IsConst()))
  4183. {
  4184. caseIntVal = GetIntCoercible(caseValue);
  4185. constantInt = mBfIRBuilder->GetConstant(caseIntVal.mValue);
  4186. }
  4187. else
  4188. {
  4189. // For a non-const case, allow for conversion operators, otherwise cast now
  4190. if ((isIntegralSwitch) && (caseValue.mValue.IsConst()))
  4191. {
  4192. if (caseValue.mType != switchValue.mType)
  4193. {
  4194. caseValue = Cast(caseExpr, caseValue, switchValue.mType);
  4195. if (!caseValue)
  4196. continue;
  4197. caseIntVal = caseValue;
  4198. }
  4199. }
  4200. if ((caseValue.mType == switchValue.mType) || (eqResult))
  4201. {
  4202. constantInt = mBfIRBuilder->GetConstant(caseValue.mValue);
  4203. if ((constantInt != NULL) && (!mBfIRBuilder->IsInt(constantInt->mTypeCode)))
  4204. constantInt = NULL;
  4205. }
  4206. }
  4207. }
  4208. if ((!switchStatement) && (!isConstSwitch))
  4209. {
  4210. // Do nothing
  4211. mayHaveMatch = true;
  4212. }
  4213. else if ((constantInt != NULL) && (!hadWhen) && (!isConstSwitch))
  4214. {
  4215. if (hadConditional)
  4216. {
  4217. condCases.Add(constantInt->mInt64);
  4218. }
  4219. else
  4220. {
  4221. _CaseState* caseState = NULL;
  4222. handledCases.TryAdd(constantInt->mInt64, NULL, &caseState);
  4223. if (condCases.Contains(constantInt->mInt64))
  4224. {
  4225. // This is a 'case .A:' after a 'case .A(let value):'
  4226. eqResult = mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseValue.mValue);
  4227. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4228. mayHaveMatch = true;
  4229. mBfIRBuilder->CreateCondBr(eqResult, caseBlock, notEqBB);
  4230. mBfIRBuilder->AddBlock(notEqBB);
  4231. mBfIRBuilder->SetInsertPoint(notEqBB);
  4232. }
  4233. else
  4234. {
  4235. if (caseState->mUncondBlock)
  4236. {
  4237. _ShowCaseError(constantInt->mInt64, caseExpr);
  4238. }
  4239. else
  4240. {
  4241. caseState->mUncondBlock = doBlock;
  4242. mBfIRBuilder->AddSwitchCase(switchStatement, caseIntVal.mValue, doBlock);
  4243. hadConstIntVals = true;
  4244. }
  4245. }
  4246. }
  4247. mayHaveMatch = true;
  4248. }
  4249. else if (!handled)
  4250. {
  4251. hadCondCase = true;
  4252. if (!eqResult)
  4253. {
  4254. BfExprEvaluator exprEvaluator(this);
  4255. BfAstNode* refNode = switchCase->mColonToken;
  4256. if ((caseValue.mType->IsPayloadEnum()) && (caseValue.mValue.IsConst()) && (switchValue.mType == caseValue.mType) &&
  4257. ((isEnumDescValue) || (constantInt != NULL)))
  4258. {
  4259. if (!enumTagVal)
  4260. {
  4261. enumTagVal = ExtractValue(switchValue, NULL, 2);
  4262. enumTagVal = LoadValue(enumTagVal);
  4263. }
  4264. eqResult = mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseValue.mValue);
  4265. }
  4266. else
  4267. {
  4268. exprEvaluator.PerformBinaryOperation(switchStmt->mSwitchValue, caseExpr, BfBinaryOp_Equality, refNode, (BfBinOpFlags)(BfBinOpFlag_ForceLeftType), switchValue, caseValue);
  4269. if (switchStmt->mSwitchValue != NULL)
  4270. UpdateSrcPos(switchStmt->mSwitchValue);
  4271. SetIllegalSrcPos();
  4272. eqResult = exprEvaluator.mResult.mValue;
  4273. if (!eqResult)
  4274. eqResult = GetConstValue(0, boolType);
  4275. }
  4276. }
  4277. ValueScopeEnd(valueScopeStartInner);
  4278. bool isConstResult = false;
  4279. bool constResult = false;
  4280. if (eqResult.IsConst())
  4281. {
  4282. auto constant = mBfIRBuilder->GetConstant(eqResult);
  4283. if (constant->mTypeCode == BfTypeCode_Boolean)
  4284. {
  4285. isConstResult = true;
  4286. constResult = constant->mBool;
  4287. }
  4288. }
  4289. if (isConstResult)
  4290. {
  4291. if (constResult)
  4292. {
  4293. mBfIRBuilder->CreateBr(caseBlock);
  4294. mayHaveMatch = true;
  4295. if (whenExpr == NULL)
  4296. {
  4297. hadConstMatch = true;
  4298. }
  4299. else
  4300. {
  4301. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4302. mBfIRBuilder->AddBlock(notEqBB);
  4303. mBfIRBuilder->SetInsertPoint(notEqBB);
  4304. }
  4305. }
  4306. }
  4307. else
  4308. {
  4309. notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq.%d", blockIdx));
  4310. mayHaveMatch = true;
  4311. mBfIRBuilder->CreateCondBr(eqResult, caseBlock, notEqBB);
  4312. mBfIRBuilder->AddBlock(notEqBB);
  4313. mBfIRBuilder->SetInsertPoint(notEqBB);
  4314. }
  4315. }
  4316. else if (whenExpr != NULL)
  4317. {
  4318. mayHaveMatch = true;
  4319. }
  4320. if (notEqBB)
  4321. lastNotEqBlock = notEqBB;
  4322. if ((!hadCondCase) && (notEqBB))
  4323. lastDefaultBlock = notEqBB;
  4324. }
  4325. if ((whenExpr != NULL) && (switchCase->mCaseExpressions.size() == 1))
  4326. {
  4327. // This was a "case when" expression, always matches
  4328. mayHaveMatch = true;
  4329. auto notEqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.notEq_when.%d", blockIdx));
  4330. mBfIRBuilder->CreateBr(caseBlock);
  4331. mBfIRBuilder->AddBlock(notEqBB);
  4332. mBfIRBuilder->SetInsertPoint(notEqBB);
  4333. lastNotEqBlock = notEqBB;
  4334. }
  4335. if ((lastDefaultBlock) && (switchStatement))
  4336. mBfIRBuilder->SetSwitchDefaultDest(switchStatement, lastDefaultBlock);
  4337. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  4338. bool isConstIgnore = !mayHaveMatch && !prevHadFallthrough;
  4339. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true, isConstIgnore);
  4340. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true, isConstIgnore);
  4341. mBfIRBuilder->AddBlock(caseBlock);
  4342. mBfIRBuilder->SetInsertPoint(caseBlock);
  4343. if (whenExpr != NULL)
  4344. {
  4345. UpdateSrcPos(whenExpr);
  4346. BfTypedValue whenValue;
  4347. if (whenExpr->mExpression != NULL)
  4348. whenValue = CreateValueFromExpression(whenExpr->mExpression, boolType, BfEvalExprFlags_AllowEnumId);
  4349. if (!whenValue)
  4350. {
  4351. AssertErrorState();
  4352. whenValue = GetDefaultTypedValue(boolType);
  4353. }
  4354. bool constResult = false;
  4355. if (mBfIRBuilder->TryGetBool(whenValue.mValue, constResult))
  4356. {
  4357. if (!constResult)
  4358. prevIgnoreWrites.Set();
  4359. }
  4360. else
  4361. {
  4362. BfIRBlock eqBB = mBfIRBuilder->CreateBlock(StrFormat("switch.when.%d", blockIdx));
  4363. mBfIRBuilder->CreateCondBr(whenValue.mValue, eqBB, lastNotEqBlock);
  4364. mBfIRBuilder->AddBlock(eqBB);
  4365. mBfIRBuilder->SetInsertPoint(eqBB);
  4366. }
  4367. }
  4368. BfIRBlock fallthroughBlock;
  4369. if (blockIdx < (int) blocks.size() - 1)
  4370. fallthroughBlock = blocks[blockIdx + 1];
  4371. else
  4372. fallthroughBlock = defaultBlock;
  4373. bool hadReturn = false;
  4374. if ((switchCase->mCodeBlock != NULL) && (!switchCase->mCodeBlock->mChildArr.IsEmpty()))
  4375. {
  4376. UpdateSrcPos(switchCase->mCodeBlock);
  4377. VisitCodeBlock(switchCase->mCodeBlock, BfIRBlock(), endBlock, fallthroughBlock, true, &hadReturn, switchStmt->mLabelNode, openedScope /*, BfEmbeddedStatementFlags_RescopeDLA*/);
  4378. openedScope = false;
  4379. deferredLocalAssignDataVec[blockIdx].mHadReturn = hadReturn;
  4380. caseCount++;
  4381. if ((!hadReturn) &&
  4382. ((!mCurMethodState->mDeferredLocalAssignData->mHadFallthrough) || (mCurMethodState->mDeferredLocalAssignData->mHadBreak)))
  4383. allHadReturns = false;
  4384. if (auto block = BfNodeDynCast<BfBlock>(switchCase->mCodeBlock))
  4385. {
  4386. //
  4387. }
  4388. else
  4389. {
  4390. if (switchStmt->mCloseBrace != NULL)
  4391. {
  4392. UpdateSrcPos(switchStmt->mCloseBrace);
  4393. }
  4394. EmitEnsureInstructionAt();
  4395. }
  4396. //UpdateSrcPos(switchCase->mCodeBlock);
  4397. //SetIllegalSrcPos();
  4398. mBfIRBuilder->ClearDebugLocation();
  4399. }
  4400. else
  4401. {
  4402. if (openedScope)
  4403. RestoreScopeState();
  4404. mBfIRBuilder->CreateBr(endBlock);
  4405. allHadReturns = false;
  4406. }
  4407. prevIgnoreWrites.Restore();
  4408. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  4409. prevHadFallthrough = mCurMethodState->mDeferredLocalAssignData->mHadFallthrough;
  4410. blockIdx++;
  4411. }
  4412. // Check for comprehensiveness
  4413. bool isComprehensive = true;
  4414. if ((switchValue) && (switchStmt->mDefaultCase == NULL))
  4415. {
  4416. if (switchValue.mType->IsEnum())
  4417. {
  4418. if (hadConstMatch)
  4419. {
  4420. // Already handled
  4421. }
  4422. else
  4423. {
  4424. auto enumType = switchValue.mType->ToTypeInstance();
  4425. if (enumType->IsPayloadEnum())
  4426. {
  4427. int lastTagId = -1;
  4428. for (auto& field : enumType->mFieldInstances)
  4429. {
  4430. auto fieldDef = field.GetFieldDef();
  4431. if (fieldDef == NULL)
  4432. continue;
  4433. if (!fieldDef->IsEnumCaseEntry())
  4434. continue;
  4435. if (field.mDataIdx < 0)
  4436. lastTagId = -field.mDataIdx - 1;
  4437. }
  4438. isComprehensive = lastTagId == (int)handledCases.size() - 1;
  4439. }
  4440. else
  4441. {
  4442. for (auto& field : enumType->mFieldInstances)
  4443. {
  4444. auto fieldDef = field.GetFieldDef();
  4445. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4446. {
  4447. if (field.mConstIdx != -1)
  4448. {
  4449. auto constant = enumType->mConstHolder->GetConstantById(field.mConstIdx);
  4450. isComprehensive &= handledCases.ContainsKey(constant->mInt64);
  4451. }
  4452. }
  4453. }
  4454. }
  4455. }
  4456. if (!isComprehensive)
  4457. {
  4458. BfAstNode* refNode = switchStmt->mSwitchToken;
  4459. Fail("Switch must be exhaustive, consider adding a default clause", switchStmt->mSwitchToken);
  4460. if ((switchStmt->mCloseBrace) && (mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  4461. {
  4462. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  4463. if (parser != NULL)
  4464. {
  4465. int fileLoc = switchStmt->mCloseBrace->GetSrcStart();
  4466. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("default:\tdefault:|%s|%d||default:", parser->mFileName.c_str(), fileLoc).c_str()));
  4467. }
  4468. }
  4469. }
  4470. }
  4471. else
  4472. isComprehensive = false;
  4473. }
  4474. if (!hadConstMatch)
  4475. mBfIRBuilder->CreateBr(defaultBlock);
  4476. mBfIRBuilder->SetInsertPoint(switchBlock);
  4477. if (!hadConstIntVals)
  4478. {
  4479. if (switchStatement)
  4480. mBfIRBuilder->EraseInstFromParent(switchStatement);
  4481. mBfIRBuilder->CreateBr(noSwitchBlock);
  4482. }
  4483. if (switchStmt->mDefaultCase != NULL)
  4484. {
  4485. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true, hadConstMatch);
  4486. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true, hadConstMatch);
  4487. mBfIRBuilder->AddBlock(defaultBlock);
  4488. mBfIRBuilder->SetInsertPoint(defaultBlock);
  4489. auto switchCase = switchStmt->mDefaultCase;
  4490. if (switchCase->mCodeBlock != NULL)
  4491. {
  4492. isComprehensive = true;
  4493. UpdateSrcPos(switchCase->mCodeBlock);
  4494. deferredLocalAssignDataVec[blockIdx].mScopeData = mCurMethodState->mCurScope;
  4495. deferredLocalAssignDataVec[blockIdx].ExtendFrom(mCurMethodState->mDeferredLocalAssignData);
  4496. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignDataVec[blockIdx]);
  4497. mCurMethodState->mDeferredLocalAssignData->mVarIdBarrier = startingLocalVarId;
  4498. BfScopeData caseScopeData;
  4499. caseScopeData.mOuterIsConditional = true;
  4500. caseScopeData.mIsSharedTempBlock = true;
  4501. mCurMethodState->AddScope(&caseScopeData);
  4502. NewScopeState();
  4503. caseScopeData.mLabel = newScope.mLabel;
  4504. bool hadReturn = false;
  4505. VisitCodeBlock(switchCase->mCodeBlock, BfIRBlock(), endBlock, BfIRBlock(), true, &hadReturn, switchStmt->mLabelNode);
  4506. deferredLocalAssignDataVec[blockIdx].mHadReturn = hadReturn;
  4507. caseCount++;
  4508. if (!hadReturn)
  4509. allHadReturns = false;
  4510. RestoreScopeState();
  4511. }
  4512. }
  4513. else
  4514. {
  4515. mBfIRBuilder->AddBlock(defaultBlock);
  4516. mBfIRBuilder->SetInsertPoint(defaultBlock);
  4517. if (isComprehensive)
  4518. {
  4519. mBfIRBuilder->CreateUnreachable();
  4520. //TODO: This masks a bug in our backend
  4521. if (IsTargetingBeefBackend())
  4522. mBfIRBuilder->CreateBr(endBlock);
  4523. }
  4524. else
  4525. mBfIRBuilder->CreateBr(endBlock);
  4526. }
  4527. if (isComprehensive)
  4528. {
  4529. // Merge and apply deferred local assign data
  4530. // We only do this if there's a default case, otherwise we assume we may have missed a case
  4531. // that by definition had no local assigns
  4532. BfDeferredLocalAssignData* mergedDeferredLocalAssignData = NULL;
  4533. for (blockIdx = 0; blockIdx < (int)blocks.size(); blockIdx++)
  4534. {
  4535. auto deferredLocalAssignData = &deferredLocalAssignDataVec[blockIdx];
  4536. if (deferredLocalAssignData->mHadFallthrough)
  4537. continue;
  4538. if (mergedDeferredLocalAssignData == NULL)
  4539. mergedDeferredLocalAssignData = deferredLocalAssignData;
  4540. else
  4541. mergedDeferredLocalAssignData->SetIntersection(*deferredLocalAssignData);
  4542. }
  4543. if (mergedDeferredLocalAssignData != NULL)
  4544. mCurMethodState->ApplyDeferredLocalAssignData(*mergedDeferredLocalAssignData);
  4545. }
  4546. if ((caseCount > 0) && (allHadReturns) &&
  4547. ((hasDefaultCase) || (isComprehensive)))
  4548. {
  4549. mCurMethodState->SetHadReturn(true);
  4550. mCurMethodState->mLeftBlockUncond = true;
  4551. if ((!hasDefaultCase) && (!isComprehensive))
  4552. mBfIRBuilder->DeleteBlock(endBlock);
  4553. else
  4554. {
  4555. if (switchStmt->mCloseBrace != NULL)
  4556. UpdateSrcPos(switchStmt->mCloseBrace);
  4557. mBfIRBuilder->AddBlock(endBlock);
  4558. mBfIRBuilder->SetInsertPoint(endBlock);
  4559. mBfIRBuilder->CreateUnreachable();
  4560. }
  4561. }
  4562. else
  4563. {
  4564. if (switchStmt->mCloseBrace != NULL)
  4565. UpdateSrcPos(switchStmt->mCloseBrace);
  4566. mBfIRBuilder->AddBlock(endBlock);
  4567. mBfIRBuilder->SetInsertPoint(endBlock);
  4568. }
  4569. BfIRValue lifetimeExtendVal;
  4570. if (tryExtendValue)
  4571. {
  4572. if (localDef->mAddr)
  4573. lifetimeExtendVal = localDef->mAddr;
  4574. else
  4575. lifetimeExtendVal = localDef->mValue;
  4576. }
  4577. RestoreScopeState(); // newScope
  4578. RestoreScopeState(); // outerScope
  4579. if (lifetimeExtendVal)
  4580. mBfIRBuilder->CreateLifetimeExtend(lifetimeExtendVal);
  4581. ValueScopeEnd(valueScopeStartOuter);
  4582. }
  4583. static int gRetIdx = 0;
  4584. void BfModule::Visit(BfReturnStatement* returnStmt)
  4585. {
  4586. if ((mCurMethodInstance == NULL) || (mCurMethodState->mDisableReturns))
  4587. {
  4588. Fail("Unexpected return", returnStmt);
  4589. if (returnStmt->mExpression != NULL)
  4590. {
  4591. BfExprEvaluator exprEvaluator(this);
  4592. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression);
  4593. }
  4594. return;
  4595. }
  4596. UpdateSrcPos(returnStmt);
  4597. EmitEnsureInstructionAt();
  4598. auto retType = mCurMethodInstance->mReturnType;
  4599. if (mCurMethodInstance->IsMixin())
  4600. retType = NULL;
  4601. bool inferReturnType = false;
  4602. if (mCurMethodState->mClosureState != NULL)
  4603. {
  4604. retType = mCurMethodState->mClosureState->mReturnType;
  4605. inferReturnType = (mCurMethodState->mClosureState->mReturnTypeInferState != BfReturnTypeInferState_None);
  4606. }
  4607. auto checkScope = mCurMethodState->mCurScope;
  4608. while (checkScope != NULL)
  4609. {
  4610. if (checkScope->mIsDeferredBlock)
  4611. {
  4612. Fail("Deferred blocks cannot contain 'return' statements", returnStmt);
  4613. if (returnStmt->mExpression != NULL)
  4614. {
  4615. BfExprEvaluator exprEvaluator(this);
  4616. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, GetPrimitiveType(BfTypeCode_Var), BfEvalExprFlags_None);
  4617. }
  4618. return;
  4619. }
  4620. if (checkScope->mInInitBlock)
  4621. {
  4622. Fail("Initialization blocks cannot contain 'return' statements", returnStmt);
  4623. }
  4624. checkScope = checkScope->mPrevScope;
  4625. }
  4626. auto checkLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  4627. while (checkLocalAssignData != NULL)
  4628. {
  4629. if (checkLocalAssignData->mScopeData != NULL)
  4630. checkLocalAssignData->mLeftBlock = true;
  4631. checkLocalAssignData = checkLocalAssignData->mChainedAssignData;
  4632. }
  4633. if ((retType == NULL) && (!inferReturnType))
  4634. {
  4635. if (returnStmt->mExpression != NULL)
  4636. {
  4637. BfExprEvaluator exprEvaluator(this);
  4638. CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, GetPrimitiveType(BfTypeCode_Var), BfEvalExprFlags_None);
  4639. }
  4640. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4641. return;
  4642. }
  4643. if (returnStmt->mExpression == NULL)
  4644. {
  4645. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4646. if ((retType != NULL) && (retType->IsVoid()))
  4647. {
  4648. EmitReturn(BfTypedValue());
  4649. return;
  4650. }
  4651. Fail("Expected return value", returnStmt);
  4652. if (retType != NULL)
  4653. EmitReturn(GetDefaultTypedValue(retType));
  4654. else
  4655. EmitReturn(BfTypedValue());
  4656. return;
  4657. }
  4658. BfType* expectingReturnType = retType;
  4659. BfType* origType;
  4660. BfExprEvaluator exprEvaluator(this);
  4661. bool alreadyWritten = false;
  4662. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  4663. exprEvaluator.mReceivingValue = &mCurMethodState->mRetVal;
  4664. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  4665. exprEvaluator.mAllowReadOnlyReference = true;
  4666. if (inferReturnType)
  4667. expectingReturnType = NULL;
  4668. auto retValue = CreateValueFromExpression(exprEvaluator, returnStmt->mExpression, expectingReturnType, BfEvalExprFlags_AllowRefExpr, &origType);
  4669. if ((retValue) && (inferReturnType))
  4670. {
  4671. if (mCurMethodState->mClosureState->mReturnType == NULL)
  4672. mCurMethodState->mClosureState->mReturnType = retValue.mType;
  4673. else
  4674. {
  4675. if ((retValue.mType == mCurMethodState->mClosureState->mReturnType) ||
  4676. (CanCast(retValue, mCurMethodState->mClosureState->mReturnType)))
  4677. {
  4678. // Leave as-is
  4679. }
  4680. else if (CanCast(GetFakeTypedValue(mCurMethodState->mClosureState->mReturnType), retValue.mType))
  4681. {
  4682. mCurMethodState->mClosureState->mReturnType = retValue.mType;
  4683. }
  4684. else
  4685. {
  4686. mCurMethodState->mClosureState->mReturnTypeInferState = BfReturnTypeInferState_Fail;
  4687. }
  4688. }
  4689. }
  4690. if ((retType == NULL) && (inferReturnType))
  4691. retType = mCurMethodState->mClosureState->mReturnType;
  4692. if (retType == NULL)
  4693. retType = GetPrimitiveType(BfTypeCode_None);
  4694. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  4695. alreadyWritten = exprEvaluator.mReceivingValue == NULL;
  4696. MarkScopeLeft(&mCurMethodState->mHeadScope);
  4697. if (!retValue)
  4698. {
  4699. AssertErrorState();
  4700. if ((expectingReturnType != NULL) && (!expectingReturnType->IsVoid()))
  4701. {
  4702. retValue = GetDefaultTypedValue(expectingReturnType, true);
  4703. }
  4704. else
  4705. {
  4706. EmitReturn(BfTypedValue());
  4707. return;
  4708. }
  4709. }
  4710. if (retValue.mType->IsVar())
  4711. {
  4712. EmitReturn(BfTypedValue());
  4713. }
  4714. else if (retValue.mType->IsVoid())
  4715. {
  4716. if (retType->IsVoid())
  4717. {
  4718. Warn(0, "Returning void value", returnStmt->mReturnToken);
  4719. EmitReturn(BfTypedValue());
  4720. }
  4721. }
  4722. else
  4723. {
  4724. if (retType->IsVoid())
  4725. {
  4726. expectingReturnType = NULL;
  4727. Fail("Attempting to return value from void method", returnStmt->mExpression);
  4728. EmitReturn(BfTypedValue());
  4729. return;
  4730. }
  4731. if ((origType != NULL) && (origType->IsStructOrStructPtr()) && (retValue.mType->IsObjectOrInterface()))
  4732. {
  4733. Fail(StrFormat("Stack boxing of type '%s' is not allowed on return statements. Use 'new box' to box on the heap.", TypeToString(origType).c_str()), returnStmt->mExpression);
  4734. }
  4735. if (!alreadyWritten)
  4736. EmitReturn(LoadOrAggregateValue(retValue));
  4737. else
  4738. EmitReturn(BfTypedValue());
  4739. }
  4740. }
  4741. void BfModule::Visit(BfYieldStatement* yieldStmt)
  4742. {
  4743. Fail("Yield not supported", yieldStmt);
  4744. }
  4745. void BfModule::Visit(BfBreakStatement* breakStmt)
  4746. {
  4747. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  4748. UpdateSrcPos(breakStmt);
  4749. EmitEnsureInstructionAt();
  4750. BfBreakData* breakData = mCurMethodState->mBreakData;
  4751. if (breakStmt->mLabel != NULL)
  4752. {
  4753. breakData = FindBreakData(breakStmt->mLabel);
  4754. }
  4755. else
  4756. {
  4757. while (breakData != NULL)
  4758. {
  4759. if (breakData->mIRBreakBlock)
  4760. break;
  4761. breakData = breakData->mPrevBreakData;
  4762. }
  4763. }
  4764. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4765. {
  4766. BfScopeData* scope = NULL;
  4767. if (breakData != NULL)
  4768. scope = breakData->mScope;
  4769. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(breakStmt->mLabel))
  4770. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, breakStmt->mBreakNode, scope);
  4771. }
  4772. if ((breakData == NULL) || (!breakData->mIRBreakBlock))
  4773. {
  4774. if (inMixinDecl)
  4775. {
  4776. // Our mixin may just require that we're injected into a breakable scope
  4777. }
  4778. else
  4779. Fail("'break' not applicable in this block", breakStmt);
  4780. return;
  4781. }
  4782. if (mCurMethodState->mInDeferredBlock)
  4783. {
  4784. auto checkScope = mCurMethodState->mCurScope;
  4785. while (checkScope != NULL)
  4786. {
  4787. if (checkScope == breakData->mScope)
  4788. break;
  4789. if (checkScope->mIsDeferredBlock)
  4790. {
  4791. Fail("The break target crosses a deferred block boundary", breakStmt);
  4792. return;
  4793. }
  4794. checkScope = checkScope->mPrevScope;
  4795. }
  4796. }
  4797. if (HasDeferredScopeCalls(breakData->mScope))
  4798. {
  4799. EmitDeferredScopeCalls(true, breakData->mScope, breakData->mIRBreakBlock);
  4800. }
  4801. else
  4802. {
  4803. mBfIRBuilder->CreateBr(breakData->mIRBreakBlock);
  4804. }
  4805. mCurMethodState->mLeftBlockUncond = true;
  4806. bool isCond = false;
  4807. int uncondScopeDepth = 0;
  4808. if (mCurMethodState->mCurScope != NULL)
  4809. uncondScopeDepth = mCurMethodState->mCurScope->mScopeDepth + 1;
  4810. BfIRValue earliestValueScopeStart;
  4811. auto checkScope = mCurMethodState->mCurScope;
  4812. while (checkScope != NULL)
  4813. {
  4814. if (!isCond)
  4815. uncondScopeDepth = checkScope->mScopeDepth;
  4816. if ((checkScope->mOuterIsConditional) && (!checkScope->mIsSharedTempBlock))
  4817. isCond = true;
  4818. if (checkScope->mValueScopeStart)
  4819. earliestValueScopeStart = checkScope->mValueScopeStart;
  4820. if (checkScope == breakData->mScope)
  4821. break;
  4822. checkScope = checkScope->mPrevScope;
  4823. }
  4824. auto checkLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  4825. while (checkLocalAssignData != NULL)
  4826. {
  4827. if ((checkLocalAssignData->mScopeData != NULL) && (checkLocalAssignData->mScopeData->mScopeDepth >= breakData->mScope->mScopeDepth))
  4828. {
  4829. if (checkLocalAssignData->mScopeData->mScopeDepth >= uncondScopeDepth)
  4830. checkLocalAssignData->mLeftBlockUncond = true;
  4831. checkLocalAssignData->mLeftBlock = true;
  4832. checkLocalAssignData->mHadBreak = true;
  4833. }
  4834. checkLocalAssignData = checkLocalAssignData->mChainedAssignData;
  4835. }
  4836. MarkScopeLeft(breakData->mScope);
  4837. ValueScopeEnd(earliestValueScopeStart);
  4838. auto checkBreakData = mCurMethodState->mBreakData;
  4839. while (true)
  4840. {
  4841. checkBreakData->mHadBreak = true;
  4842. if (checkBreakData == breakData)
  4843. break;
  4844. checkBreakData = checkBreakData->mPrevBreakData;
  4845. }
  4846. }
  4847. void BfModule::Visit(BfContinueStatement* continueStmt)
  4848. {
  4849. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  4850. UpdateSrcPos(continueStmt);
  4851. EmitEnsureInstructionAt();
  4852. // If we're in a switch, 'break' is valid but we need to continue looking outward for a 'continue' target
  4853. BfBreakData* breakData = mCurMethodState->mBreakData;
  4854. if (continueStmt->mLabel != NULL)
  4855. {
  4856. breakData = FindBreakData(continueStmt->mLabel);
  4857. if ((breakData != NULL) && (!breakData->mIRContinueBlock))
  4858. {
  4859. Fail(StrFormat("'continue' not applicable in '%s'", continueStmt->mLabel->ToString().c_str()), continueStmt);
  4860. return;
  4861. }
  4862. }
  4863. else
  4864. {
  4865. while (breakData != NULL)
  4866. {
  4867. if (breakData->mIRContinueBlock)
  4868. break;
  4869. breakData = breakData->mPrevBreakData;
  4870. }
  4871. }
  4872. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4873. {
  4874. BfScopeData* scope = NULL;
  4875. if (breakData != NULL)
  4876. scope = breakData->mScope;
  4877. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(continueStmt->mLabel))
  4878. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, continueStmt->mContinueNode, scope);
  4879. }
  4880. if ((breakData == NULL) || (!breakData->mIRContinueBlock))
  4881. {
  4882. if (inMixinDecl)
  4883. {
  4884. // Our mixin may just require that we're injected into a breakable scope
  4885. }
  4886. else
  4887. Fail("'continue' not applicable in this block", continueStmt);
  4888. return;
  4889. }
  4890. BfIRValue earliestValueScopeStart;
  4891. // We don't want to close out our own scope, we want to close out any scopes that were opened after us
  4892. auto nextScope = mCurMethodState->mCurScope;
  4893. while (nextScope != NULL)
  4894. {
  4895. if (nextScope->mValueScopeStart)
  4896. earliestValueScopeStart = nextScope->mValueScopeStart;
  4897. if (nextScope->mPrevScope == breakData->mScope)
  4898. break;
  4899. nextScope = nextScope->mPrevScope;
  4900. }
  4901. if (breakData->mInnerValueScopeStart)
  4902. earliestValueScopeStart = breakData->mInnerValueScopeStart;
  4903. if (mCurMethodState->mInDeferredBlock)
  4904. {
  4905. auto checkScope = mCurMethodState->mCurScope;
  4906. while (checkScope != NULL)
  4907. {
  4908. if (checkScope == breakData->mScope)
  4909. break;
  4910. if (checkScope->mIsDeferredBlock)
  4911. {
  4912. Fail("The continue target crosses a deferred block boundary", continueStmt);
  4913. return;
  4914. }
  4915. checkScope = checkScope->mPrevScope;
  4916. }
  4917. }
  4918. if ((nextScope != NULL) && (HasDeferredScopeCalls(nextScope)))
  4919. {
  4920. EmitDeferredScopeCalls(true, nextScope, breakData->mIRContinueBlock);
  4921. }
  4922. else
  4923. {
  4924. mBfIRBuilder->CreateBr(breakData->mIRContinueBlock);
  4925. }
  4926. MarkScopeLeft(breakData->mScope);
  4927. ValueScopeEnd(earliestValueScopeStart);
  4928. mCurMethodState->mLeftBlockUncond = true;
  4929. if (!mCurMethodState->mInPostReturn)
  4930. mCurMethodState->mHadContinue = true;
  4931. }
  4932. void BfModule::Visit(BfFallthroughStatement* fallthroughStmt)
  4933. {
  4934. UpdateSrcPos(fallthroughStmt);
  4935. BfBreakData* breakData = mCurMethodState->mBreakData;
  4936. if (fallthroughStmt->mLabel != NULL)
  4937. {
  4938. breakData = FindBreakData(fallthroughStmt->mLabel);
  4939. }
  4940. else
  4941. {
  4942. while (breakData != NULL)
  4943. {
  4944. if (breakData->mIRFallthroughBlock)
  4945. break;
  4946. breakData = breakData->mPrevBreakData;
  4947. }
  4948. }
  4949. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4950. {
  4951. BfScopeData* scope = NULL;
  4952. if (breakData != NULL)
  4953. scope = breakData->mScope;
  4954. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(fallthroughStmt->mLabel))
  4955. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(identifer, fallthroughStmt->mFallthroughToken, scope);
  4956. }
  4957. if (mCurMethodState->mInDeferredBlock)
  4958. {
  4959. auto checkScope = mCurMethodState->mCurScope;
  4960. while (checkScope != NULL)
  4961. {
  4962. if (checkScope == breakData->mScope)
  4963. break;
  4964. if (checkScope->mIsDeferredBlock)
  4965. {
  4966. Fail("The fallthrough crosses a deferred block boundary", fallthroughStmt);
  4967. return;
  4968. }
  4969. checkScope = checkScope->mPrevScope;
  4970. }
  4971. }
  4972. if (breakData == NULL)
  4973. {
  4974. Fail("'fallthrough' not applicable in this block", fallthroughStmt);
  4975. return;
  4976. }
  4977. EmitDeferredScopeCalls(true, breakData->mScope, breakData->mIRFallthroughBlock);
  4978. mCurMethodState->mLeftBlockUncond = true; // Not really a return, but handled the same way
  4979. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  4980. mCurMethodState->mDeferredLocalAssignData->mHadFallthrough = true;
  4981. auto checkBreakData = mCurMethodState->mBreakData;
  4982. while (true)
  4983. {
  4984. if (checkBreakData == breakData)
  4985. break;
  4986. checkBreakData->mHadBreak = true;
  4987. checkBreakData = checkBreakData->mPrevBreakData;
  4988. }
  4989. }
  4990. void BfModule::Visit(BfUsingStatement* usingStmt)
  4991. {
  4992. UpdateSrcPos(usingStmt);
  4993. mCurMethodState->mInHeadScope = false;
  4994. BfScopeData newScope;
  4995. mCurMethodState->AddScope(&newScope);
  4996. NewScopeState();
  4997. if (usingStmt->mVariableDeclaration != NULL)
  4998. UpdateSrcPos(usingStmt->mVariableDeclaration);
  4999. BfTypedValue embeddedValue;
  5000. SizedArray<BfIRValue, 1> llvmArgs;
  5001. BfModuleMethodInstance moduleMethodInstance;
  5002. BfFunctionBindResult functionBindResult;
  5003. BfExprEvaluator exprEvaluator(this);
  5004. bool failed = false;
  5005. if (usingStmt->mVariableDeclaration == NULL)
  5006. {
  5007. AssertErrorState();
  5008. failed = true;
  5009. }
  5010. else if (usingStmt->mVariableDeclaration->mNameNode != NULL)
  5011. {
  5012. BfLocalVariable* localVar = HandleVariableDeclaration(usingStmt->mVariableDeclaration);
  5013. if (localVar == NULL)
  5014. {
  5015. AssertErrorState();
  5016. failed = true;
  5017. }
  5018. else
  5019. {
  5020. embeddedValue = exprEvaluator.LoadLocal(localVar);
  5021. }
  5022. //exprEvaluator.CheckModifyResult(embeddedValue, usingStmt->mVariableDeclaration->mNameNode,);
  5023. }
  5024. else
  5025. {
  5026. embeddedValue = CreateValueFromExpression(usingStmt->mVariableDeclaration->mInitializer);
  5027. if (!embeddedValue)
  5028. failed = true;
  5029. }
  5030. if (!failed)
  5031. {
  5032. auto iDisposableType = ResolveTypeDef(mCompiler->mIDisposableTypeDef)->ToTypeInstance();
  5033. auto dispMethod = GetMethodByName(iDisposableType, "Dispose");
  5034. if ((!dispMethod) || (!CanCast(embeddedValue, iDisposableType)))
  5035. {
  5036. Fail(StrFormat("Type '%s' must be implicitly convertible to 'System.IDisposable' for use in 'using' statement", TypeToString(embeddedValue.mType).c_str()), usingStmt->mVariableDeclaration);
  5037. failed = true;
  5038. }
  5039. else
  5040. {
  5041. bool mayBeNull = true;
  5042. if (embeddedValue.mType->IsStruct())
  5043. {
  5044. // It's possible that a struct can convert to an IDisposable through a conversion operator that CAN
  5045. // return null, so the only way we can know we are not null is if we are a struct that directly
  5046. // implements the interface
  5047. if (TypeIsSubTypeOf(embeddedValue.mType->ToTypeInstance(), iDisposableType))
  5048. mayBeNull = false;
  5049. }
  5050. exprEvaluator.mFunctionBindResult = &functionBindResult;
  5051. SizedArray<BfResolvedArg, 0> resolvedArgs;
  5052. BfMethodMatcher methodMatcher(usingStmt->mVariableDeclaration, this, dispMethod.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  5053. methodMatcher.CheckType(iDisposableType, embeddedValue, false);
  5054. methodMatcher.TryDevirtualizeCall(embeddedValue);
  5055. auto retVal = exprEvaluator.CreateCall(&methodMatcher, embeddedValue);
  5056. if (functionBindResult.mMethodInstance != NULL)
  5057. {
  5058. moduleMethodInstance = BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc);
  5059. AddDeferredCall(moduleMethodInstance, functionBindResult.mIRArgs, mCurMethodState->mCurScope, NULL, false, mayBeNull);
  5060. }
  5061. }
  5062. }
  5063. if (usingStmt->mEmbeddedStatement == NULL)
  5064. {
  5065. AssertErrorState();
  5066. }
  5067. else
  5068. {
  5069. VisitEmbeddedStatement(usingStmt->mEmbeddedStatement);
  5070. }
  5071. RestoreScopeState();
  5072. }
  5073. void BfModule::Visit(BfDoStatement* doStmt)
  5074. {
  5075. UpdateSrcPos(doStmt);
  5076. auto bodyBB = mBfIRBuilder->CreateBlock("do.body", true);
  5077. auto endBB = mBfIRBuilder->CreateBlock("do.end");
  5078. BfScopeData scopeData;
  5079. if (doStmt->mLabelNode != NULL)
  5080. scopeData.mLabelNode = doStmt->mLabelNode->mLabel;
  5081. mCurMethodState->AddScope(&scopeData);
  5082. NewScopeState();
  5083. BfBreakData breakData;
  5084. breakData.mIRBreakBlock = endBB;
  5085. breakData.mScope = &scopeData;
  5086. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5087. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5088. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5089. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5090. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5091. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5092. // We may have a call in the loop body
  5093. mCurMethodState->mMayNeedThisAccessCheck = true;
  5094. mBfIRBuilder->CreateBr(bodyBB);
  5095. mBfIRBuilder->SetInsertPoint(bodyBB);
  5096. VisitEmbeddedStatement(doStmt->mEmbeddedStatement);
  5097. prevDLA.Restore();
  5098. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5099. RestoreScopeState();
  5100. if (!mCurMethodState->mLeftBlockUncond)
  5101. mBfIRBuilder->CreateBr(endBB);
  5102. mCurMethodState->SetHadReturn(false);
  5103. mCurMethodState->mLeftBlockUncond = false;
  5104. mBfIRBuilder->AddBlock(endBB);
  5105. mBfIRBuilder->SetInsertPoint(endBB);
  5106. }
  5107. void BfModule::Visit(BfRepeatStatement* repeatStmt)
  5108. {
  5109. // if (repeatStmt->mCondition != NULL)
  5110. // UpdateSrcPos(repeatStmt->mCondition);
  5111. // else
  5112. UpdateSrcPos(repeatStmt);
  5113. if (repeatStmt->mRepeatToken->mToken == BfToken_Do)
  5114. {
  5115. Fail("Repeat block requires 'repeat' token", repeatStmt->mRepeatToken);
  5116. }
  5117. auto bodyBB = mBfIRBuilder->CreateBlock("repeat.body", true);
  5118. auto condBB = mBfIRBuilder->CreateBlock("repeat.cond");
  5119. auto endBB = mBfIRBuilder->CreateBlock("repeat.end");
  5120. BfScopeData scopeData;
  5121. // We set mIsLoop later
  5122. if (repeatStmt->mLabelNode != NULL)
  5123. scopeData.mLabelNode = repeatStmt->mLabelNode->mLabel;
  5124. mCurMethodState->AddScope(&scopeData);
  5125. NewScopeState();
  5126. BfBreakData breakData;
  5127. breakData.mIRContinueBlock = condBB;
  5128. breakData.mIRBreakBlock = endBB;
  5129. breakData.mScope = &scopeData;
  5130. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5131. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5132. // We may have a call in the loop body
  5133. mCurMethodState->mMayNeedThisAccessCheck = true;
  5134. mBfIRBuilder->CreateBr(bodyBB);
  5135. mBfIRBuilder->SetInsertPoint(bodyBB);
  5136. scopeData.mIsLoop = true;
  5137. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5138. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5139. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5140. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5141. VisitEmbeddedStatement(repeatStmt->mEmbeddedStatement);
  5142. if (!mCurMethodState->mLeftBlockUncond)
  5143. mBfIRBuilder->CreateBr(condBB);
  5144. mCurMethodState->SetHadReturn(false);
  5145. mCurMethodState->mLeftBlockUncond = false;
  5146. mCurMethodState->mLeftBlockCond = false;
  5147. mBfIRBuilder->AddBlock(condBB);
  5148. mBfIRBuilder->SetInsertPoint(condBB);
  5149. bool isInfiniteLoop = false;
  5150. if (repeatStmt->mCondition != NULL)
  5151. {
  5152. UpdateSrcPos(repeatStmt->mCondition);
  5153. auto checkVal = CreateValueFromExpression(repeatStmt->mCondition, GetPrimitiveType(BfTypeCode_Boolean));
  5154. if (checkVal)
  5155. {
  5156. if ((!breakData.mHadBreak) && (checkVal.mValue.IsConst()))
  5157. {
  5158. auto constVal = mBfIRBuilder->GetConstantById(checkVal.mValue.mId);
  5159. if (constVal->mTypeCode == BfTypeCode_Boolean)
  5160. isInfiniteLoop = constVal->mBool;
  5161. }
  5162. mBfIRBuilder->CreateCondBr(checkVal.mValue, bodyBB, endBB);
  5163. mBfIRBuilder->AddBlock(endBB);
  5164. mBfIRBuilder->SetInsertPoint(endBB);
  5165. }
  5166. }
  5167. RestoreScopeState();
  5168. prevDLA.Restore();
  5169. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5170. if (isInfiniteLoop)
  5171. EmitDefaultReturn();
  5172. }
  5173. void BfModule::Visit(BfWhileStatement* whileStmt)
  5174. {
  5175. UpdateSrcPos(whileStmt);
  5176. bool prevHadReturn = mCurMethodState->mHadReturn;
  5177. auto condBB = mBfIRBuilder->CreateBlock("while.cond");
  5178. auto bodyBB = mBfIRBuilder->CreateBlock("while.body");
  5179. auto endBB = mBfIRBuilder->CreateBlock("while.end");
  5180. mCurMethodState->mInHeadScope = false;
  5181. BfScopeData scopeData;
  5182. scopeData.mScopeKind = BfScopeKind_StatementTarget_Conditional;
  5183. scopeData.mIsLoop = true;
  5184. if (whileStmt->mLabelNode != NULL)
  5185. scopeData.mLabelNode = whileStmt->mLabelNode->mLabel;
  5186. scopeData.mValueScopeStart = ValueScopeStart();
  5187. mCurMethodState->AddScope(&scopeData);
  5188. NewScopeState();
  5189. BfBreakData breakData;
  5190. breakData.mIRContinueBlock = condBB;
  5191. breakData.mIRBreakBlock = endBB;
  5192. breakData.mScope = &scopeData;
  5193. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5194. breakData.mInnerValueScopeStart = scopeData.mValueScopeStart;
  5195. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5196. mBfIRBuilder->AddBlock(condBB);
  5197. mBfIRBuilder->CreateBr(condBB);
  5198. mBfIRBuilder->SetInsertPoint(condBB);
  5199. BfTypedValue checkVal;
  5200. if (whileStmt->mCondition != NULL)
  5201. {
  5202. UpdateSrcPos(whileStmt->mCondition);
  5203. checkVal = CreateValueFromExpression(whileStmt->mCondition, GetPrimitiveType(BfTypeCode_Boolean));
  5204. }
  5205. if (!checkVal)
  5206. {
  5207. AssertErrorState();
  5208. checkVal = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Boolean));
  5209. }
  5210. bool isInfiniteLoop = false;
  5211. bool isFalseLoop = false;
  5212. if (checkVal.mValue.IsConst())
  5213. {
  5214. EmitEnsureInstructionAt();
  5215. auto constVal = mBfIRBuilder->GetConstantById(checkVal.mValue.mId);
  5216. if (constVal->mTypeCode == BfTypeCode_Boolean)
  5217. {
  5218. isInfiniteLoop = constVal->mBool;
  5219. isFalseLoop = !isInfiniteLoop;
  5220. }
  5221. }
  5222. // We may have a call in the loop body
  5223. mCurMethodState->mMayNeedThisAccessCheck = true;
  5224. // For BeefBackend we continue to do CondBr because it helps our flow analysis and we optimize it anyway
  5225. if ((isInfiniteLoop) && (!IsTargetingBeefBackend()))
  5226. mBfIRBuilder->CreateBr(bodyBB);
  5227. else if (isFalseLoop)
  5228. mBfIRBuilder->CreateBr(endBB);
  5229. else
  5230. mBfIRBuilder->CreateCondBr(checkVal.mValue, bodyBB, endBB);
  5231. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5232. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5233. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5234. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5235. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5236. deferredLocalAssignData.mIsUnconditional = isInfiniteLoop;
  5237. mBfIRBuilder->AddBlock(bodyBB);
  5238. mBfIRBuilder->SetInsertPoint(bodyBB);
  5239. if (whileStmt->mEmbeddedStatement != NULL)
  5240. {
  5241. if (isFalseLoop)
  5242. {
  5243. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5244. SetAndRestoreValue<bool> prevInConstIgnore(mCurMethodState->mCurScope->mInConstIgnore, true);
  5245. VisitEmbeddedStatement(whileStmt->mEmbeddedStatement);
  5246. }
  5247. else
  5248. VisitEmbeddedStatement(whileStmt->mEmbeddedStatement);
  5249. }
  5250. else
  5251. {
  5252. AssertErrorState();
  5253. }
  5254. if (breakData.mHadBreak)
  5255. {
  5256. isInfiniteLoop = false;
  5257. }
  5258. if ((!mCurMethodState->mLeftBlockUncond) && (!isFalseLoop))
  5259. {
  5260. mBfIRBuilder->CreateBr(condBB);
  5261. }
  5262. if (!isInfiniteLoop)
  5263. mCurMethodState->mHadReturn = prevHadReturn;
  5264. mCurMethodState->mLeftBlockUncond = false;
  5265. mCurMethodState->mLeftBlockCond = false;
  5266. mBfIRBuilder->AddBlock(endBB);
  5267. mBfIRBuilder->SetInsertPoint(endBB);
  5268. if (isFalseLoop)
  5269. {
  5270. mBfIRBuilder->EraseFromParent(bodyBB);
  5271. }
  5272. RestoreScopeState();
  5273. if ((isInfiniteLoop) && (mCurMethodInstance != NULL))
  5274. EmitDefaultReturn();
  5275. }
  5276. void BfModule::Visit(BfForStatement* forStmt)
  5277. {
  5278. auto autoComplete = mCompiler->GetAutoComplete();
  5279. if (autoComplete != NULL)
  5280. autoComplete->CheckIdentifier(forStmt->mForToken, true);
  5281. UpdateSrcPos(forStmt);
  5282. auto startBB = mBfIRBuilder->CreateBlock("for.start", true);
  5283. mBfIRBuilder->CreateBr(startBB);
  5284. mBfIRBuilder->SetInsertPoint(startBB);
  5285. BfScopeData scopeData;
  5286. scopeData.mIsLoop = true;
  5287. if (forStmt->mLabelNode != NULL)
  5288. scopeData.mLabelNode = forStmt->mLabelNode->mLabel;
  5289. scopeData.mCloseNode = forStmt;
  5290. scopeData.mValueScopeStart = ValueScopeStart();
  5291. mCurMethodState->AddScope(&scopeData);
  5292. NewScopeState();
  5293. for (auto initializer : forStmt->mInitializers)
  5294. {
  5295. VisitChild(initializer);
  5296. }
  5297. // We may have a call in the loop body
  5298. mCurMethodState->mMayNeedThisAccessCheck = true;
  5299. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  5300. auto condBB = mBfIRBuilder->CreateBlock("for.cond", true);
  5301. auto bodyBB = mBfIRBuilder->CreateBlock("for.body");
  5302. auto incBB = mBfIRBuilder->CreateBlock("for.inc");
  5303. auto endBB = mBfIRBuilder->CreateBlock("for.end");
  5304. BfBreakData breakData;
  5305. breakData.mIRContinueBlock = incBB;
  5306. breakData.mIRBreakBlock = endBB;
  5307. breakData.mScope = &scopeData;
  5308. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5309. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5310. mBfIRBuilder->CreateBr(condBB);
  5311. bool isInfiniteLoop = false;
  5312. mBfIRBuilder->SetInsertPoint(condBB);
  5313. if (forStmt->mCondition != NULL)
  5314. {
  5315. auto conditionValue = CreateValueFromExpression(forStmt->mCondition, boolType);
  5316. if (!conditionValue)
  5317. conditionValue = GetDefaultTypedValue(boolType);
  5318. auto constant = mBfIRBuilder->GetConstant(conditionValue.mValue);
  5319. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_Boolean))
  5320. isInfiniteLoop = constant->mBool;
  5321. ValueScopeEnd(scopeData.mValueScopeStart);
  5322. mBfIRBuilder->CreateCondBr(conditionValue.mValue, bodyBB, endBB);
  5323. }
  5324. else
  5325. {
  5326. isInfiniteLoop = true;
  5327. mBfIRBuilder->CreateBr(bodyBB);
  5328. }
  5329. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5330. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5331. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5332. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5333. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5334. mBfIRBuilder->AddBlock(bodyBB);
  5335. mBfIRBuilder->SetInsertPoint(bodyBB);
  5336. if (forStmt->mEmbeddedStatement != NULL)
  5337. {
  5338. VisitEmbeddedStatement(forStmt->mEmbeddedStatement);
  5339. }
  5340. if (!mCurMethodState->mLeftBlockUncond)
  5341. mBfIRBuilder->CreateBr(incBB);
  5342. mBfIRBuilder->AddBlock(incBB);
  5343. mBfIRBuilder->SetInsertPoint(incBB);
  5344. for (auto itrStmt : forStmt->mIterators)
  5345. {
  5346. VisitChild(itrStmt);
  5347. if ((mCurMethodState->mLeftBlockUncond) && (!mCurMethodState->mHadContinue) && (!mCurMethodState->mInPostReturn))
  5348. Warn(BfWarning_CS0162_UnreachableCode, "Unreachable code", itrStmt);
  5349. }
  5350. ValueScopeEnd(scopeData.mValueScopeStart);
  5351. mBfIRBuilder->CreateBr(condBB);
  5352. mBfIRBuilder->AddBlock(endBB);
  5353. mBfIRBuilder->SetInsertPoint(endBB);
  5354. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  5355. mCurMethodState->SetHadReturn(false);
  5356. mCurMethodState->mLeftBlockUncond = false;
  5357. mCurMethodState->mLeftBlockCond = false;
  5358. if (breakData.mHadBreak)
  5359. isInfiniteLoop = false;
  5360. RestoreScopeState();
  5361. if (isInfiniteLoop)
  5362. EmitDefaultReturn();
  5363. }
  5364. void BfModule::DoForLess(BfForEachStatement* forEachStmt)
  5365. {
  5366. UpdateSrcPos(forEachStmt);
  5367. auto startBB = mBfIRBuilder->GetInsertBlock();
  5368. auto condBB = mBfIRBuilder->CreateBlock("forless.cond", true);
  5369. mBfIRBuilder->SetInsertPoint(condBB);
  5370. BfScopeData scopeData;
  5371. // We set mIsLoop later
  5372. if (forEachStmt->mLabelNode != NULL)
  5373. scopeData.mLabelNode = forEachStmt->mLabelNode->mLabel;
  5374. mCurMethodState->AddScope(&scopeData);
  5375. NewScopeState();
  5376. auto autoComplete = mCompiler->GetAutoComplete();
  5377. auto isLet = BfNodeDynCast<BfLetTypeReference>(forEachStmt->mVariableTypeRef) != 0;
  5378. auto isVar = BfNodeDynCast<BfVarTypeReference>(forEachStmt->mVariableTypeRef) != 0;
  5379. BfTypedValue target;
  5380. BfType* varType = NULL;
  5381. bool didInference = false;
  5382. if (isLet || isVar)
  5383. {
  5384. if (forEachStmt->mCollectionExpression != NULL)
  5385. target = CreateValueFromExpression(forEachStmt->mCollectionExpression);
  5386. if (target)
  5387. {
  5388. FixIntUnknown(target);
  5389. varType = target.mType;
  5390. }
  5391. if (autoComplete != NULL)
  5392. autoComplete->CheckVarResolution(forEachStmt->mVariableTypeRef, varType);
  5393. didInference = true;
  5394. }
  5395. else
  5396. {
  5397. varType = ResolveTypeRef(forEachStmt->mVariableTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  5398. if (forEachStmt->mCollectionExpression != NULL)
  5399. target = CreateValueFromExpression(forEachStmt->mCollectionExpression, varType);
  5400. }
  5401. if (varType == NULL)
  5402. varType = GetPrimitiveType(BfTypeCode_IntPtr);
  5403. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5404. deferredLocalAssignData.mIsIfCondition = true;
  5405. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, true);
  5406. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5407. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5408. deferredLocalAssignData.mIsIfCondition = false;
  5409. // The "extend chain" is only valid for the conditional -- since that expression may contain unconditionally executed and
  5410. // conditionally executed code (in the case of "(GetVal(out a) && GetVal(out b))" for example
  5411. mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  5412. BfType* checkType = varType;
  5413. if (checkType->IsTypedPrimitive())
  5414. checkType = checkType->GetUnderlyingType();
  5415. if (!checkType->IsIntegral())
  5416. {
  5417. Fail(StrFormat("Cannot iterate over '%s' in for-less statements, only integer types are allowed", TypeToString(varType).c_str()), forEachStmt->mVariableTypeRef);
  5418. varType = GetPrimitiveType(BfTypeCode_IntPtr);
  5419. if (didInference)
  5420. target = GetDefaultTypedValue(varType);
  5421. }
  5422. PopulateType(varType, BfPopulateType_Data);
  5423. auto condEndBB = mBfIRBuilder->GetInsertBlock();
  5424. mBfIRBuilder->SetInsertPoint(startBB);
  5425. BfLocalVariable* localDef = new BfLocalVariable();
  5426. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(forEachStmt->mVariableName);
  5427. localDef->mName = localDef->mNameNode->ToString();
  5428. localDef->mResolvedType = varType;
  5429. BfIRValue varInst;
  5430. if (!varType->IsValuelessType())
  5431. {
  5432. varInst = CreateAlloca(varType);
  5433. }
  5434. localDef->mAddr = varInst;
  5435. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5436. localDef->mReadFromId = 0;
  5437. localDef->mIsReadOnly = isLet || (forEachStmt->mReadOnlyToken != NULL);
  5438. CheckVariableDef(localDef);
  5439. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(varType), localDef->mAddr, varType->mAlign);
  5440. localDef->Init();
  5441. UpdateExprSrcPos(forEachStmt->mVariableName);
  5442. AddLocalVariableDef(localDef, true);
  5443. auto bodyBB = mBfIRBuilder->CreateBlock("forless.body");
  5444. auto incBB = mBfIRBuilder->CreateBlock("forless.inc");
  5445. auto endBB = mBfIRBuilder->CreateBlock("forless.end");
  5446. BfBreakData breakData;
  5447. breakData.mIRContinueBlock = incBB;
  5448. breakData.mIRBreakBlock = endBB;
  5449. breakData.mScope = &scopeData;
  5450. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  5451. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  5452. mBfIRBuilder->CreateBr(condBB);
  5453. mBfIRBuilder->SetInsertPoint(condEndBB);
  5454. if (forEachStmt->mCollectionExpression != NULL)
  5455. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  5456. BfIRValue conditionValue;
  5457. // We may have a call in the loop body
  5458. mCurMethodState->mMayNeedThisAccessCheck = true;
  5459. // Cond
  5460. auto valueScopeStart = ValueScopeStart();
  5461. auto localVal = mBfIRBuilder->CreateAlignedLoad(localDef->mAddr, localDef->mResolvedType->mAlign);
  5462. if (!target)
  5463. {
  5464. // Soldier on
  5465. target = GetDefaultTypedValue(varType);
  5466. }
  5467. if (forEachStmt->mInToken->mToken == BfToken_LessEquals)
  5468. conditionValue = mBfIRBuilder->CreateCmpLTE(localVal, target.mValue, varType->IsSigned());
  5469. else
  5470. conditionValue = mBfIRBuilder->CreateCmpLT(localVal, target.mValue, varType->IsSigned());
  5471. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  5472. ValueScopeEnd(valueScopeStart);
  5473. mBfIRBuilder->AddBlock(bodyBB);
  5474. mBfIRBuilder->SetInsertPoint(bodyBB);
  5475. // Body
  5476. scopeData.mIsLoop = true;
  5477. if (forEachStmt->mEmbeddedStatement != NULL)
  5478. {
  5479. VisitEmbeddedStatement(forEachStmt->mEmbeddedStatement);
  5480. }
  5481. // Inc
  5482. if (!mCurMethodState->mLeftBlockUncond)
  5483. {
  5484. mBfIRBuilder->CreateBr(incBB);
  5485. }
  5486. mBfIRBuilder->AddBlock(incBB);
  5487. mBfIRBuilder->SetInsertPoint(incBB);
  5488. if (forEachStmt->mCollectionExpression != NULL)
  5489. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  5490. auto one = GetConstValue(1, localDef->mResolvedType);
  5491. // We have to reload localVal before the inc, user logic could have changed it
  5492. localVal = mBfIRBuilder->CreateAlignedLoad(localDef->mAddr, localDef->mResolvedType->mAlign);
  5493. auto result = mBfIRBuilder->CreateAdd(localVal, one);
  5494. mBfIRBuilder->CreateAlignedStore(result, localDef->mAddr, localDef->mResolvedType->mAlign);
  5495. ValueScopeEnd(valueScopeStart);
  5496. mBfIRBuilder->CreateBr(condBB);
  5497. mBfIRBuilder->AddBlock(endBB);
  5498. mBfIRBuilder->SetInsertPoint(endBB);
  5499. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  5500. mCurMethodState->SetHadReturn(false);
  5501. mCurMethodState->mLeftBlockUncond = false;
  5502. mCurMethodState->mLeftBlockCond = false;
  5503. bool definitelyExecuted = false;
  5504. if (target.mValue.IsConst())
  5505. {
  5506. auto constant = mBfIRBuilder->GetConstant(target.mValue);
  5507. if (constant->mInt32 > 0)
  5508. definitelyExecuted = true;
  5509. }
  5510. prevDLA.Restore();
  5511. if (definitelyExecuted)
  5512. mCurMethodState->ApplyDeferredLocalAssignData(deferredLocalAssignData);
  5513. RestoreScopeState();
  5514. }
  5515. void BfModule::Visit(BfForEachStatement* forEachStmt)
  5516. {
  5517. if ((forEachStmt->mInToken != NULL) &&
  5518. ((forEachStmt->mInToken->GetToken() == BfToken_LChevron) || (forEachStmt->mInToken->GetToken() == BfToken_LessEquals)))
  5519. {
  5520. DoForLess(forEachStmt);
  5521. return;
  5522. }
  5523. auto autoComplete = mCompiler->GetAutoComplete();
  5524. UpdateSrcPos(forEachStmt);
  5525. BfScopeData scopeData;
  5526. // We set mIsLoop after the non-looped initializations
  5527. scopeData.mValueScopeStart = ValueScopeStart();
  5528. mCurMethodState->AddScope(&scopeData);
  5529. NewScopeState();
  5530. bool isRefExpression = false;
  5531. BfExpression* collectionExpr = forEachStmt->mCollectionExpression;
  5532. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(collectionExpr))
  5533. {
  5534. if ((unaryOpExpr->mOp == BfUnaryOp_Ref) || (unaryOpExpr->mOp == BfUnaryOp_Mut))
  5535. {
  5536. isRefExpression = true;
  5537. collectionExpr = unaryOpExpr->mExpression;
  5538. }
  5539. }
  5540. BfTypedValue target;
  5541. if (collectionExpr != NULL)
  5542. target = CreateValueFromExpression(collectionExpr);
  5543. if (!target)
  5544. {
  5545. // Soldier on
  5546. target = BfTypedValue(GetDefaultValue(mContext->mBfObjectType), mContext->mBfObjectType);
  5547. }
  5548. bool isLet = (forEachStmt->mVariableTypeRef != NULL) && (forEachStmt->mVariableTypeRef->IsA<BfLetTypeReference>());
  5549. BfType* varType = NULL;
  5550. bool inferVarType = false;
  5551. if ((forEachStmt->mVariableTypeRef == NULL) || (forEachStmt->mVariableTypeRef->IsA<BfVarTypeReference>()) || (isLet))
  5552. {
  5553. if (target.mType->IsSizedArray())
  5554. {
  5555. varType = target.mType->GetUnderlyingType();
  5556. if (isRefExpression)
  5557. varType = CreateRefType(varType);
  5558. }
  5559. else if (target.mType->IsArray())
  5560. {
  5561. varType = target.mType->GetUnderlyingType();
  5562. if (isRefExpression)
  5563. varType = CreateRefType(varType);
  5564. }
  5565. else
  5566. inferVarType = true;
  5567. }
  5568. else
  5569. {
  5570. if (autoComplete != NULL)
  5571. autoComplete->CheckTypeRef(forEachStmt->mVariableTypeRef, false);
  5572. varType = ResolveTypeRef(forEachStmt->mVariableTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  5573. }
  5574. if (varType == NULL)
  5575. varType = GetPrimitiveType(BfTypeCode_Var);
  5576. bool isArray = target.mType->IsArray();
  5577. bool isSizedArray = target.mType->IsSizedArray();
  5578. bool isVarEnumerator = target.mType->IsVar();
  5579. // Array
  5580. BfType* itrType;
  5581. BfTypedValue itr;
  5582. BfTypeInstance* itrInterface = NULL;
  5583. BfTypeInstance* refItrInterface = NULL;
  5584. if (isVarEnumerator)
  5585. varType = GetPrimitiveType(BfTypeCode_Var);
  5586. BfGenericParamInstance* genericParamInst = NULL;
  5587. if (target.mType->IsGenericParam())
  5588. {
  5589. genericParamInst = GetGenericParamInstance((BfGenericParamType*)target.mType);
  5590. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5591. {
  5592. varType = GetPrimitiveType(BfTypeCode_Var);
  5593. isVarEnumerator = true;
  5594. }
  5595. if (genericParamInst->mTypeConstraint != NULL)
  5596. {
  5597. if (genericParamInst->mTypeConstraint->IsVar())
  5598. {
  5599. varType = GetPrimitiveType(BfTypeCode_Var);
  5600. isVarEnumerator = true;
  5601. }
  5602. if (genericParamInst->mTypeConstraint->IsGenericTypeInstance())
  5603. {
  5604. auto genericConstraintType = (BfTypeInstance*)genericParamInst->mTypeConstraint;
  5605. if (genericConstraintType->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  5606. {
  5607. varType = genericConstraintType->mGenericTypeInfo->mTypeGenericArguments[0];
  5608. isVarEnumerator = true;
  5609. }
  5610. }
  5611. }
  5612. }
  5613. if (target.mType->IsConcreteInterfaceType())
  5614. target.mType = target.mType->GetUnderlyingType();
  5615. if (isArray || isSizedArray)
  5616. {
  5617. itrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5618. BfIRValue itrInst = CreateAlloca(itrType);
  5619. itr = BfTypedValue(itrInst, itrType, true);
  5620. }
  5621. else if (isVarEnumerator)
  5622. {
  5623. // Generic method or mixin decl
  5624. }
  5625. else if ((!target.mType->IsTypeInstance()) && (genericParamInst == NULL))
  5626. {
  5627. Fail(StrFormat("Type '%s' cannot be used in enumeration", TypeToString(target.mType).c_str()), forEachStmt->mCollectionExpression);
  5628. }
  5629. else if (forEachStmt->mCollectionExpression != NULL)
  5630. {
  5631. auto targetTypeInstance = target.mType->ToTypeInstance();
  5632. itr = target;
  5633. bool hadGetEnumeratorType = false;
  5634. if (genericParamInst != NULL)
  5635. {
  5636. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  5637. {
  5638. if (ifaceConstraint->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef))
  5639. {
  5640. if (targetTypeInstance != NULL)
  5641. {
  5642. targetTypeInstance = NULL;
  5643. break;
  5644. }
  5645. targetTypeInstance = ifaceConstraint->ToTypeInstance();
  5646. }
  5647. }
  5648. }
  5649. if (targetTypeInstance != NULL)
  5650. {
  5651. PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  5652. auto getEnumeratorMethod = GetMethodByName(targetTypeInstance, "GetEnumerator", 0, true);
  5653. if (!getEnumeratorMethod)
  5654. {
  5655. hadGetEnumeratorType = false;
  5656. }
  5657. else if (getEnumeratorMethod.mMethodInstance->mMethodDef->mIsStatic)
  5658. {
  5659. hadGetEnumeratorType = true;
  5660. Fail(StrFormat("Type '%s' does not contain a non-static 'GetEnumerator' method", TypeToString(targetTypeInstance).c_str()), forEachStmt->mCollectionExpression);
  5661. }
  5662. else
  5663. {
  5664. if (getEnumeratorMethod.mMethodInstance->mMethodDef->mIsConcrete)
  5665. {
  5666. hadGetEnumeratorType = true;
  5667. if (genericParamInst != NULL)
  5668. {
  5669. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) == 0)
  5670. Fail(StrFormat("Iteration requires a concrete implementation of '%s', consider adding 'concrete' constraint to '%s'", TypeToString(targetTypeInstance).c_str(), genericParamInst->GetName().c_str()), forEachStmt->mCollectionExpression);
  5671. }
  5672. else
  5673. Fail(StrFormat("Iteration requires a concrete implementation of '%s'", TypeToString(targetTypeInstance).c_str()), forEachStmt->mCollectionExpression);
  5674. }
  5675. hadGetEnumeratorType = true;
  5676. BfExprEvaluator exprEvaluator(this);
  5677. SizedArray<BfIRValue, 1> args;
  5678. auto castedTarget = Cast(forEachStmt->mCollectionExpression, target, getEnumeratorMethod.mMethodInstance->GetOwner());
  5679. exprEvaluator.PushThis(forEachStmt->mCollectionExpression, castedTarget, getEnumeratorMethod.mMethodInstance, args);
  5680. itr = exprEvaluator.CreateCall(forEachStmt->mCollectionExpression, getEnumeratorMethod.mMethodInstance, IsSkippingExtraResolveChecks() ? BfIRValue() : getEnumeratorMethod.mFunc, false, args);
  5681. if (itr.mType->IsConcreteInterfaceType())
  5682. itr.mType = itr.mType->GetUnderlyingType();
  5683. }
  5684. }
  5685. if (itr)
  5686. {
  5687. PopulateType(itr.mType, BfPopulateType_DataAndMethods);
  5688. BfTypeInstance* genericItrInterface = NULL;
  5689. auto _CheckInterface = [&](BfTypeInstance* interface)
  5690. {
  5691. if (interface->IsInstanceOf(isRefExpression ? mCompiler->mGenericIRefEnumeratorTypeDef : mCompiler->mGenericIEnumeratorTypeDef))
  5692. {
  5693. if (genericItrInterface != NULL)
  5694. {
  5695. Fail(StrFormat("Type '%s' implements multiple %s<T> interfaces", TypeToString(itr.mType).c_str(), isRefExpression ? "IRefEnumerator" : "IEnumerator"), forEachStmt->mCollectionExpression);
  5696. }
  5697. itrInterface = interface;
  5698. genericItrInterface = itrInterface->ToGenericTypeInstance();
  5699. if (inferVarType)
  5700. {
  5701. varType = genericItrInterface->mGenericTypeInfo->mTypeGenericArguments[0];
  5702. if (isRefExpression)
  5703. {
  5704. if (varType->IsPointer())
  5705. varType = CreateRefType(varType->GetUnderlyingType());
  5706. }
  5707. }
  5708. }
  5709. };
  5710. auto enumeratorTypeInst = itr.mType->ToTypeInstance();
  5711. while (enumeratorTypeInst != NULL)
  5712. {
  5713. PopulateType(enumeratorTypeInst, Beefy::BfPopulateType_Interfaces_All);
  5714. for (auto& interfaceRef : enumeratorTypeInst->mInterfaces)
  5715. {
  5716. BfTypeInstance* interface = interfaceRef.mInterfaceType;
  5717. _CheckInterface(interface);
  5718. }
  5719. if (enumeratorTypeInst->IsInstanceOf(isRefExpression ? mCompiler->mGenericIRefEnumeratorTypeDef : mCompiler->mGenericIEnumeratorTypeDef))
  5720. {
  5721. itrInterface = enumeratorTypeInst;
  5722. genericItrInterface = itrInterface->ToGenericTypeInstance();
  5723. if (inferVarType)
  5724. {
  5725. varType = genericItrInterface->mGenericTypeInfo->mTypeGenericArguments[0];
  5726. if (isRefExpression)
  5727. {
  5728. if (varType->IsPointer())
  5729. varType = CreateRefType(varType);
  5730. }
  5731. }
  5732. break;
  5733. }
  5734. if (itrInterface != NULL)
  5735. break;
  5736. enumeratorTypeInst = enumeratorTypeInst->mBaseType;
  5737. }
  5738. if ((genericItrInterface == NULL) && (genericParamInst != NULL))
  5739. {
  5740. for (auto interface : genericParamInst->mInterfaceConstraints)
  5741. _CheckInterface(interface);
  5742. }
  5743. if (genericItrInterface == NULL)
  5744. {
  5745. if (!hadGetEnumeratorType)
  5746. {
  5747. Fail(StrFormat("Type '%s' must contain a 'GetEnumerator' method or implement an IEnumerator<T> interface", TypeToString(target.mType).c_str()), forEachStmt->mCollectionExpression);
  5748. }
  5749. else
  5750. Fail(StrFormat("Enumerator type '%s' must implement an %s<T> interface", TypeToString(itr.mType).c_str(), isRefExpression ? "IRefEnumerator" : "IEnumerator"), forEachStmt->mCollectionExpression);
  5751. itrInterface = NULL;
  5752. itr = BfTypedValue();
  5753. }
  5754. else
  5755. {
  5756. itrInterface = genericItrInterface;
  5757. if (isRefExpression)
  5758. {
  5759. refItrInterface = itrInterface;
  5760. PopulateType(refItrInterface);
  5761. // Must IRefEnumeratorf<T> must include only IEnumerator<T>
  5762. // BF_ASSERT(refItrInterface->mInterfaces.size() == 1);
  5763. // if (refItrInterface->mInterfaces.size() == 1)
  5764. // itrInterface = refItrInterface->mInterfaces[0].mInterfaceType;
  5765. }
  5766. itr = MakeAddressable(itr);
  5767. itr = RemoveReadOnly(itr);
  5768. }
  5769. }
  5770. }
  5771. else
  5772. {
  5773. AssertErrorState();
  5774. }
  5775. PopulateType(varType, BfPopulateType_Data);
  5776. // Apply deferred local assign to mEmbeddedStatement and itrStmt
  5777. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  5778. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  5779. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  5780. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  5781. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites);
  5782. if ((target.mType->IsSizedArray()) && (((BfSizedArrayType*)target.mType)->mElementCount == 0))
  5783. {
  5784. EmitEnsureInstructionAt();
  5785. mBfIRBuilder->mIgnoreWrites = true;
  5786. }
  5787. BfIdentifierNode* nameNode = NULL;
  5788. String variableName;
  5789. struct _TupleBind
  5790. {
  5791. BfIdentifierNode* mNameNode;
  5792. String mName;
  5793. BfType* mType;
  5794. BfLocalVariable* mVariable;
  5795. };
  5796. Array<_TupleBind> tupleBinds;
  5797. if (forEachStmt->mVariableName != NULL)
  5798. {
  5799. if (auto tupleExpr = BfNodeDynCast<BfTupleExpression>(forEachStmt->mVariableName))
  5800. {
  5801. CheckTupleVariableDeclaration(tupleExpr, varType);
  5802. if (varType->IsTuple())
  5803. {
  5804. auto tupleType = (BfTypeInstance*)varType;
  5805. for (int idx = 0; idx < BF_MIN((int)tupleExpr->mValues.size(), (int)tupleType->mFieldInstances.size()); idx++)
  5806. {
  5807. auto nameNode = tupleExpr->mValues[idx];
  5808. _TupleBind tupleBind;
  5809. tupleBind.mNameNode = BfNodeDynCast<BfIdentifierNode>(nameNode);
  5810. if ((tupleBind.mNameNode == NULL) && (nameNode != NULL))
  5811. {
  5812. Fail("Variable name expected", nameNode);
  5813. }
  5814. tupleBind.mName = nameNode->ToString();
  5815. tupleBind.mType = tupleType->mFieldInstances[idx].mResolvedType;
  5816. tupleBind.mVariable = NULL;
  5817. tupleBinds.Add(tupleBind);
  5818. if (idx == 0)
  5819. variableName = tupleBind.mName;
  5820. }
  5821. }
  5822. }
  5823. else
  5824. {
  5825. nameNode = BfNodeDynCast<BfIdentifierNode>(forEachStmt->mVariableName);
  5826. if (nameNode != NULL)
  5827. variableName = nameNode->ToString();
  5828. }
  5829. }
  5830. if (variableName.IsEmpty())
  5831. variableName = "_";
  5832. BfModuleMethodInstance getNextMethodInst;
  5833. BfType* nextEmbeddedType = NULL;
  5834. BfTypedValue nextResult;
  5835. if ((refItrInterface) || (itrInterface))
  5836. {
  5837. if (isRefExpression)
  5838. {
  5839. PopulateType(refItrInterface, BfPopulateType_Full_Force);
  5840. getNextMethodInst = GetMethodByName(refItrInterface, "GetNextRef");
  5841. }
  5842. else
  5843. {
  5844. PopulateType(itrInterface, BfPopulateType_Full_Force);
  5845. getNextMethodInst = GetMethodByName(itrInterface, "GetNext");
  5846. }
  5847. if (getNextMethodInst)
  5848. {
  5849. nextResult = BfTypedValue(CreateAlloca(getNextMethodInst.mMethodInstance->mReturnType), getNextMethodInst.mMethodInstance->mReturnType, true);
  5850. if (nextResult.mType->IsGenericTypeInstance())
  5851. {
  5852. nextEmbeddedType = ((BfTypeInstance*)nextResult.mType)->mGenericTypeInfo->mTypeGenericArguments[0];
  5853. }
  5854. }
  5855. else
  5856. {
  5857. InternalError("Failed to find GetNext");
  5858. }
  5859. }
  5860. if (nextEmbeddedType == NULL)
  5861. nextEmbeddedType = GetPrimitiveType(BfTypeCode_Var);
  5862. BfLocalVariable* itrLocalDef = NULL;
  5863. // Iterator local def
  5864. if (itr)
  5865. {
  5866. BfLocalVariable* localDef = new BfLocalVariable();
  5867. itrLocalDef = localDef;
  5868. localDef->mNameNode = nameNode;
  5869. localDef->mName = variableName;
  5870. localDef->mResolvedType = itr.mType;
  5871. localDef->mAddr = itr.mValue;
  5872. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5873. localDef->mReadFromId = 0;
  5874. localDef->Init();
  5875. UpdateSrcPos(forEachStmt);
  5876. CheckVariableDef(localDef);
  5877. AddLocalVariableDef(localDef, true);
  5878. }
  5879. BfIRValue varInst;
  5880. BfTypedValue varTypedVal;
  5881. bool needsValCopy = true;
  5882. BfType* origVarType = varType;
  5883. // Local variable
  5884. {
  5885. if (!tupleBinds.IsEmpty())
  5886. {
  5887. BF_ASSERT(varType->IsTuple());
  5888. auto tupleType = (BfTypeInstance*)varType;
  5889. // Tuple binds
  5890. needsValCopy = false;
  5891. if (!nextResult)
  5892. {
  5893. varInst = CreateAlloca(varType);
  5894. varTypedVal = BfTypedValue(varInst, varType, true);
  5895. }
  5896. // Local
  5897. for (int idx = 0; idx < (int)tupleBinds.size(); idx++)
  5898. {
  5899. auto& tupleBind = tupleBinds[idx];
  5900. BfLocalVariable* localDef = new BfLocalVariable();
  5901. localDef->mNameNode = tupleBind.mNameNode;
  5902. localDef->mName = tupleBind.mName;
  5903. localDef->mResolvedType = tupleBind.mType;
  5904. if (!needsValCopy)
  5905. localDef->mResolvedType = CreateRefType(localDef->mResolvedType);
  5906. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  5907. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5908. localDef->mReadFromId = 0;
  5909. if ((isLet) || (forEachStmt->mReadOnlyToken != NULL))
  5910. localDef->mIsReadOnly = true;
  5911. localDef->Init();
  5912. auto fieldInstance = &tupleType->mFieldInstances[idx];
  5913. if (fieldInstance->mDataIdx >= 0)
  5914. {
  5915. auto tuplePtrType = CreatePointerType(varType);
  5916. BfIRValue tuplePtr;
  5917. if (nextResult)
  5918. tuplePtr = mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(tuplePtrType));
  5919. else
  5920. tuplePtr = mBfIRBuilder->CreateBitCast(varInst, mBfIRBuilder->MapType(tuplePtrType));
  5921. auto valAddr = mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, fieldInstance->mDataIdx);
  5922. mBfIRBuilder->CreateAlignedStore(valAddr, localDef->mAddr, localDef->mResolvedType->mAlign);
  5923. }
  5924. UpdateSrcPos(forEachStmt);
  5925. if ((itrLocalDef != NULL) && (idx == 0))
  5926. {
  5927. localDef->mLocalVarId = itrLocalDef->mLocalVarId;
  5928. localDef->mIsShadow = true;
  5929. }
  5930. else
  5931. {
  5932. CheckVariableDef(localDef);
  5933. }
  5934. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded_AliveOnDecl);
  5935. }
  5936. }
  5937. else
  5938. {
  5939. // Normal case
  5940. if ((nextResult) && (varType->IsComposite()) && (!varType->IsValuelessType()) && (!isRefExpression))
  5941. {
  5942. needsValCopy = false;
  5943. varType = CreateRefType(varType);
  5944. }
  5945. // Local
  5946. BfLocalVariable* localDef = new BfLocalVariable();
  5947. localDef->mNameNode = nameNode;
  5948. localDef->mName = variableName;
  5949. localDef->mResolvedType = varType;
  5950. if (!varType->IsValuelessType())
  5951. varInst = CreateAlloca(varType);
  5952. else
  5953. varInst = mBfIRBuilder->GetFakeVal();
  5954. localDef->mAddr = varInst;
  5955. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  5956. localDef->mReadFromId = 0;
  5957. if ((isLet) || (forEachStmt->mReadOnlyToken != NULL))
  5958. localDef->mIsReadOnly = true;
  5959. localDef->Init();
  5960. if (!needsValCopy)
  5961. {
  5962. auto valAddr = mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(varType));
  5963. mBfIRBuilder->CreateAlignedStore(valAddr, varInst, varType->mAlign);
  5964. }
  5965. UpdateSrcPos(forEachStmt);
  5966. if (itrLocalDef != NULL)
  5967. {
  5968. localDef->mLocalVarId = itrLocalDef->mLocalVarId;
  5969. localDef->mIsShadow = true;
  5970. }
  5971. else
  5972. {
  5973. CheckVariableDef(localDef);
  5974. }
  5975. AddLocalVariableDef(localDef, true, false, BfIRValue(), BfIRInitType_NotNeeded_AliveOnDecl);
  5976. varTypedVal = BfTypedValue(varInst, varType, true);
  5977. }
  5978. }
  5979. // Iterator
  5980. if (itr)
  5981. {
  5982. if ((!isArray) && (!isSizedArray))
  5983. {
  5984. BfFunctionBindResult functionBindResult;
  5985. BfExprEvaluator exprEvaluator(this);
  5986. exprEvaluator.mFunctionBindResult = &functionBindResult;
  5987. // Allow for "Dispose" not to exist
  5988. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5989. BfResolvedArgs resolvedArgs;
  5990. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  5991. exprEvaluator.MatchMethod(forEachStmt->mCollectionExpression, NULL, itr, false, false, "Dispose", resolvedArgs, BfMethodGenericArguments());
  5992. if (functionBindResult.mMethodInstance != NULL)
  5993. {
  5994. BfModuleMethodInstance moduleMethodInstance;
  5995. moduleMethodInstance = BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc);
  5996. AddDeferredCall(moduleMethodInstance, functionBindResult.mIRArgs, mCurMethodState->mCurScope);
  5997. }
  5998. }
  5999. }
  6000. BfScopeData innerScopeData;
  6001. if (forEachStmt->mLabelNode != NULL)
  6002. innerScopeData.mLabelNode = forEachStmt->mLabelNode->mLabel;
  6003. innerScopeData.mValueScopeStart = ValueScopeStart();
  6004. mCurMethodState->AddScope(&innerScopeData);
  6005. NewScopeState(true, false);
  6006. innerScopeData.mIsLoop = true;
  6007. if ((autoComplete != NULL) && (forEachStmt->mVariableTypeRef != NULL))
  6008. autoComplete->CheckVarResolution(forEachStmt->mVariableTypeRef, origVarType);
  6009. if (isArray || isSizedArray)
  6010. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), itr.mValue, itr.mType->mAlign);
  6011. auto valueScopeStartInner = ValueScopeStart();
  6012. // We may have a call in the loop body
  6013. mCurMethodState->mMayNeedThisAccessCheck = true;
  6014. auto condBB = mBfIRBuilder->CreateBlock("foreach.cond", true);
  6015. auto bodyBB = mBfIRBuilder->CreateBlock("foreach.body");
  6016. auto incBB = mBfIRBuilder->CreateBlock("foreach.inc");
  6017. auto endBB = mBfIRBuilder->CreateBlock("foreach.end");
  6018. BfBreakData breakData;
  6019. breakData.mIRContinueBlock = incBB;
  6020. breakData.mIRBreakBlock = endBB;
  6021. breakData.mScope = &innerScopeData;
  6022. breakData.mInnerValueScopeStart = valueScopeStartInner;
  6023. breakData.mPrevBreakData = mCurMethodState->mBreakData;
  6024. SetAndRestoreValue<BfBreakData*> prevBreakData(mCurMethodState->mBreakData, &breakData);
  6025. mBfIRBuilder->CreateBr(condBB);
  6026. mBfIRBuilder->SetInsertPoint(condBB);
  6027. if (forEachStmt->mCollectionExpression != NULL)
  6028. UpdateExprSrcPos(forEachStmt->mCollectionExpression);
  6029. BfIRValue conditionValue;
  6030. if (isSizedArray) // if (i < lengthof(array)
  6031. {
  6032. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  6033. auto arrayType = (BfSizedArrayType*)target.mType;
  6034. PopulateType(arrayType, BfPopulateType_DataAndMethods);
  6035. BfIRValue lengthVal = GetConstValue(arrayType->mElementCount);
  6036. conditionValue = mBfIRBuilder->CreateCmpLT(itrVal, lengthVal, true);
  6037. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  6038. ValueScopeEnd(valueScopeStartInner);
  6039. }
  6040. else if (isArray) // if (i < array.mLength)
  6041. {
  6042. auto itrVal = mBfIRBuilder->CreateAlignedLoad(itr.mValue, itr.mType->mAlign);
  6043. auto arrayType = (BfArrayType*)target.mType;
  6044. PopulateType(arrayType);
  6045. auto arrayBaseValue = mBfIRBuilder->CreateBitCast(target.mValue, mBfIRBuilder->MapType(arrayType->mBaseType, BfIRPopulateType_Full));
  6046. int getLengthBitCount = arrayType->GetLengthBitCount();
  6047. BfIRValue lengthVal;
  6048. if (arrayType->mBaseType->mTypeFailed)
  6049. {
  6050. AssertErrorState();
  6051. if (getLengthBitCount == 64)
  6052. lengthVal = GetConstValue64(0);
  6053. else
  6054. lengthVal = GetConstValue32(0);
  6055. }
  6056. else
  6057. {
  6058. auto fieldInst = GetFieldInstance(arrayType->mBaseType, 0, "mLength");
  6059. if (fieldInst != NULL)
  6060. {
  6061. auto lengthValAddr = mBfIRBuilder->CreateInBoundsGEP(arrayBaseValue, 0, fieldInst->mDataIdx);
  6062. lengthVal = mBfIRBuilder->CreateAlignedLoad(lengthValAddr, fieldInst->mResolvedType->mAlign);
  6063. }
  6064. }
  6065. lengthVal = mBfIRBuilder->CreateNumericCast(lengthVal, true, BfTypeCode_IntPtr);
  6066. conditionValue = mBfIRBuilder->CreateCmpLT(itrVal, lengthVal, true);
  6067. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  6068. ValueScopeEnd(valueScopeStartInner);
  6069. }
  6070. else // if (itr.MoveNext())
  6071. {
  6072. if (!itr)
  6073. {
  6074. if (!isVarEnumerator)
  6075. AssertErrorState();
  6076. mBfIRBuilder->CreateBr(endBB);
  6077. }
  6078. else
  6079. {
  6080. BfExprEvaluator exprEvaluator(this);
  6081. auto itrTypeInstance = itr.mType->ToTypeInstance();
  6082. SizedArray<BfResolvedArg, 0> resolvedArgs;
  6083. BfMethodMatcher methodMatcher(forEachStmt->mCollectionExpression, this, getNextMethodInst.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  6084. if (isRefExpression)
  6085. methodMatcher.CheckType(refItrInterface, itr, false);
  6086. else
  6087. methodMatcher.CheckType(itrInterface, itr, false);
  6088. methodMatcher.TryDevirtualizeCall(itr);
  6089. exprEvaluator.mReceivingValue = &nextResult;
  6090. auto retVal = exprEvaluator.CreateCall(&methodMatcher, itr);
  6091. if (exprEvaluator.mReceivingValue != NULL)
  6092. {
  6093. if (mIsComptimeModule)
  6094. {
  6095. retVal = LoadValue(retVal);
  6096. mBfIRBuilder->CreateStore(retVal.mValue, nextResult.mValue);
  6097. }
  6098. else
  6099. AssertErrorState();
  6100. }
  6101. if ((retVal) && (!retVal.mType->IsVar()))
  6102. {
  6103. auto i8Result = ExtractValue(nextResult, NULL, 2);
  6104. i8Result = LoadValue(i8Result);
  6105. BF_ASSERT(i8Result.mType == GetPrimitiveType(BfTypeCode_Int8));
  6106. conditionValue = mBfIRBuilder->CreateCmpEQ(i8Result.mValue, GetConstValue8(0));
  6107. }
  6108. else
  6109. conditionValue = GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean));
  6110. mBfIRBuilder->CreateCondBr(conditionValue, bodyBB, endBB);
  6111. ValueScopeEnd(valueScopeStartInner);
  6112. }
  6113. }
  6114. mBfIRBuilder->AddBlock(bodyBB);
  6115. mBfIRBuilder->SetInsertPoint(bodyBB);
  6116. if (!varTypedVal)
  6117. {
  6118. // Nothing to do...
  6119. }
  6120. else if (isSizedArray) // val = array[i]
  6121. {
  6122. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  6123. auto arrayType = (BfSizedArrayType*)target.mType;
  6124. BfType* ptrType = CreatePointerType(arrayType->mElementType);
  6125. BfTypedValue arrayItem;
  6126. if (arrayType->mElementType->IsValuelessType())
  6127. {
  6128. arrayItem = GetDefaultTypedValue(arrayType->mElementType);
  6129. }
  6130. else
  6131. {
  6132. target = MakeAddressable(target);
  6133. arrayItem = BfTypedValue(CreateIndexedValue(arrayType->mElementType, target.mValue, itrVal, true), arrayType->mElementType, true);
  6134. if (isRefExpression)
  6135. arrayItem = BfTypedValue(arrayItem.mValue, CreateRefType(arrayItem.mType));
  6136. }
  6137. arrayItem = Cast(forEachStmt->mCollectionExpression, arrayItem, varType, BfCastFlags_Explicit);
  6138. if ((arrayItem) && (!arrayItem.mValue.IsFake()))
  6139. {
  6140. arrayItem = LoadValue(arrayItem);
  6141. if (arrayItem)
  6142. mBfIRBuilder->CreateStore(arrayItem.mValue, varInst);
  6143. }
  6144. }
  6145. else if (isArray) // val = array[i]
  6146. {
  6147. auto itrVal = mBfIRBuilder->CreateLoad(itr.mValue);
  6148. BfTypedValueExpression typedValueExpr;
  6149. typedValueExpr.Init(BfTypedValue(itrVal, itrType));
  6150. BfExprEvaluator exprEvaluator(this);
  6151. SizedArray<BfExpression*, 1> indices;
  6152. indices.push_back(&typedValueExpr);
  6153. BfSizedArray<BfExpression*> sizedArgExprs(indices);
  6154. BfResolvedArgs argValues(&sizedArgExprs);
  6155. exprEvaluator.ResolveArgValues(argValues);
  6156. bool boundsCheck = mCompiler->mOptions.mRuntimeChecks;
  6157. auto typeOptions = GetTypeOptions();
  6158. if (typeOptions != NULL)
  6159. boundsCheck = typeOptions->Apply(boundsCheck, BfOptionFlags_RuntimeChecks);
  6160. BfMethodMatcher methodMatcher(forEachStmt->mVariableName, this, "get__", argValues.mResolvedArgs, BfMethodGenericArguments());
  6161. methodMatcher.mMethodType = BfMethodType_PropertyGetter;
  6162. methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  6163. if (methodMatcher.mBestMethodDef == NULL)
  6164. {
  6165. Fail("Failed to find indexer method in array", forEachStmt);
  6166. }
  6167. else
  6168. {
  6169. methodMatcher.mCheckedKind = boundsCheck ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  6170. BfTypedValue arrayItem = exprEvaluator.CreateCall(&methodMatcher, target);
  6171. if ((varInst) && (arrayItem))
  6172. {
  6173. if (isRefExpression)
  6174. arrayItem = BfTypedValue(arrayItem.mValue, CreateRefType(arrayItem.mType));
  6175. else if (!arrayItem.mType->IsComposite())
  6176. arrayItem = LoadValue(arrayItem);
  6177. arrayItem = Cast(forEachStmt->mCollectionExpression, arrayItem, varType, BfCastFlags_Explicit);
  6178. arrayItem = LoadValue(arrayItem);
  6179. if (arrayItem)
  6180. mBfIRBuilder->CreateStore(arrayItem.mValue, varInst);
  6181. }
  6182. }
  6183. }
  6184. else
  6185. {
  6186. if (!itr)
  6187. {
  6188. if (!isVarEnumerator)
  6189. AssertErrorState();
  6190. }
  6191. else if (mCompiler->IsAutocomplete())
  6192. {
  6193. // If we don't do this shortcut, we can end up creating temporary "boxed" objects
  6194. }
  6195. else
  6196. {
  6197. if (needsValCopy)
  6198. {
  6199. auto nextVal = BfTypedValue(mBfIRBuilder->CreateBitCast(nextResult.mValue, mBfIRBuilder->MapType(CreatePointerType(nextEmbeddedType))), nextEmbeddedType, true);
  6200. if (isRefExpression)
  6201. {
  6202. if (nextVal.mType->IsPointer())
  6203. nextVal = BfTypedValue(nextVal.mValue, CreateRefType(nextVal.mType->GetUnderlyingType()), true);
  6204. }
  6205. nextVal = Cast(forEachStmt->mCollectionExpression, nextVal, varType, BfCastFlags_Explicit);
  6206. nextVal = LoadValue(nextVal);
  6207. if ((nextVal) && (!nextVal.mType->IsValuelessType()))
  6208. mBfIRBuilder->CreateAlignedStore(nextVal.mValue, varInst, nextVal.mType->mAlign);
  6209. }
  6210. }
  6211. }
  6212. if (forEachStmt->mEmbeddedStatement != NULL)
  6213. {
  6214. VisitEmbeddedStatement(forEachStmt->mEmbeddedStatement);
  6215. }
  6216. if (!mCurMethodState->mLeftBlockUncond)
  6217. {
  6218. ValueScopeEnd(valueScopeStartInner);
  6219. mBfIRBuilder->CreateBr(incBB);
  6220. }
  6221. mBfIRBuilder->AddBlock(incBB);
  6222. mBfIRBuilder->SetInsertPoint(incBB);
  6223. if (isArray || isSizedArray)
  6224. {
  6225. auto val = mBfIRBuilder->CreateLoad(itr.mValue);
  6226. auto result = mBfIRBuilder->CreateAdd(val, GetConstValue(1));
  6227. mBfIRBuilder->CreateStore(result, itr.mValue);
  6228. }
  6229. else
  6230. {
  6231. // Nothing to do
  6232. }
  6233. mBfIRBuilder->CreateBr(condBB);
  6234. mBfIRBuilder->AddBlock(endBB);
  6235. mBfIRBuilder->SetInsertPoint(endBB);
  6236. if ((itrLocalDef != NULL) && (itrLocalDef->mDbgVarInst) && (IsTargetingBeefBackend()))
  6237. {
  6238. // If this shadows another enumerator variable then we need to explicitly mark the end of this one
  6239. mBfIRBuilder->DbgLifetimeEnd(itrLocalDef->mDbgVarInst);
  6240. }
  6241. // The 'return' may have been inside the block, which may not have been entered if preconditions were not met
  6242. mCurMethodState->SetHadReturn(false);
  6243. mCurMethodState->mLeftBlockUncond = false;
  6244. mCurMethodState->mLeftBlockCond = false;
  6245. RestoreScopeState();
  6246. RestoreScopeState();
  6247. }
  6248. void BfModule::Visit(BfDeferStatement* deferStmt)
  6249. {
  6250. if (deferStmt->mTargetNode == NULL)
  6251. {
  6252. AssertErrorState();
  6253. return;
  6254. }
  6255. //TODO: Why in the world didn't we want to be able to step onto a defer statement?
  6256. // We only want the breakpoint to hit on execution of the defer, not on insertion of it
  6257. //SetAndRestoreValue<bool> prevSetIllegalSrcPos(mSetIllegalSrcPosition, true);
  6258. UpdateSrcPos(deferStmt);
  6259. EmitEnsureInstructionAt();
  6260. BfScopeData* scope = NULL;
  6261. if (deferStmt->mScopeToken != NULL)
  6262. {
  6263. if (deferStmt->mScopeToken->GetToken() == BfToken_Scope)
  6264. scope = mCurMethodState->mCurScope->GetTargetable();
  6265. else
  6266. scope = &mCurMethodState->mHeadScope;
  6267. }
  6268. else if (deferStmt->mScopeName != NULL)
  6269. scope = FindScope(deferStmt->mScopeName, true);
  6270. else
  6271. scope = mCurMethodState->mCurScope;
  6272. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  6273. {
  6274. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(deferStmt->mScopeName);
  6275. if ((deferStmt->mScopeName == NULL) || (targetIdentifier != NULL))
  6276. mCompiler->mResolvePassData->mAutoComplete->CheckLabel(targetIdentifier, deferStmt->mColonToken, scope);
  6277. }
  6278. if ((scope == mCurMethodState->mCurScope) && (scope->mCloseNode == NULL))
  6279. {
  6280. auto parser = deferStmt->GetParser();
  6281. if ((parser == NULL) || (!parser->mIsEmitted))
  6282. Warn(0, "This defer will immediately execute. Consider specifying a wider scope target such as 'defer::'", deferStmt->mDeferToken);
  6283. }
  6284. if (auto block = BfNodeDynCast<BfBlock>(deferStmt->mTargetNode))
  6285. {
  6286. if (deferStmt->mBind != NULL)
  6287. {
  6288. Array<BfDeferredCapture> captures;
  6289. for (auto identifier : deferStmt->mBind->mParams)
  6290. {
  6291. BfDeferredCapture deferredCapture;
  6292. deferredCapture.mName = identifier->ToString();
  6293. deferredCapture.mValue = CreateValueFromExpression(identifier);
  6294. if (deferredCapture.mValue)
  6295. {
  6296. captures.push_back(deferredCapture);
  6297. }
  6298. }
  6299. AddDeferredBlock(block, scope, &captures);
  6300. }
  6301. else
  6302. AddDeferredBlock(block, scope);
  6303. }
  6304. else if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(deferStmt->mTargetNode))
  6305. {
  6306. BfExprEvaluator expressionEvaluator(this);
  6307. expressionEvaluator.mDeferCallRef = exprStmt->mExpression;
  6308. expressionEvaluator.mDeferScopeAlloc = scope;
  6309. expressionEvaluator.VisitChild(exprStmt->mExpression);
  6310. if (mCurMethodState->mPendingNullConditional != NULL)
  6311. FlushNullConditional(expressionEvaluator.mResult, true);
  6312. }
  6313. else if (auto deleteStmt = BfNodeDynCast<BfDeleteStatement>(deferStmt->mTargetNode))
  6314. {
  6315. if (deleteStmt->mExpression == NULL)
  6316. {
  6317. AssertErrorState();
  6318. return;
  6319. }
  6320. auto val = CreateValueFromExpression(deleteStmt->mExpression);
  6321. if (!val)
  6322. return;
  6323. if (mCompiler->IsAutocomplete())
  6324. return;
  6325. bool isGenericParam = false;
  6326. auto checkType = val.mType;
  6327. if (val.mType->IsGenericParam())
  6328. {
  6329. isGenericParam = true;
  6330. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)val.mType);
  6331. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete)
  6332. return;
  6333. if (genericParamInst->mTypeConstraint != NULL)
  6334. checkType = genericParamInst->mTypeConstraint;
  6335. }
  6336. bool isAppendDelete = false;
  6337. BfTypedValue customAllocator;
  6338. if (deleteStmt->mAllocExpr != NULL)
  6339. {
  6340. if (auto expr = BfNodeDynCast<BfExpression>(deleteStmt->mAllocExpr))
  6341. customAllocator = CreateValueFromExpression(expr);
  6342. else if (auto tokenNode = BfNodeDynCast<BfTokenNode>(deleteStmt->mAllocExpr))
  6343. {
  6344. if (tokenNode->mToken == BfToken_Append)
  6345. isAppendDelete = true;
  6346. }
  6347. }
  6348. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  6349. PopulateType(checkType);
  6350. if (checkType->IsVar())
  6351. return;
  6352. if ((!checkType->IsObjectOrInterface()) && (!checkType->IsPointer()))
  6353. {
  6354. VisitChild(deferStmt->mTargetNode);
  6355. Fail(StrFormat("Cannot delete a value of type '%s'", TypeToString(val.mType).c_str()), deferStmt->mTargetNode);
  6356. return;
  6357. }
  6358. if (isGenericParam)
  6359. return;
  6360. bool isDtorOnly = false;
  6361. if (customAllocator.mType == GetPrimitiveType(BfTypeCode_NullPtr))
  6362. {
  6363. if (!checkType->IsObjectOrInterface())
  6364. Warn(0, "Type '%' has no destructor, so delete:null has no effect", deleteStmt->mExpression);
  6365. }
  6366. else if (customAllocator)
  6367. {
  6368. BfFunctionBindResult functionBindResult;
  6369. functionBindResult.mWantsArgs = true;
  6370. auto customAllocTypeInst = customAllocator.mType->ToTypeInstance();
  6371. if ((checkType->IsObjectOrInterface()) && (customAllocTypeInst != NULL) && (customAllocTypeInst->mTypeDef->GetMethodByName("FreeObject") != NULL))
  6372. {
  6373. BfTypedValueExpression typedValueExpr;
  6374. typedValueExpr.Init(val);
  6375. typedValueExpr.mRefNode = deleteStmt->mAllocExpr;
  6376. BfExprEvaluator exprEvaluator(this);
  6377. SizedArray<BfExpression*, 2> argExprs;
  6378. argExprs.push_back(&typedValueExpr);
  6379. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6380. BfResolvedArgs argValues(&sizedArgExprs);
  6381. exprEvaluator.ResolveArgValues(argValues);
  6382. exprEvaluator.mNoBind = true;
  6383. exprEvaluator.mFunctionBindResult = &functionBindResult;
  6384. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "FreeObject", argValues, BfMethodGenericArguments());
  6385. }
  6386. else
  6387. {
  6388. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6389. auto ptrValue = BfTypedValue(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(voidPtrType)), voidPtrType);
  6390. BfTypedValueExpression typedValueExpr;
  6391. typedValueExpr.Init(ptrValue);
  6392. BfExprEvaluator exprEvaluator(this);
  6393. SizedArray<BfExpression*, 2> argExprs;
  6394. argExprs.push_back(&typedValueExpr);
  6395. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6396. BfResolvedArgs argValues(&sizedArgExprs);
  6397. exprEvaluator.ResolveArgValues(argValues);
  6398. exprEvaluator.mNoBind = true;
  6399. exprEvaluator.mFunctionBindResult = &functionBindResult;
  6400. exprEvaluator.MatchMethod(deleteStmt->mAllocExpr, NULL, customAllocator, false, false, "Free", argValues, BfMethodGenericArguments());
  6401. }
  6402. if (functionBindResult.mMethodInstance != NULL)
  6403. {
  6404. AddDeferredCall(BfModuleMethodInstance(functionBindResult.mMethodInstance, functionBindResult.mFunc), functionBindResult.mIRArgs, scope, deleteStmt, true);
  6405. }
  6406. }
  6407. if (checkType->IsObjectOrInterface())
  6408. {
  6409. auto objectType = mContext->mBfObjectType;
  6410. PopulateType(objectType);
  6411. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  6412. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  6413. SizedArray<BfIRValue, 1> llvmArgs;
  6414. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  6415. if (!customAllocator)
  6416. {
  6417. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!mIsComptimeModule))
  6418. {
  6419. auto moduleMethodInstance = GetInternalMethod("Dbg_MarkObjectDeleted");
  6420. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6421. }
  6422. else
  6423. {
  6424. auto moduleMethodInstance = GetInternalMethod("Free");
  6425. SizedArray<BfIRValue, 1> llvmArgs;
  6426. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)));
  6427. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6428. }
  6429. }
  6430. auto moduleMethodInstance = GetMethodInstance(objectType, methodInstance->mMethodDef, BfTypeVector());
  6431. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6432. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  6433. {
  6434. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), (deleteStmt->mTargetTypeToken != NULL) ? "Dbg_ObjectPreCustomDelete" : "Dbg_ObjectPreDelete");
  6435. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6436. }
  6437. }
  6438. else
  6439. {
  6440. if ((!customAllocator) && (!isAppendDelete))
  6441. {
  6442. val = LoadValue(val);
  6443. BfModuleMethodInstance moduleMethodInstance;
  6444. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6445. moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), "Dbg_RawFree");
  6446. else
  6447. moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), "Free");
  6448. SizedArray<BfIRValue, 1> llvmArgs;
  6449. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr)));
  6450. AddDeferredCall(moduleMethodInstance, llvmArgs, scope, deleteStmt, false, true);
  6451. }
  6452. }
  6453. }
  6454. else
  6455. {
  6456. AssertErrorState();
  6457. VisitChild(deferStmt->mTargetNode);
  6458. }
  6459. }
  6460. void BfModule::Visit(BfBlock* block)
  6461. {
  6462. VisitEmbeddedStatement(block);
  6463. }
  6464. void BfModule::Visit(BfUnscopedBlock* block)
  6465. {
  6466. VisitEmbeddedStatement(block, NULL, BfEmbeddedStatementFlags_Unscoped);
  6467. }
  6468. void BfModule::Visit(BfLabeledBlock* labeledBlock)
  6469. {
  6470. VisitEmbeddedStatement(labeledBlock);
  6471. }
  6472. void BfModule::Visit(BfRootNode* rootNode)
  6473. {
  6474. VisitMembers(rootNode);
  6475. }
  6476. void BfModule::Visit(BfInlineAsmStatement* asmStmt)
  6477. {
  6478. #if 0
  6479. enum RegClobberFlags //CDH TODO add support for mmx/xmm/fpst etc (how are these signified in LLVM? check LangRef inline asm docs clobber list info)
  6480. {
  6481. // please keep eax through edx in alphabetical order (grep $BYTEREGS for why)
  6482. REGCLOBBERF_EAX = (1 << 0),
  6483. REGCLOBBERF_EBX = (1 << 1),
  6484. REGCLOBBERF_ECX = (1 << 2),
  6485. REGCLOBBERF_EDX = (1 << 3),
  6486. REGCLOBBERF_ESI = (1 << 4),
  6487. REGCLOBBERF_EDI = (1 << 5),
  6488. REGCLOBBERF_ESP = (1 << 6),
  6489. REGCLOBBERF_EBP = (1 << 7),
  6490. REGCLOBBERF_XMM0 = (1 << 8),
  6491. REGCLOBBERF_XMM1 = (1 << 9),
  6492. REGCLOBBERF_XMM2 = (1 << 10),
  6493. REGCLOBBERF_XMM3 = (1 << 11),
  6494. REGCLOBBERF_XMM4 = (1 << 12),
  6495. REGCLOBBERF_XMM5 = (1 << 13),
  6496. REGCLOBBERF_XMM6 = (1 << 14),
  6497. REGCLOBBERF_XMM7 = (1 << 15),
  6498. REGCLOBBERF_FPST0 = (1 << 16),
  6499. REGCLOBBERF_FPST1 = (1 << 17),
  6500. REGCLOBBERF_FPST2 = (1 << 18),
  6501. REGCLOBBERF_FPST3 = (1 << 19),
  6502. REGCLOBBERF_FPST4 = (1 << 20),
  6503. REGCLOBBERF_FPST5 = (1 << 21),
  6504. REGCLOBBERF_FPST6 = (1 << 22),
  6505. REGCLOBBERF_FPST7 = (1 << 23),
  6506. REGCLOBBERF_MM0 = (1 << 24),
  6507. REGCLOBBERF_MM1 = (1 << 25),
  6508. REGCLOBBERF_MM2 = (1 << 26),
  6509. REGCLOBBERF_MM3 = (1 << 27),
  6510. REGCLOBBERF_MM4 = (1 << 28),
  6511. REGCLOBBERF_MM5 = (1 << 29),
  6512. REGCLOBBERF_MM6 = (1 << 30),
  6513. REGCLOBBERF_MM7 = (1 << 31),
  6514. };
  6515. const char* regClobberNames[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "esp", "ebp", nullptr }; // must be in same order as flags
  6516. unsigned long regClobberFlags = 0;
  6517. std::function<bool(const StringImpl&, bool)> matchRegFunc = [this, &regClobberNames, &regClobberFlags](const StringImpl& name, bool isClobber)
  6518. {
  6519. bool found = false;
  6520. int nameLen = name.length();
  6521. if (nameLen == 3)
  6522. {
  6523. if ((name[0] == 's') && (name[1] == 't') && (name[2] >= '0') && (name[2] <= '7'))
  6524. {
  6525. // st# regs (unparenthesized at this point)
  6526. if (isClobber)
  6527. regClobberFlags |= (REGCLOBBERF_FPST0 << (name[2] - '0'));
  6528. found = true;
  6529. }
  6530. else if ((name[0] == 'm') && (name[1] == 'm') && (name[2] >= '0') && (name[2] <= '7'))
  6531. {
  6532. // mm regs
  6533. if (isClobber)
  6534. regClobberFlags |= (REGCLOBBERF_MM0 << (name[2] - '0'));
  6535. found = true;
  6536. }
  6537. else
  6538. {
  6539. // dword regs
  6540. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6541. {
  6542. if (!strcmp(name.c_str(), regClobberNames[iRegCheck]))
  6543. {
  6544. if (isClobber)
  6545. regClobberFlags |= (1 << iRegCheck);
  6546. found = true;
  6547. break;
  6548. }
  6549. }
  6550. }
  6551. }
  6552. else if (nameLen == 2)
  6553. {
  6554. // word & byte regs
  6555. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6556. {
  6557. if (!strcmp(name.c_str(), regClobberNames[iRegCheck] + 1)) // skip leading 'e'
  6558. {
  6559. if (isClobber)
  6560. regClobberFlags |= (1 << iRegCheck);
  6561. found = true;
  6562. break;
  6563. }
  6564. }
  6565. if (!found)
  6566. {
  6567. // check for byte regs for eax through edx (e.g. al, ah, bl, bh....)
  6568. if ((nameLen == 2) && (name[0] >= 'a') && (name[0] <= 'd') && ((name[1] == 'l') || (name[1] == 'h')))
  6569. {
  6570. if (isClobber)
  6571. regClobberFlags |= (1 << (name[0] - 'a'));// $BYTEREGS this is why we want alphabetical order
  6572. found = true;
  6573. }
  6574. }
  6575. }
  6576. else if ((nameLen == 4) && (name[0] == 'x') && (name[1] == 'm') && (name[2] == 'm') && (name[3] >= '0') && (name[3] <= '7'))
  6577. {
  6578. // xmm regs
  6579. if (isClobber)
  6580. regClobberFlags |= (REGCLOBBERF_XMM0 << (name[3] - '0'));
  6581. found = true;
  6582. }
  6583. return found;
  6584. };
  6585. int asmInstCount = (int)asmStmt->mInstructions.size();
  6586. typedef std::map<String, int> StrToVarIndexMap;
  6587. StrToVarIndexMap strToVarIndexMap;
  6588. if (mCompiler->IsAutocomplete())
  6589. {
  6590. // auto-complete "fast-pass" just to eliminate unused/unassigned variable yellow warning flashes
  6591. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6592. {
  6593. auto instNode = asmStmt->mInstructions[iInst];
  6594. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6595. bool hasLabel = !asmInst.mLabel.empty();
  6596. bool hasOpCode = !asmInst.mOpCode.empty();
  6597. if (hasLabel || hasOpCode) // check against blank lines
  6598. {
  6599. if (hasOpCode) // check against label-only lines (which still get written out, but don't do any other processing)
  6600. {
  6601. int argCount = (int)asmInst.mArgs.size();
  6602. for (int iArg=0; iArg<argCount; ++iArg)
  6603. {
  6604. BfInlineAsmInstruction::AsmArg* arg = &asmInst.mArgs[iArg];
  6605. if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg)
  6606. {
  6607. bool found = matchRegFunc(arg->mReg, false);
  6608. if (!found)
  6609. {
  6610. StrToVarIndexMap::iterator it = strToVarIndexMap.find(arg->mReg);
  6611. if (it == strToVarIndexMap.end())
  6612. {
  6613. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6614. {
  6615. auto& checkLocal = mCurMethodState->mLocals[i];
  6616. if (checkLocal.mName == arg->mReg)
  6617. {
  6618. // if you access a variable in asm, we suppress any warnings related to used or assigned, regardless of usage
  6619. checkLocal.mIsReadFrom = true;
  6620. checkLocal.mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6621. found = true;
  6622. break;
  6623. }
  6624. }
  6625. }
  6626. }
  6627. }
  6628. }
  6629. }
  6630. }
  6631. }
  6632. return;
  6633. }
  6634. int debugLocOffset = 0;
  6635. if (!asmStmt->mInstructions.empty())
  6636. debugLocOffset = asmStmt->mInstructions.front()->GetSrcStart() - asmStmt->GetSrcStart();
  6637. UpdateSrcPos(asmStmt, true, debugLocOffset);
  6638. mCurMethodState->mInHeadScope = false;
  6639. BfScopeData prevScope = mCurMethodState->mCurScope;
  6640. mCurMethodState->mCurScope->mPrevScope = &prevScope;
  6641. NewScopeState();
  6642. bool failed = false;
  6643. if (!mCpu)
  6644. mCpu = new Beefy::X86Cpu();
  6645. //const char* srcAsmText = "nop\nnop\n\n\nmov eax, i\ninc eax\nmov i, eax\n_emit 0x0F\n_emit 0xC7\n_emit 0xF0\n\n\nnop\nnop"; //CDH TODO extract from actual lexical text block
  6646. //const char* srcAsmText = "nop\nnop\n\n\nmov eax, i\ninc eax\nmov i, eax\nrdrand eax\n\n\nnop\nnop"; //CDH TODO extract from actual lexical text block
  6647. //String srcAsmTextStr(&asmStmt->mParser->mSrc[asmStmt->mSrcStart], asmStmt->mSrcEnd - asmStmt->mSrcStart);
  6648. //const char* srcAsmText = srcAsmTextStr.c_str();
  6649. String dstAsmText;
  6650. String constraintStr, clobberStr;
  6651. int constraintCount = 0;
  6652. bool hasMemoryClobber = false;
  6653. Array<Type*> paramTypes;
  6654. SizedArray<Value*, 1> llvmArgs;
  6655. int lastDebugLine = -1;
  6656. int curDebugLineDeltaValue = 0, curDebugLineDeltaRunCount = 0;
  6657. String debugLineSequenceStr;
  6658. int isFirstDebugLine = 1;
  6659. auto maybeEmitDebugLineRun = [&curDebugLineDeltaValue, &curDebugLineDeltaRunCount, &debugLineSequenceStr, &isFirstDebugLine]()
  6660. {
  6661. if (curDebugLineDeltaRunCount > 0)
  6662. {
  6663. for (int i=isFirstDebugLine; i<2; ++i)
  6664. {
  6665. int value = i ? curDebugLineDeltaValue : curDebugLineDeltaRunCount;
  6666. String encodedValue;
  6667. EncodeULEB32(value, encodedValue);
  6668. if (encodedValue.length() > 1)
  6669. debugLineSequenceStr += String("$") + encodedValue + "$";
  6670. else
  6671. debugLineSequenceStr += encodedValue;
  6672. }
  6673. curDebugLineDeltaRunCount = 0;
  6674. isFirstDebugLine = 0;
  6675. }
  6676. };
  6677. auto mangledLabelName = [&asmStmt](const StringImpl& labelName, int numericLabel) -> String
  6678. {
  6679. return StrFormat("%d", numericLabel);
  6680. //return String(".") + labelName;
  6681. //return StrFormat("%s_%p_%d", labelName.c_str(), asmStmt->mSource, asmStmt->mSrcStart); // suffix label name with location information to make it block-specific (since labels get external linkage)
  6682. };
  6683. typedef std::pair<String, int> LabelPair;
  6684. std::unordered_map<String, LabelPair> labelNames;
  6685. // pre-scan instructions for label names
  6686. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6687. {
  6688. auto instNode = asmStmt->mInstructions[iInst];
  6689. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6690. if (!asmInst.mLabel.empty())
  6691. {
  6692. if (labelNames.find(asmInst.mLabel) != labelNames.end())
  6693. {
  6694. Fail(StrFormat("Label \"%s\" already defined in asm block", asmInst.mLabel.c_str()), instNode, true);
  6695. failed = true;
  6696. }
  6697. else
  6698. {
  6699. String mangledLabel(mangledLabelName(asmInst.mLabel, instNode->GetSrcStart()));
  6700. labelNames[asmInst.mLabel] = LabelPair(mangledLabel, instNode->GetSrcStart());
  6701. asmInst.mLabel = mangledLabel;
  6702. }
  6703. }
  6704. }
  6705. for (int iInst=0; iInst<asmInstCount; ++iInst)
  6706. {
  6707. auto instNode = asmStmt->mInstructions[iInst];
  6708. BfInlineAsmInstruction::AsmInst& asmInst = instNode->mAsmInst;
  6709. bool hasLabel = !asmInst.mLabel.empty();
  6710. bool hasOpCode = !asmInst.mOpCode.empty();
  6711. if (hasLabel || hasOpCode) // check against blank lines
  6712. {
  6713. if (hasOpCode) // check against label-only lines (which still get written out, but don't do any other processing)
  6714. {
  6715. int argCount = (int)asmInst.mArgs.size();
  6716. // reasonable defaults for clobber info
  6717. int clobberCount = 1; // destination is usually first arg in Intel syntax
  6718. bool mayClobberMem = true; // we only care about this when it gets turned to false by GetClobbersForMnemonic (no operand form of the instruction clobbers mem)
  6719. // pseudo-ops
  6720. if (asmInst.mOpCode == "_emit")
  6721. {
  6722. asmInst.mOpCode = ".byte";
  6723. }
  6724. else
  6725. {
  6726. Array<int> opcodes;
  6727. if (!mCpu->GetOpcodesForMnemonic(asmInst.mOpCode, opcodes))
  6728. {
  6729. Fail(StrFormat("Unrecognized instruction mnemonic \"%s\"", asmInst.mOpCode.c_str()), instNode, true);
  6730. failed = true;
  6731. }
  6732. else
  6733. {
  6734. Array<int> implicitClobbers;
  6735. mCpu->GetClobbersForMnemonic(asmInst.mOpCode, argCount, implicitClobbers, clobberCount, mayClobberMem);
  6736. for (int iClobberReg : implicitClobbers)
  6737. {
  6738. String regName = CPURegisters::GetRegisterName(iClobberReg);
  6739. std::transform(regName.begin(), regName.end(), regName.begin(), ::tolower);
  6740. matchRegFunc(regName, true);
  6741. }
  6742. }
  6743. }
  6744. String fakeLabel; // used when running label-using instructions through LLVM semantic pre-check
  6745. for (int iArg=0; iArg<argCount; ++iArg)
  6746. {
  6747. BfInlineAsmInstruction::AsmArg* arg = &asmInst.mArgs[iArg];
  6748. if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg)
  6749. {
  6750. bool isClobber = (iArg < clobberCount);
  6751. bool found = matchRegFunc(arg->mReg, isClobber);
  6752. if (!found)
  6753. {
  6754. StrToVarIndexMap::iterator it = strToVarIndexMap.find(arg->mReg);
  6755. if (it != strToVarIndexMap.end())
  6756. {
  6757. arg->mReg = StrFormat("$%d", it->second);
  6758. if (isClobber)
  6759. mayClobberMem = true;
  6760. found = true;
  6761. }
  6762. else
  6763. {
  6764. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6765. {
  6766. auto& checkLocal = mCurMethodState->mLocals[i];
  6767. if (checkLocal.mName == arg->mReg)
  6768. {
  6769. BfIRValue testValue = checkLocal.mAddr;
  6770. llvmArgs.push_back(testValue);
  6771. paramTypes.push_back(testValue->getType());
  6772. arg->mReg = StrFormat("$%d", constraintCount);//CDH TODO does this need size qualifiers for "dword ptr $0" or whatever?
  6773. strToVarIndexMap[checkLocal.mName] = constraintCount;
  6774. constraintStr += "=*m,";
  6775. ++constraintCount;
  6776. if (isClobber)
  6777. mayClobberMem = true;
  6778. // if you access a variable in asm, we suppress any warnings related to used or assigned, regardless of usage
  6779. checkLocal.mIsReadFrom = true;
  6780. checkLocal.mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6781. found = true;
  6782. break;
  6783. }
  6784. }
  6785. }
  6786. }
  6787. if (!found)
  6788. {
  6789. auto labelIt = labelNames.find(arg->mReg);
  6790. if (labelIt != labelNames.end())
  6791. {
  6792. arg->mReg = labelIt->second.first;
  6793. if (labelIt->second.second <= instNode->GetSrcStart())
  6794. {
  6795. fakeLabel = arg->mReg;
  6796. arg->mReg += "b";
  6797. }
  6798. else
  6799. arg->mReg += "f";
  6800. }
  6801. else
  6802. {
  6803. Fail(StrFormat("Unrecognized variable \"%s\"", arg->mReg.c_str()), instNode, true);
  6804. failed = true;
  6805. }
  6806. }
  6807. }
  6808. else if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_FloatReg)
  6809. {
  6810. //CDH individual reg clobber is probably insufficient for fp regs since it's stack-based; without deeper knowledge of how individual instructions
  6811. // manipulate the FP stack, the safest approach is to clobber all FP regs as soon as one of them is involved
  6812. //bool isClobber = (iArg == 0); // destination is first arg in Intel syntax
  6813. //bool found = matchRegFunc(StrFormat("st%d", arg->mInt), isClobber);
  6814. //BF_ASSERT(found);
  6815. for (int iRegCheck=0; iRegCheck<8; ++iRegCheck)
  6816. regClobberFlags |= (REGCLOBBERF_FPST0 << iRegCheck);
  6817. }
  6818. else if (arg->mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_Memory)
  6819. {
  6820. bool isClobber = (iArg < clobberCount);
  6821. // check regs for clobber flags
  6822. /*
  6823. //CDH TODO do we need to set clobber flags for regs that are used *indirectly* like this? Actually I don't think so; commenting out for now
  6824. if (!arg->mReg.empty())
  6825. matchRegFunc(arg->mReg, isClobber);
  6826. if (!arg->mAdjReg.empty())
  6827. matchRegFunc(arg->mAdjReg, isClobber);
  6828. */
  6829. if (isClobber)
  6830. mayClobberMem = true;
  6831. if (!arg->mMemberSuffix.empty())
  6832. {
  6833. //CDH TODO add member support once I know the right way to look up struct member offsets. Once we know the offset,
  6834. // add it to arg->mInt, and set ARGMEMF_ImmediateDisp if it's not set already (member support is just used as an offset)
  6835. Fail("Member suffix syntax is not yet supported", instNode, true);
  6836. failed = true;
  6837. }
  6838. }
  6839. }
  6840. if (mayClobberMem)
  6841. hasMemoryClobber = true;
  6842. //debugLineSequenceStr += StrFormat("%d_", asmInst.mDebugLine);
  6843. int curDebugLine = asmInst.mDebugLine;
  6844. int debugLineDelta = (lastDebugLine > 0) ? curDebugLine - lastDebugLine : curDebugLine;
  6845. lastDebugLine = curDebugLine;
  6846. //String encodedDebugLineDelta;
  6847. //EncodeULEB32(debugLineDelta, encodedDebugLineDelta);
  6848. //debugLineSequenceStr += encodedDebugLineDelta + "_";
  6849. if (curDebugLineDeltaValue != debugLineDelta)
  6850. {
  6851. maybeEmitDebugLineRun();
  6852. curDebugLineDeltaValue = debugLineDelta;
  6853. }
  6854. ++curDebugLineDeltaRunCount;
  6855. // run instruction through LLVM for better semantic errors (can be slow in debug; feel free to comment out this scopeData if it's intolerable; the errors will still be caught at compile time)
  6856. //if (false)
  6857. {
  6858. BfInlineAsmInstruction::AsmInst tempAsmInst(asmInst);
  6859. tempAsmInst.mLabel = fakeLabel;
  6860. for (auto & arg : tempAsmInst.mArgs)
  6861. {
  6862. if ((arg.mType == BfInlineAsmInstruction::AsmArg::ARGTYPE_IntReg) && !arg.mReg.empty() && (arg.mReg[0] == '$'))
  6863. {
  6864. // if we've rewritten a local variable instruction arg to use a $-prefixed input, we can't pass that to LLVM
  6865. // at this stage as it won't recognize it; the actual compilation would have changed all these to use actual
  6866. // memory operand syntax first. However, those changes all work down in LLVM to printIntelMemReference inside
  6867. // of X86AsmPrinter.cpp, and that always results in a [bracketed] memory access string no matter what, which
  6868. // means for our semantic checking purposes here it's sufficient to just use "[eax]" for all such cases,
  6869. // rather than go through an even more expensive setup & teardown process to use the AsmPrinter itself.
  6870. arg.mType = BfInlineAsmInstruction::AsmArg::ARGTYPE_Memory;
  6871. arg.mMemFlags = BfInlineAsmInstruction::AsmArg::ARGMEMF_BaseReg;
  6872. arg.mReg = "eax";
  6873. }
  6874. }
  6875. String llvmError;
  6876. if (!mCpu->ParseInlineAsmInstructionLLVM(tempAsmInst.ToString(), llvmError))
  6877. {
  6878. Fail(StrFormat("Inline asm error: %s", llvmError.c_str()), instNode, true);
  6879. failed = true;
  6880. }
  6881. }
  6882. }
  6883. dstAsmText += asmInst.ToString();
  6884. dstAsmText += "\n";
  6885. }
  6886. }
  6887. maybeEmitDebugLineRun(); // leftovers
  6888. if (failed)
  6889. {
  6890. RestoreScopeState(&prevScope);
  6891. return;
  6892. }
  6893. // prepare constraints/clobbers
  6894. {
  6895. for (int iRegCheck = 0; regClobberNames[iRegCheck] != nullptr; ++iRegCheck)
  6896. {
  6897. if (regClobberFlags & (1 << iRegCheck))
  6898. clobberStr += StrFormat("~{%s},", regClobberNames[iRegCheck]);
  6899. }
  6900. for (int iRegCheck=0; iRegCheck<8; ++iRegCheck)
  6901. {
  6902. if (regClobberFlags & (REGCLOBBERF_XMM0 << iRegCheck))
  6903. clobberStr += StrFormat("~{xmm%d},", iRegCheck);
  6904. if (regClobberFlags & (REGCLOBBERF_FPST0 << iRegCheck))
  6905. clobberStr += StrFormat("~{fp%d},~{st(%d)},", iRegCheck, iRegCheck); // both fp# and st(#) are listed in X86RegisterInfo.td
  6906. if (regClobberFlags & (REGCLOBBERF_MM0 << iRegCheck))
  6907. clobberStr += StrFormat("~{mm%d},", iRegCheck);
  6908. }
  6909. // add wrapping instructions to preserve certain regs (e.g. ESI), due to LLVM bypassing register allocator when choosing a base register
  6910. //CDH TODO currently I'm only shielding against ESI stompage; people generally know not to mess with ESP & EBP, but ESI is still a "general" reg and should be allowed to be clobbered
  6911. //if (regClobberFlags & REGCLOBBERF_ESI)
  6912. //{
  6913. //CDH TODO Bah! This doesn't actually work, because if you do any local variable access after mutating ESI, the variable substitution could have generated a base address dependency
  6914. // on ESI which will not expect it to have changed, e.g. "mov esi, var\ninc esi\nmov var, esi\n" dies if "var" gets internally rewritten to "[esi + displacement]". What to do? Hmm.
  6915. //dstAsmText = String("push esi\n") + dstAsmText + String("pop esi\n");
  6916. //}
  6917. if (hasMemoryClobber)
  6918. clobberStr += "~{memory},";
  6919. clobberStr += "~{dirflag},~{fpsr},~{flags}";
  6920. constraintStr += clobberStr;
  6921. }
  6922. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  6923. if (wantsDIData)
  6924. {
  6925. static int sVarNum = 0;
  6926. String varName(StrFormat("__asmLines_%d.%s", ++sVarNum, debugLineSequenceStr.c_str()));
  6927. auto varType = GetPrimitiveType(BfTypeCode_Int32);
  6928. auto allocaInst = mBfIRBuilder->CreateAlloca(varType->mLLVMType, 0, varName + ".addr");
  6929. allocaInst->setAlignment(varType->mAlign);
  6930. //paramVar->mAddr = allocaInst;
  6931. auto varValue = GetConstValue(0, varType);
  6932. auto diVariable = mDIBuilder->createAutoVariable(mCurMethodState->mCurScope->mDIScope,
  6933. varName.c_str(), mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, varType->mDIType/*, true*/);
  6934. //auto varValue = llvm::ConstantInt::getTrue(*mLLVMContext);
  6935. //auto varValue = GetDefaultValue(varType);
  6936. //auto varValue = CreateGlobalConstValue(varName, llvm::ConstantInt::getTrue(*mLLVMContext), true);
  6937. //auto varValue = AllocGlobalVariable(*mIRModule, diType->getType(), false, GlobalValue::ExternalLinkage, llvm::ConstantInt::getTrue(*mLLVMContext), varName.c_str());
  6938. //auto diVariable = mDIBuilder->createGlobalVariable(mCurMethodState->mCurScope->mDIScope, varName.c_str(), "", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, false, varValue);
  6939. //BasicBlock* block = mBfIRBuilder->GetInsertBlock();
  6940. //auto declareVar = mDIBuilder->insertDeclare(varValue, diVariable, mBfIRBuilder->GetInsertBlock());
  6941. auto declareVar = mDIBuilder->insertDeclare(allocaInst, diVariable, mDIBuilder->createExpression(),
  6942. mIRBuilder->getCurrentDebugLocation(), mBfIRBuilder->GetInsertBlock());
  6943. //auto declareVar = mDIBuilder->insertDbgValueIntrinsic(varValue, 0, diVariable, mBfIRBuilder->GetInsertBlock());
  6944. declareVar->setDebugLoc(mIRBuilder->getCurrentDebugLocation());
  6945. }
  6946. /*
  6947. BfIRValue testValue = NULL;
  6948. for (int i = 0; i < (int) mCurMethodState->mLocals.size(); i++)
  6949. {
  6950. auto& checkLocal = mCurMethodState->mLocals[i];
  6951. if (checkLocal.mName == "i")
  6952. {
  6953. testValue = checkLocal.mAddr;
  6954. break;
  6955. }
  6956. }
  6957. */
  6958. //BF_ASSERT((testValue != NULL) && "Need local variable \"i\"");
  6959. //if (testValue != NULL)
  6960. {
  6961. //Type* voidPtrType = Type::getInt8PtrTy(*mLLVMContext);
  6962. //if (mContext->mAsmObjectCheckFuncType == NULL)
  6963. //{
  6964. //Array<Type*> paramTypes;
  6965. //paramTypes.push_back(voidPtrType);
  6966. //mContext->mAsmObjectCheckFuncType = FunctionType::get(Type::getVoidTy(*mLLVMContext), paramTypes, false);
  6967. //}
  6968. FunctionType* funcType = FunctionType::get(Type::getVoidTy(*mLLVMContext), paramTypes, false);
  6969. //SizedArray<Value*, 1> llvmArgs;
  6970. //llvmArgs.push_back(testValue);
  6971. //CDH REMOVE NOTE
  6972. //generates IR (e.g.):
  6973. // call void asm sideeffect "#4\0Anop\0Anop\0Amovl %eax, %eax\0Anop\0Anop", "~{cc},~{dirflag},~{fpsr},~{flags},~{eax}"() #0, !dbg !492
  6974. static int asmIdx = 0;
  6975. asmIdx++;
  6976. String asmStr = StrFormat("#%d\n", asmIdx) +
  6977. //"nop\nnop\nmovl $0, %eax\nincl %eax\nmovl %eax, $0\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6978. //"nop\nnop\nmovl ($0), %eax\nincl %eax\nmovl %eax, ($0)\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6979. //"nop\nnop\nmovl %eax, %eax\nmovl $$0, %ecx\nmovl $$0, %esp\nnop\nnop";
  6980. //"nop\nnop\nmovl %eax, %eax\nnop\nnop";
  6981. //"nop\nnop\n.byte 0x0F\n.byte 0xC7\n.byte 0xF0\nmov eax, 7\nmov ecx, 0\ncpuid\nmov eax, dword ptr $0\ninc eax\nmov dword ptr $0, eax\nmov ecx, 0\nmov esp, 0\nnop\nnop"; // rdrand test
  6982. dstAsmText;
  6983. llvm::InlineAsm* inlineAsm = llvm::InlineAsm::get(funcType,
  6984. //asmStr.c_str(), "~{r},~{cc},~{dirflag},~{fpsr},~{flags},~{eax},~{memory},~{esi},~{esp}", true,
  6985. //asmStr.c_str(), "~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{ecx},~{esp}", true,
  6986. //DOES NOT WORK (mem not written back to from reg:
  6987. //asmStr.c_str(), "+r,~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{eax},~{ecx},~{esp}", true,
  6988. //asmStr.c_str(), "+rm,~{cc},~{dirflag},~{fpsr},~{flags},~{memory},~{eax},~{ecx},~{esp}", true,
  6989. asmStr.c_str(), constraintStr.c_str(), true,
  6990. false, /*llvm::InlineAsm::AD_ATT*/llvm::InlineAsm::AD_Intel);
  6991. llvm::CallInst* callInst = mIRBuilder->CreateCall(inlineAsm, llvmArgs);
  6992. //llvm::CallInst* callInst = mIRBuilder->CreateCall(inlineAsm);
  6993. callInst->addAttribute(llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoUnwind);
  6994. }
  6995. RestoreScopeState(&prevScope);
  6996. #endif
  6997. }