aoptx86.pas 631 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p : tai) : boolean; static;
  102. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  103. class function IsBTXAcceptable(p : tai) : boolean; static;
  104. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  105. conversion was successful }
  106. function ConvertLEA(const p : taicpu): Boolean;
  107. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  108. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  109. procedure DebugMsg(const s : string; p : tai);inline;
  110. class function IsExitCode(p : tai) : boolean; static;
  111. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  112. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  113. procedure RemoveLastDeallocForFuncRes(p : tai);
  114. function DoArithCombineOpt(var p : tai) : Boolean;
  115. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  116. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  117. function PrePeepholeOptSxx(var p : tai) : boolean;
  118. function PrePeepholeOptIMUL(var p : tai) : boolean;
  119. function PrePeepholeOptAND(var p : tai) : boolean;
  120. function OptPass1Test(var p: tai): boolean;
  121. function OptPass1Add(var p: tai): boolean;
  122. function OptPass1AND(var p : tai) : boolean;
  123. function OptPass1_V_MOVAP(var p : tai) : boolean;
  124. function OptPass1VOP(var p : tai) : boolean;
  125. function OptPass1MOV(var p : tai) : boolean;
  126. function OptPass1Movx(var p : tai) : boolean;
  127. function OptPass1MOVXX(var p : tai) : boolean;
  128. function OptPass1OP(var p : tai) : boolean;
  129. function OptPass1LEA(var p : tai) : boolean;
  130. function OptPass1Sub(var p : tai) : boolean;
  131. function OptPass1SHLSAL(var p : tai) : boolean;
  132. function OptPass1SHR(var p : tai) : boolean;
  133. function OptPass1FSTP(var p : tai) : boolean;
  134. function OptPass1FLD(var p : tai) : boolean;
  135. function OptPass1Cmp(var p : tai) : boolean;
  136. function OptPass1PXor(var p : tai) : boolean;
  137. function OptPass1VPXor(var p: tai): boolean;
  138. function OptPass1Imul(var p : tai) : boolean;
  139. function OptPass1Jcc(var p : tai) : boolean;
  140. function OptPass1SHXX(var p: tai): boolean;
  141. function OptPass1VMOVDQ(var p: tai): Boolean;
  142. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  143. function OptPass2Movx(var p : tai): Boolean;
  144. function OptPass2MOV(var p : tai) : boolean;
  145. function OptPass2Imul(var p : tai) : boolean;
  146. function OptPass2Jmp(var p : tai) : boolean;
  147. function OptPass2Jcc(var p : tai) : boolean;
  148. function OptPass2Lea(var p: tai): Boolean;
  149. function OptPass2SUB(var p: tai): Boolean;
  150. function OptPass2ADD(var p : tai): Boolean;
  151. function OptPass2SETcc(var p : tai) : boolean;
  152. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  153. function PostPeepholeOptMov(var p : tai) : Boolean;
  154. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  155. function PostPeepholeOptXor(var p : tai) : Boolean;
  156. function PostPeepholeOptAnd(var p : tai) : boolean;
  157. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  158. function PostPeepholeOptCmp(var p : tai) : Boolean;
  159. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  160. function PostPeepholeOptCall(var p : tai) : Boolean;
  161. function PostPeepholeOptLea(var p : tai) : Boolean;
  162. function PostPeepholeOptPush(var p: tai): Boolean;
  163. function PostPeepholeOptShr(var p : tai) : boolean;
  164. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  165. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  166. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  167. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  168. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  169. { Processor-dependent reference optimisation }
  170. class procedure OptimizeRefs(var p: taicpu); static;
  171. end;
  172. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  173. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  175. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  176. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  177. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  178. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  179. {$if max_operands>2}
  180. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  181. {$endif max_operands>2}
  182. function RefsEqual(const r1, r2: treference): boolean;
  183. { Note that Result is set to True if the references COULD overlap but the
  184. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  185. might still overlap because %reg2 could be equal to %reg1-4 }
  186. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  187. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  188. { returns true, if ref is a reference using only the registers passed as base and index
  189. and having an offset }
  190. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  191. implementation
  192. uses
  193. cutils,verbose,
  194. systems,
  195. globals,
  196. cpuinfo,
  197. procinfo,
  198. paramgr,
  199. aasmbase,
  200. aoptbase,aoptutils,
  201. symconst,symsym,
  202. cgx86,
  203. itcpugas;
  204. {$ifdef DEBUG_AOPTCPU}
  205. const
  206. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  207. {$else DEBUG_AOPTCPU}
  208. { Empty strings help the optimizer to remove string concatenations that won't
  209. ever appear to the user on release builds. [Kit] }
  210. const
  211. SPeepholeOptimization = '';
  212. {$endif DEBUG_AOPTCPU}
  213. LIST_STEP_SIZE = 4;
  214. type
  215. TJumpTrackingItem = class(TLinkedListItem)
  216. private
  217. FSymbol: TAsmSymbol;
  218. FRefs: LongInt;
  219. public
  220. constructor Create(ASymbol: TAsmSymbol);
  221. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  222. property Symbol: TAsmSymbol read FSymbol;
  223. property Refs: LongInt read FRefs;
  224. end;
  225. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  226. begin
  227. inherited Create;
  228. FSymbol := ASymbol;
  229. FRefs := 0;
  230. end;
  231. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  232. begin
  233. Inc(FRefs);
  234. end;
  235. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. (taicpu(instr).opcode = op) and
  240. ((opsize = []) or (taicpu(instr).opsize in opsize));
  241. end;
  242. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. ((taicpu(instr).opcode = op1) or
  247. (taicpu(instr).opcode = op2)
  248. ) and
  249. ((opsize = []) or (taicpu(instr).opsize in opsize));
  250. end;
  251. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  252. begin
  253. result :=
  254. (instr.typ = ait_instruction) and
  255. ((taicpu(instr).opcode = op1) or
  256. (taicpu(instr).opcode = op2) or
  257. (taicpu(instr).opcode = op3)
  258. ) and
  259. ((opsize = []) or (taicpu(instr).opsize in opsize));
  260. end;
  261. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  262. const opsize : topsizes) : boolean;
  263. var
  264. op : TAsmOp;
  265. begin
  266. result:=false;
  267. if (instr.typ <> ait_instruction) or
  268. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  269. exit;
  270. for op in ops do
  271. begin
  272. if taicpu(instr).opcode = op then
  273. begin
  274. result:=true;
  275. exit;
  276. end;
  277. end;
  278. end;
  279. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  280. begin
  281. result := (oper.typ = top_reg) and (oper.reg = reg);
  282. end;
  283. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  284. begin
  285. result := (oper.typ = top_const) and (oper.val = a);
  286. end;
  287. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  288. begin
  289. result := oper1.typ = oper2.typ;
  290. if result then
  291. case oper1.typ of
  292. top_const:
  293. Result:=oper1.val = oper2.val;
  294. top_reg:
  295. Result:=oper1.reg = oper2.reg;
  296. top_ref:
  297. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  298. else
  299. internalerror(2013102801);
  300. end
  301. end;
  302. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  303. begin
  304. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  305. if result then
  306. case oper1.typ of
  307. top_const:
  308. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  309. top_reg:
  310. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  311. top_ref:
  312. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  313. else
  314. internalerror(2020052401);
  315. end
  316. end;
  317. function RefsEqual(const r1, r2: treference): boolean;
  318. begin
  319. RefsEqual :=
  320. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  321. (r1.relsymbol = r2.relsymbol) and
  322. (r1.segment = r2.segment) and (r1.base = r2.base) and
  323. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  324. (r1.offset = r2.offset) and
  325. (r1.volatility + r2.volatility = []);
  326. end;
  327. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  328. begin
  329. if (r1.symbol<>r2.symbol) then
  330. { If the index registers are different, there's a chance one could
  331. be set so it equals the other symbol }
  332. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  333. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  334. (r1.relsymbol = r2.relsymbol) and
  335. (r1.segment = r2.segment) and (r1.base = r2.base) and
  336. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  337. (r1.volatility + r2.volatility = []) then
  338. { In this case, it all depends on the offsets }
  339. Exit(abs(r1.offset - r2.offset) < Range);
  340. { There's a chance things MIGHT overlap, so take no chances }
  341. Result := True;
  342. end;
  343. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  344. begin
  345. Result:=(ref.offset=0) and
  346. (ref.scalefactor in [0,1]) and
  347. (ref.segment=NR_NO) and
  348. (ref.symbol=nil) and
  349. (ref.relsymbol=nil) and
  350. ((base=NR_INVALID) or
  351. (ref.base=base)) and
  352. ((index=NR_INVALID) or
  353. (ref.index=index)) and
  354. (ref.volatility=[]);
  355. end;
  356. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  357. begin
  358. Result:=(ref.scalefactor in [0,1]) and
  359. (ref.segment=NR_NO) and
  360. (ref.symbol=nil) and
  361. (ref.relsymbol=nil) and
  362. ((base=NR_INVALID) or
  363. (ref.base=base)) and
  364. ((index=NR_INVALID) or
  365. (ref.index=index)) and
  366. (ref.volatility=[]);
  367. end;
  368. function InstrReadsFlags(p: tai): boolean;
  369. begin
  370. InstrReadsFlags := true;
  371. case p.typ of
  372. ait_instruction:
  373. if InsProp[taicpu(p).opcode].Ch*
  374. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  375. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  376. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  377. exit;
  378. ait_label:
  379. exit;
  380. else
  381. ;
  382. end;
  383. InstrReadsFlags := false;
  384. end;
  385. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  386. begin
  387. Next:=Current;
  388. repeat
  389. Result:=GetNextInstruction(Next,Next);
  390. until not (Result) or
  391. not(cs_opt_level3 in current_settings.optimizerswitches) or
  392. (Next.typ<>ait_instruction) or
  393. RegInInstruction(reg,Next) or
  394. is_calljmp(taicpu(Next).opcode);
  395. end;
  396. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  397. var
  398. GetNextResult: Boolean;
  399. begin
  400. Result:=0;
  401. Next:=Current;
  402. repeat
  403. GetNextResult := GetNextInstruction(Next,Next);
  404. if GetNextResult then
  405. Inc(Result)
  406. else
  407. { Must return zero upon hitting the end of the linked list without a match }
  408. Result := 0;
  409. until not (GetNextResult) or
  410. not(cs_opt_level3 in current_settings.optimizerswitches) or
  411. (Next.typ<>ait_instruction) or
  412. RegInInstruction(reg,Next) or
  413. is_calljmp(taicpu(Next).opcode);
  414. end;
  415. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  416. procedure TrackJump(Symbol: TAsmSymbol);
  417. var
  418. Search: TJumpTrackingItem;
  419. begin
  420. { See if an entry already exists in our jump tracking list
  421. (faster to search backwards due to the higher chance of
  422. matching destinations) }
  423. Search := TJumpTrackingItem(JumpTracking.Last);
  424. while Assigned(Search) do
  425. begin
  426. if Search.Symbol = Symbol then
  427. begin
  428. { Found it - remove it so it can be pushed to the front }
  429. JumpTracking.Remove(Search);
  430. Break;
  431. end;
  432. Search := TJumpTrackingItem(Search.Previous);
  433. end;
  434. if not Assigned(Search) then
  435. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  436. JumpTracking.Concat(Search);
  437. Search.IncRefs;
  438. end;
  439. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  440. var
  441. Search: TJumpTrackingItem;
  442. begin
  443. Result := False;
  444. { See if this label appears in the tracking list }
  445. Search := TJumpTrackingItem(JumpTracking.Last);
  446. while Assigned(Search) do
  447. begin
  448. if Search.Symbol = Symbol then
  449. begin
  450. { Found it - let's see what we can discover }
  451. if Search.Symbol.getrefs = Search.Refs then
  452. begin
  453. { Success - all the references are accounted for }
  454. JumpTracking.Remove(Search);
  455. Search.Free;
  456. { It is logically impossible for CrossJump to be false here
  457. because we must have run into a conditional jump for
  458. this label at some point }
  459. if not CrossJump then
  460. InternalError(2022041710);
  461. if JumpTracking.First = nil then
  462. { Tracking list is now empty - no more cross jumps }
  463. CrossJump := False;
  464. Result := True;
  465. Exit;
  466. end;
  467. { If the references don't match, it's possible to enter
  468. this label through other means, so drop out }
  469. Exit;
  470. end;
  471. Search := TJumpTrackingItem(Search.Previous);
  472. end;
  473. end;
  474. var
  475. Next_Label: tai;
  476. begin
  477. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  478. Next := Current;
  479. repeat
  480. Result := GetNextInstruction(Next,Next);
  481. if not Result then
  482. Break;
  483. if Next.typ = ait_align then
  484. Result := SkipAligns(Next, Next);
  485. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  486. if is_calljmpuncondret(taicpu(Next).opcode) then
  487. begin
  488. if (taicpu(Next).opcode = A_JMP) and
  489. { Remove dead code now to save time }
  490. RemoveDeadCodeAfterJump(taicpu(Next)) then
  491. { A jump was removed, but not the current instruction, and
  492. Result doesn't necessarily translate into an optimisation
  493. routine's Result, so use the "Force New Iteration" flag so
  494. mark a new pass }
  495. Include(OptsToCheck, aoc_ForceNewIteration);
  496. if not Assigned(JumpTracking) then
  497. begin
  498. { Cross-label optimisations often causes other optimisations
  499. to perform worse because they're not given the chance to
  500. optimise locally. In this case, don't do the cross-label
  501. optimisations yet, but flag them as a potential possibility
  502. for the next iteration of Pass 1 }
  503. if not NotFirstIteration then
  504. Include(OptsToCheck, aoc_ForceNewIteration);
  505. end
  506. else if IsJumpToLabel(taicpu(Next)) and
  507. GetNextInstruction(Next, Next_Label) and
  508. SkipAligns(Next_Label, Next_Label) then
  509. begin
  510. { If we have JMP .lbl, and the label after it has all of its
  511. references tracked, then this is probably an if-else style of
  512. block and we can keep tracking. If the label for this jump
  513. then appears later and is fully tracked, then it's the end
  514. of the if-else blocks and the code paths converge (thus
  515. marking the end of the cross-jump) }
  516. if (Next_Label.typ = ait_label) then
  517. begin
  518. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  519. begin
  520. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  521. Next := Next_Label;
  522. { CrossJump gets set to false by LabelAccountedFor if the
  523. list is completely emptied (as it indicates that all
  524. code paths have converged). We could avoid this nuance
  525. by moving the TrackJump call to before the
  526. LabelAccountedFor call, but this is slower in situations
  527. where LabelAccountedFor would return False due to the
  528. creation of a new object that is not used and destroyed
  529. soon after. }
  530. CrossJump := True;
  531. Continue;
  532. end;
  533. end
  534. else if (Next_Label.typ <> ait_marker) then
  535. { We just did a RemoveDeadCodeAfterJump, so either we find
  536. a label, the end of the procedure or some kind of marker}
  537. InternalError(2022041720);
  538. end;
  539. Result := False;
  540. Exit;
  541. end
  542. else
  543. begin
  544. if not Assigned(JumpTracking) then
  545. begin
  546. { Cross-label optimisations often causes other optimisations
  547. to perform worse because they're not given the chance to
  548. optimise locally. In this case, don't do the cross-label
  549. optimisations yet, but flag them as a potential possibility
  550. for the next iteration of Pass 1 }
  551. if not NotFirstIteration then
  552. Include(OptsToCheck, aoc_ForceNewIteration);
  553. end
  554. else if IsJumpToLabel(taicpu(Next)) then
  555. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  556. else
  557. { Conditional jumps should always be a jump to label }
  558. InternalError(2022041701);
  559. CrossJump := True;
  560. Continue;
  561. end;
  562. if Next.typ = ait_label then
  563. begin
  564. if not Assigned(JumpTracking) then
  565. begin
  566. { Cross-label optimisations often causes other optimisations
  567. to perform worse because they're not given the chance to
  568. optimise locally. In this case, don't do the cross-label
  569. optimisations yet, but flag them as a potential possibility
  570. for the next iteration of Pass 1 }
  571. if not NotFirstIteration then
  572. Include(OptsToCheck, aoc_ForceNewIteration);
  573. end
  574. else if LabelAccountedFor(tai_label(Next).labsym) then
  575. Continue;
  576. { If we reach here, we're at a label that hasn't been seen before
  577. (or JumpTracking was nil) }
  578. Break;
  579. end;
  580. until not Result or
  581. not (cs_opt_level3 in current_settings.optimizerswitches) or
  582. not (Next.typ in [ait_label, ait_instruction]) or
  583. RegInInstruction(reg,Next);
  584. end;
  585. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  586. begin
  587. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  588. begin
  589. Result:=GetNextInstruction(Current,Next);
  590. exit;
  591. end;
  592. Next:=tai(Current.Next);
  593. Result:=false;
  594. while assigned(Next) do
  595. begin
  596. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  597. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  598. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  599. exit
  600. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  601. begin
  602. Result:=true;
  603. exit;
  604. end;
  605. Next:=tai(Next.Next);
  606. end;
  607. end;
  608. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  609. begin
  610. Result:=RegReadByInstruction(reg,hp);
  611. end;
  612. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  613. var
  614. p: taicpu;
  615. opcount: longint;
  616. begin
  617. RegReadByInstruction := false;
  618. if hp.typ <> ait_instruction then
  619. exit;
  620. p := taicpu(hp);
  621. case p.opcode of
  622. A_CALL:
  623. regreadbyinstruction := true;
  624. A_IMUL:
  625. case p.ops of
  626. 1:
  627. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  628. (
  629. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  630. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  631. );
  632. 2,3:
  633. regReadByInstruction :=
  634. reginop(reg,p.oper[0]^) or
  635. reginop(reg,p.oper[1]^);
  636. else
  637. InternalError(2019112801);
  638. end;
  639. A_MUL:
  640. begin
  641. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  642. (
  643. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  644. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  645. );
  646. end;
  647. A_IDIV,A_DIV:
  648. begin
  649. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  650. (
  651. (getregtype(reg)=R_INTREGISTER) and
  652. (
  653. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  654. )
  655. );
  656. end;
  657. else
  658. begin
  659. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  660. begin
  661. RegReadByInstruction := false;
  662. exit;
  663. end;
  664. for opcount := 0 to p.ops-1 do
  665. if (p.oper[opCount]^.typ = top_ref) and
  666. RegInRef(reg,p.oper[opcount]^.ref^) then
  667. begin
  668. RegReadByInstruction := true;
  669. exit
  670. end;
  671. { special handling for SSE MOVSD }
  672. if (p.opcode=A_MOVSD) and (p.ops>0) then
  673. begin
  674. if p.ops<>2 then
  675. internalerror(2017042702);
  676. regReadByInstruction := reginop(reg,p.oper[0]^) or
  677. (
  678. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  679. );
  680. exit;
  681. end;
  682. with insprop[p.opcode] do
  683. begin
  684. case getregtype(reg) of
  685. R_INTREGISTER:
  686. begin
  687. case getsupreg(reg) of
  688. RS_EAX:
  689. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  690. begin
  691. RegReadByInstruction := true;
  692. exit
  693. end;
  694. RS_ECX:
  695. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  696. begin
  697. RegReadByInstruction := true;
  698. exit
  699. end;
  700. RS_EDX:
  701. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  702. begin
  703. RegReadByInstruction := true;
  704. exit
  705. end;
  706. RS_EBX:
  707. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  708. begin
  709. RegReadByInstruction := true;
  710. exit
  711. end;
  712. RS_ESP:
  713. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  714. begin
  715. RegReadByInstruction := true;
  716. exit
  717. end;
  718. RS_EBP:
  719. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. RS_ESI:
  725. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  726. begin
  727. RegReadByInstruction := true;
  728. exit
  729. end;
  730. RS_EDI:
  731. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  732. begin
  733. RegReadByInstruction := true;
  734. exit
  735. end;
  736. end;
  737. end;
  738. R_MMREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_XMM0:
  742. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. end;
  748. end;
  749. else
  750. ;
  751. end;
  752. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  753. begin
  754. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  755. begin
  756. case p.condition of
  757. C_A,C_NBE, { CF=0 and ZF=0 }
  758. C_BE,C_NA: { CF=1 or ZF=1 }
  759. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  760. C_AE,C_NB,C_NC, { CF=0 }
  761. C_B,C_NAE,C_C: { CF=1 }
  762. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  763. C_NE,C_NZ, { ZF=0 }
  764. C_E,C_Z: { ZF=1 }
  765. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  766. C_G,C_NLE, { ZF=0 and SF=OF }
  767. C_LE,C_NG: { ZF=1 or SF<>OF }
  768. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  769. C_GE,C_NL, { SF=OF }
  770. C_L,C_NGE: { SF<>OF }
  771. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  772. C_NO, { OF=0 }
  773. C_O: { OF=1 }
  774. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  775. C_NP,C_PO, { PF=0 }
  776. C_P,C_PE: { PF=1 }
  777. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  778. C_NS, { SF=0 }
  779. C_S: { SF=1 }
  780. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  781. else
  782. internalerror(2017042701);
  783. end;
  784. if RegReadByInstruction then
  785. exit;
  786. end;
  787. case getsubreg(reg) of
  788. R_SUBW,R_SUBD,R_SUBQ:
  789. RegReadByInstruction :=
  790. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  791. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  792. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  793. R_SUBFLAGCARRY:
  794. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  795. R_SUBFLAGPARITY:
  796. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  797. R_SUBFLAGAUXILIARY:
  798. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  799. R_SUBFLAGZERO:
  800. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  801. R_SUBFLAGSIGN:
  802. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGOVERFLOW:
  804. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGINTERRUPT:
  806. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGDIRECTION:
  808. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. else
  810. internalerror(2017042601);
  811. end;
  812. exit;
  813. end;
  814. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  815. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  816. (p.oper[0]^.reg=p.oper[1]^.reg) then
  817. exit;
  818. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  819. begin
  820. RegReadByInstruction := true;
  821. exit
  822. end;
  823. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  824. begin
  825. RegReadByInstruction := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  829. begin
  830. RegReadByInstruction := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  834. begin
  835. RegReadByInstruction := true;
  836. exit
  837. end;
  838. end;
  839. end;
  840. end;
  841. end;
  842. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  843. begin
  844. result:=false;
  845. if p1.typ<>ait_instruction then
  846. exit;
  847. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  848. exit(true);
  849. if (getregtype(reg)=R_INTREGISTER) and
  850. { change information for xmm movsd are not correct }
  851. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  852. begin
  853. case getsupreg(reg) of
  854. { RS_EAX = RS_RAX on x86-64 }
  855. RS_EAX:
  856. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  857. RS_ECX:
  858. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  859. RS_EDX:
  860. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  861. RS_EBX:
  862. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  863. RS_ESP:
  864. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  865. RS_EBP:
  866. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  867. RS_ESI:
  868. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. RS_EDI:
  870. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. else
  872. ;
  873. end;
  874. if result then
  875. exit;
  876. end
  877. else if getregtype(reg)=R_MMREGISTER then
  878. begin
  879. case getsupreg(reg) of
  880. RS_XMM0:
  881. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  882. else
  883. ;
  884. end;
  885. if result then
  886. exit;
  887. end
  888. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  889. begin
  890. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  891. exit(true);
  892. case getsubreg(reg) of
  893. R_SUBFLAGCARRY:
  894. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. R_SUBFLAGPARITY:
  896. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  897. R_SUBFLAGAUXILIARY:
  898. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  899. R_SUBFLAGZERO:
  900. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  901. R_SUBFLAGSIGN:
  902. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  903. R_SUBFLAGOVERFLOW:
  904. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. R_SUBFLAGINTERRUPT:
  906. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. R_SUBFLAGDIRECTION:
  908. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  909. R_SUBW,R_SUBD,R_SUBQ:
  910. { Everything except the direction bits }
  911. Result:=
  912. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  913. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  914. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  915. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  916. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  917. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  918. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  919. else
  920. ;
  921. end;
  922. if result then
  923. exit;
  924. end
  925. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  926. exit(true);
  927. Result:=inherited RegInInstruction(Reg, p1);
  928. end;
  929. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  930. const
  931. WriteOps: array[0..3] of set of TInsChange =
  932. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  933. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  934. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  935. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  936. var
  937. OperIdx: Integer;
  938. begin
  939. Result := False;
  940. if p1.typ <> ait_instruction then
  941. exit;
  942. with insprop[taicpu(p1).opcode] do
  943. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  944. begin
  945. case getsubreg(reg) of
  946. R_SUBW,R_SUBD,R_SUBQ:
  947. Result :=
  948. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  949. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  950. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  951. R_SUBFLAGCARRY:
  952. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  953. R_SUBFLAGPARITY:
  954. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  955. R_SUBFLAGAUXILIARY:
  956. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  957. R_SUBFLAGZERO:
  958. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  959. R_SUBFLAGSIGN:
  960. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  961. R_SUBFLAGOVERFLOW:
  962. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  963. R_SUBFLAGINTERRUPT:
  964. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  965. R_SUBFLAGDIRECTION:
  966. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  967. else
  968. internalerror(2017042602);
  969. end;
  970. exit;
  971. end;
  972. case taicpu(p1).opcode of
  973. A_CALL:
  974. { We could potentially set Result to False if the register in
  975. question is non-volatile for the subroutine's calling convention,
  976. but this would require detecting the calling convention in use and
  977. also assuming that the routine doesn't contain malformed assembly
  978. language, for example... so it could only be done under -O4 as it
  979. would be considered a side-effect. [Kit] }
  980. Result := True;
  981. A_MOVSD:
  982. { special handling for SSE MOVSD }
  983. if (taicpu(p1).ops>0) then
  984. begin
  985. if taicpu(p1).ops<>2 then
  986. internalerror(2017042703);
  987. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  988. end;
  989. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  990. so fix it here (FK)
  991. }
  992. A_VMOVSS,
  993. A_VMOVSD:
  994. begin
  995. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  996. exit;
  997. end;
  998. A_IMUL:
  999. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1000. else
  1001. ;
  1002. end;
  1003. if Result then
  1004. exit;
  1005. with insprop[taicpu(p1).opcode] do
  1006. begin
  1007. if getregtype(reg)=R_INTREGISTER then
  1008. begin
  1009. case getsupreg(reg) of
  1010. RS_EAX:
  1011. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1012. begin
  1013. Result := True;
  1014. exit
  1015. end;
  1016. RS_ECX:
  1017. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1018. begin
  1019. Result := True;
  1020. exit
  1021. end;
  1022. RS_EDX:
  1023. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1024. begin
  1025. Result := True;
  1026. exit
  1027. end;
  1028. RS_EBX:
  1029. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1030. begin
  1031. Result := True;
  1032. exit
  1033. end;
  1034. RS_ESP:
  1035. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1036. begin
  1037. Result := True;
  1038. exit
  1039. end;
  1040. RS_EBP:
  1041. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1042. begin
  1043. Result := True;
  1044. exit
  1045. end;
  1046. RS_ESI:
  1047. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1048. begin
  1049. Result := True;
  1050. exit
  1051. end;
  1052. RS_EDI:
  1053. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1054. begin
  1055. Result := True;
  1056. exit
  1057. end;
  1058. end;
  1059. end;
  1060. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1061. if (WriteOps[OperIdx]*Ch<>[]) and
  1062. { The register doesn't get modified inside a reference }
  1063. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1064. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1065. begin
  1066. Result := true;
  1067. exit
  1068. end;
  1069. end;
  1070. end;
  1071. {$ifdef DEBUG_AOPTCPU}
  1072. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1073. begin
  1074. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1075. end;
  1076. function debug_tostr(i: tcgint): string; inline;
  1077. begin
  1078. Result := tostr(i);
  1079. end;
  1080. function debug_regname(r: TRegister): string; inline;
  1081. begin
  1082. Result := '%' + std_regname(r);
  1083. end;
  1084. { Debug output function - creates a string representation of an operator }
  1085. function debug_operstr(oper: TOper): string;
  1086. begin
  1087. case oper.typ of
  1088. top_const:
  1089. Result := '$' + debug_tostr(oper.val);
  1090. top_reg:
  1091. Result := debug_regname(oper.reg);
  1092. top_ref:
  1093. begin
  1094. if oper.ref^.offset <> 0 then
  1095. Result := debug_tostr(oper.ref^.offset) + '('
  1096. else
  1097. Result := '(';
  1098. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1099. begin
  1100. Result := Result + debug_regname(oper.ref^.base);
  1101. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1102. Result := Result + ',' + debug_regname(oper.ref^.index);
  1103. end
  1104. else
  1105. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1106. Result := Result + debug_regname(oper.ref^.index);
  1107. if (oper.ref^.scalefactor > 1) then
  1108. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1109. else
  1110. Result := Result + ')';
  1111. end;
  1112. else
  1113. Result := '[UNKNOWN]';
  1114. end;
  1115. end;
  1116. function debug_op2str(opcode: tasmop): string; inline;
  1117. begin
  1118. Result := std_op2str[opcode];
  1119. end;
  1120. function debug_opsize2str(opsize: topsize): string; inline;
  1121. begin
  1122. Result := gas_opsize2str[opsize];
  1123. end;
  1124. {$else DEBUG_AOPTCPU}
  1125. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1126. begin
  1127. end;
  1128. function debug_tostr(i: tcgint): string; inline;
  1129. begin
  1130. Result := '';
  1131. end;
  1132. function debug_regname(r: TRegister): string; inline;
  1133. begin
  1134. Result := '';
  1135. end;
  1136. function debug_operstr(oper: TOper): string; inline;
  1137. begin
  1138. Result := '';
  1139. end;
  1140. function debug_op2str(opcode: tasmop): string; inline;
  1141. begin
  1142. Result := '';
  1143. end;
  1144. function debug_opsize2str(opsize: topsize): string; inline;
  1145. begin
  1146. Result := '';
  1147. end;
  1148. {$endif DEBUG_AOPTCPU}
  1149. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1150. begin
  1151. {$ifdef x86_64}
  1152. { Always fine on x86-64 }
  1153. Result := True;
  1154. {$else x86_64}
  1155. Result :=
  1156. {$ifdef i8086}
  1157. (current_settings.cputype >= cpu_386) and
  1158. {$endif i8086}
  1159. (
  1160. { Always accept if optimising for size }
  1161. (cs_opt_size in current_settings.optimizerswitches) or
  1162. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1163. (current_settings.optimizecputype >= cpu_Pentium2)
  1164. );
  1165. {$endif x86_64}
  1166. end;
  1167. { Attempts to allocate a volatile integer register for use between p and hp,
  1168. using AUsedRegs for the current register usage information. Returns NR_NO
  1169. if no free register could be found }
  1170. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1171. var
  1172. RegSet: TCPURegisterSet;
  1173. CurrentSuperReg: Integer;
  1174. CurrentReg: TRegister;
  1175. Currentp: tai;
  1176. Breakout: Boolean;
  1177. begin
  1178. Result := NR_NO;
  1179. RegSet :=
  1180. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1181. current_procinfo.saved_regs_int;
  1182. for CurrentSuperReg in RegSet do
  1183. begin
  1184. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1185. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1186. {$if defined(i386) or defined(i8086)}
  1187. { If the target size is 8-bit, make sure we can actually encode it }
  1188. and (
  1189. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1190. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1191. )
  1192. {$endif i386 or i8086}
  1193. then
  1194. begin
  1195. Currentp := p;
  1196. Breakout := False;
  1197. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1198. begin
  1199. case Currentp.typ of
  1200. ait_instruction:
  1201. begin
  1202. if RegInInstruction(CurrentReg, Currentp) then
  1203. begin
  1204. Breakout := True;
  1205. Break;
  1206. end;
  1207. { Cannot allocate across an unconditional jump }
  1208. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1209. Exit;
  1210. end;
  1211. ait_marker:
  1212. { Don't try anything more if a marker is hit }
  1213. Exit;
  1214. ait_regalloc:
  1215. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1216. begin
  1217. Breakout := True;
  1218. Break;
  1219. end;
  1220. else
  1221. ;
  1222. end;
  1223. end;
  1224. if Breakout then
  1225. { Try the next register }
  1226. Continue;
  1227. { We have a free register available }
  1228. Result := CurrentReg;
  1229. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1230. Exit;
  1231. end;
  1232. end;
  1233. end;
  1234. { Attempts to allocate a volatile MM register for use between p and hp,
  1235. using AUsedRegs for the current register usage information. Returns NR_NO
  1236. if no free register could be found }
  1237. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1238. var
  1239. RegSet: TCPURegisterSet;
  1240. CurrentSuperReg: Integer;
  1241. CurrentReg: TRegister;
  1242. Currentp: tai;
  1243. Breakout: Boolean;
  1244. begin
  1245. Result := NR_NO;
  1246. RegSet :=
  1247. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1248. current_procinfo.saved_regs_mm;
  1249. for CurrentSuperReg in RegSet do
  1250. begin
  1251. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1252. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1253. begin
  1254. Currentp := p;
  1255. Breakout := False;
  1256. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1257. begin
  1258. case Currentp.typ of
  1259. ait_instruction:
  1260. begin
  1261. if RegInInstruction(CurrentReg, Currentp) then
  1262. begin
  1263. Breakout := True;
  1264. Break;
  1265. end;
  1266. { Cannot allocate across an unconditional jump }
  1267. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1268. Exit;
  1269. end;
  1270. ait_marker:
  1271. { Don't try anything more if a marker is hit }
  1272. Exit;
  1273. ait_regalloc:
  1274. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1275. begin
  1276. Breakout := True;
  1277. Break;
  1278. end;
  1279. else
  1280. ;
  1281. end;
  1282. end;
  1283. if Breakout then
  1284. { Try the next register }
  1285. Continue;
  1286. { We have a free register available }
  1287. Result := CurrentReg;
  1288. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1289. Exit;
  1290. end;
  1291. end;
  1292. end;
  1293. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1294. begin
  1295. if not SuperRegistersEqual(reg1,reg2) then
  1296. exit(false);
  1297. if getregtype(reg1)<>R_INTREGISTER then
  1298. exit(true); {because SuperRegisterEqual is true}
  1299. case getsubreg(reg1) of
  1300. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1301. higher, it preserves the high bits, so the new value depends on
  1302. reg2's previous value. In other words, it is equivalent to doing:
  1303. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1304. R_SUBL:
  1305. exit(getsubreg(reg2)=R_SUBL);
  1306. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1307. higher, it actually does a:
  1308. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1309. R_SUBH:
  1310. exit(getsubreg(reg2)=R_SUBH);
  1311. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1312. bits of reg2:
  1313. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1314. R_SUBW:
  1315. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1316. { a write to R_SUBD always overwrites every other subregister,
  1317. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1318. R_SUBD,
  1319. R_SUBQ:
  1320. exit(true);
  1321. else
  1322. internalerror(2017042801);
  1323. end;
  1324. end;
  1325. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1326. begin
  1327. if not SuperRegistersEqual(reg1,reg2) then
  1328. exit(false);
  1329. if getregtype(reg1)<>R_INTREGISTER then
  1330. exit(true); {because SuperRegisterEqual is true}
  1331. case getsubreg(reg1) of
  1332. R_SUBL:
  1333. exit(getsubreg(reg2)<>R_SUBH);
  1334. R_SUBH:
  1335. exit(getsubreg(reg2)<>R_SUBL);
  1336. R_SUBW,
  1337. R_SUBD,
  1338. R_SUBQ:
  1339. exit(true);
  1340. else
  1341. internalerror(2017042802);
  1342. end;
  1343. end;
  1344. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1345. var
  1346. hp1 : tai;
  1347. l : TCGInt;
  1348. begin
  1349. result:=false;
  1350. { changes the code sequence
  1351. shr/sar const1, x
  1352. shl const2, x
  1353. to
  1354. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1355. if GetNextInstruction(p, hp1) and
  1356. MatchInstruction(hp1,A_SHL,[]) and
  1357. (taicpu(p).oper[0]^.typ = top_const) and
  1358. (taicpu(hp1).oper[0]^.typ = top_const) and
  1359. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1360. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1361. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1362. begin
  1363. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1364. not(cs_opt_size in current_settings.optimizerswitches) then
  1365. begin
  1366. { shr/sar const1, %reg
  1367. shl const2, %reg
  1368. with const1 > const2 }
  1369. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1370. taicpu(hp1).opcode := A_AND;
  1371. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1372. case taicpu(p).opsize Of
  1373. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1374. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1375. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1376. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1377. else
  1378. Internalerror(2017050703)
  1379. end;
  1380. end
  1381. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1382. not(cs_opt_size in current_settings.optimizerswitches) then
  1383. begin
  1384. { shr/sar const1, %reg
  1385. shl const2, %reg
  1386. with const1 < const2 }
  1387. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1388. taicpu(p).opcode := A_AND;
  1389. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1390. case taicpu(p).opsize Of
  1391. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1392. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1393. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1394. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1395. else
  1396. Internalerror(2017050702)
  1397. end;
  1398. end
  1399. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1400. begin
  1401. { shr/sar const1, %reg
  1402. shl const2, %reg
  1403. with const1 = const2 }
  1404. taicpu(p).opcode := A_AND;
  1405. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1406. case taicpu(p).opsize Of
  1407. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1408. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1409. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1410. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1411. else
  1412. Internalerror(2017050701)
  1413. end;
  1414. RemoveInstruction(hp1);
  1415. end;
  1416. end;
  1417. end;
  1418. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1419. var
  1420. opsize : topsize;
  1421. hp1, hp2 : tai;
  1422. tmpref : treference;
  1423. ShiftValue : Cardinal;
  1424. BaseValue : TCGInt;
  1425. begin
  1426. result:=false;
  1427. opsize:=taicpu(p).opsize;
  1428. { changes certain "imul const, %reg"'s to lea sequences }
  1429. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1430. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1431. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1432. if (taicpu(p).oper[0]^.val = 1) then
  1433. if (taicpu(p).ops = 2) then
  1434. { remove "imul $1, reg" }
  1435. begin
  1436. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1437. Result := RemoveCurrentP(p);
  1438. end
  1439. else
  1440. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1441. begin
  1442. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1443. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1444. asml.InsertAfter(hp1, p);
  1445. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1446. RemoveCurrentP(p, hp1);
  1447. Result := True;
  1448. end
  1449. else if ((taicpu(p).ops <= 2) or
  1450. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1451. not(cs_opt_size in current_settings.optimizerswitches) and
  1452. (not(GetNextInstruction(p, hp1)) or
  1453. not((tai(hp1).typ = ait_instruction) and
  1454. ((taicpu(hp1).opcode=A_Jcc) and
  1455. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1456. begin
  1457. {
  1458. imul X, reg1, reg2 to
  1459. lea (reg1,reg1,Y), reg2
  1460. shl ZZ,reg2
  1461. imul XX, reg1 to
  1462. lea (reg1,reg1,YY), reg1
  1463. shl ZZ,reg2
  1464. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1465. it does not exist as a separate optimization target in FPC though.
  1466. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1467. at most two zeros
  1468. }
  1469. reference_reset(tmpref,1,[]);
  1470. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1471. begin
  1472. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1473. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1474. TmpRef.base := taicpu(p).oper[1]^.reg;
  1475. TmpRef.index := taicpu(p).oper[1]^.reg;
  1476. if not(BaseValue in [3,5,9]) then
  1477. Internalerror(2018110101);
  1478. TmpRef.ScaleFactor := BaseValue-1;
  1479. if (taicpu(p).ops = 2) then
  1480. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1481. else
  1482. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1483. AsmL.InsertAfter(hp1,p);
  1484. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1485. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1486. RemoveCurrentP(p, hp1);
  1487. if ShiftValue>0 then
  1488. begin
  1489. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1490. AsmL.InsertAfter(hp2,hp1);
  1491. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1492. end;
  1493. Result := True;
  1494. end;
  1495. end;
  1496. end;
  1497. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1498. begin
  1499. Result := False;
  1500. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1501. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1502. begin
  1503. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1504. taicpu(p).opcode := A_MOV;
  1505. Result := True;
  1506. end;
  1507. end;
  1508. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1509. var
  1510. p: taicpu absolute hp; { Implicit typecast }
  1511. i: Integer;
  1512. begin
  1513. Result := False;
  1514. if not assigned(hp) or
  1515. (hp.typ <> ait_instruction) then
  1516. Exit;
  1517. Prefetch(insprop[p.opcode]);
  1518. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1519. with insprop[p.opcode] do
  1520. begin
  1521. case getsubreg(reg) of
  1522. R_SUBW,R_SUBD,R_SUBQ:
  1523. Result:=
  1524. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1525. uncommon flags are checked first }
  1526. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1527. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1528. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1531. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1532. R_SUBFLAGCARRY:
  1533. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1534. R_SUBFLAGPARITY:
  1535. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1536. R_SUBFLAGAUXILIARY:
  1537. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1538. R_SUBFLAGZERO:
  1539. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1540. R_SUBFLAGSIGN:
  1541. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1542. R_SUBFLAGOVERFLOW:
  1543. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1544. R_SUBFLAGINTERRUPT:
  1545. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1546. R_SUBFLAGDIRECTION:
  1547. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1548. else
  1549. internalerror(2017050501);
  1550. end;
  1551. exit;
  1552. end;
  1553. { Handle special cases first }
  1554. case p.opcode of
  1555. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1556. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1557. begin
  1558. Result :=
  1559. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1560. (p.oper[1]^.typ = top_reg) and
  1561. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1562. (
  1563. (p.oper[0]^.typ = top_const) or
  1564. (
  1565. (p.oper[0]^.typ = top_reg) and
  1566. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1567. ) or (
  1568. (p.oper[0]^.typ = top_ref) and
  1569. not RegInRef(reg,p.oper[0]^.ref^)
  1570. )
  1571. );
  1572. end;
  1573. A_MUL, A_IMUL:
  1574. Result :=
  1575. (
  1576. (p.ops=3) and { IMUL only }
  1577. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1578. (
  1579. (
  1580. (p.oper[1]^.typ=top_reg) and
  1581. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1582. ) or (
  1583. (p.oper[1]^.typ=top_ref) and
  1584. not RegInRef(reg,p.oper[1]^.ref^)
  1585. )
  1586. )
  1587. ) or (
  1588. (
  1589. (p.ops=1) and
  1590. (
  1591. (
  1592. (
  1593. (p.oper[0]^.typ=top_reg) and
  1594. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1595. )
  1596. ) or (
  1597. (p.oper[0]^.typ=top_ref) and
  1598. not RegInRef(reg,p.oper[0]^.ref^)
  1599. )
  1600. ) and (
  1601. (
  1602. (p.opsize=S_B) and
  1603. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1604. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1605. ) or (
  1606. (p.opsize=S_W) and
  1607. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1608. ) or (
  1609. (p.opsize=S_L) and
  1610. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1611. {$ifdef x86_64}
  1612. ) or (
  1613. (p.opsize=S_Q) and
  1614. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1615. {$endif x86_64}
  1616. )
  1617. )
  1618. )
  1619. );
  1620. A_CBW:
  1621. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1622. {$ifndef x86_64}
  1623. A_LDS:
  1624. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1625. A_LES:
  1626. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1627. {$endif not x86_64}
  1628. A_LFS:
  1629. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1630. A_LGS:
  1631. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1632. A_LSS:
  1633. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1634. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1635. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1636. A_LODSB:
  1637. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1638. A_LODSW:
  1639. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1640. {$ifdef x86_64}
  1641. A_LODSQ:
  1642. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1643. {$endif x86_64}
  1644. A_LODSD:
  1645. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1646. A_FSTSW, A_FNSTSW:
  1647. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1648. else
  1649. begin
  1650. with insprop[p.opcode] do
  1651. begin
  1652. if (
  1653. { xor %reg,%reg etc. is classed as a new value }
  1654. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1655. MatchOpType(p, top_reg, top_reg) and
  1656. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1657. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1658. ) then
  1659. begin
  1660. Result := True;
  1661. Exit;
  1662. end;
  1663. { Make sure the entire register is overwritten }
  1664. if (getregtype(reg) = R_INTREGISTER) then
  1665. begin
  1666. if (p.ops > 0) then
  1667. begin
  1668. if RegInOp(reg, p.oper[0]^) then
  1669. begin
  1670. if (p.oper[0]^.typ = top_ref) then
  1671. begin
  1672. if RegInRef(reg, p.oper[0]^.ref^) then
  1673. begin
  1674. Result := False;
  1675. Exit;
  1676. end;
  1677. end
  1678. else if (p.oper[0]^.typ = top_reg) then
  1679. begin
  1680. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1681. begin
  1682. Result := False;
  1683. Exit;
  1684. end
  1685. else if ([Ch_WOp1]*Ch<>[]) then
  1686. begin
  1687. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1688. Result := True
  1689. else
  1690. begin
  1691. Result := False;
  1692. Exit;
  1693. end;
  1694. end;
  1695. end;
  1696. end;
  1697. if (p.ops > 1) then
  1698. begin
  1699. if RegInOp(reg, p.oper[1]^) then
  1700. begin
  1701. if (p.oper[1]^.typ = top_ref) then
  1702. begin
  1703. if RegInRef(reg, p.oper[1]^.ref^) then
  1704. begin
  1705. Result := False;
  1706. Exit;
  1707. end;
  1708. end
  1709. else if (p.oper[1]^.typ = top_reg) then
  1710. begin
  1711. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1712. begin
  1713. Result := False;
  1714. Exit;
  1715. end
  1716. else if ([Ch_WOp2]*Ch<>[]) then
  1717. begin
  1718. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1719. Result := True
  1720. else
  1721. begin
  1722. Result := False;
  1723. Exit;
  1724. end;
  1725. end;
  1726. end;
  1727. end;
  1728. if (p.ops > 2) then
  1729. begin
  1730. if RegInOp(reg, p.oper[2]^) then
  1731. begin
  1732. if (p.oper[2]^.typ = top_ref) then
  1733. begin
  1734. if RegInRef(reg, p.oper[2]^.ref^) then
  1735. begin
  1736. Result := False;
  1737. Exit;
  1738. end;
  1739. end
  1740. else if (p.oper[2]^.typ = top_reg) then
  1741. begin
  1742. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1743. begin
  1744. Result := False;
  1745. Exit;
  1746. end
  1747. else if ([Ch_WOp3]*Ch<>[]) then
  1748. begin
  1749. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1750. Result := True
  1751. else
  1752. begin
  1753. Result := False;
  1754. Exit;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1760. begin
  1761. if (p.oper[3]^.typ = top_ref) then
  1762. begin
  1763. if RegInRef(reg, p.oper[3]^.ref^) then
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end
  1769. else if (p.oper[3]^.typ = top_reg) then
  1770. begin
  1771. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1772. begin
  1773. Result := False;
  1774. Exit;
  1775. end
  1776. else if ([Ch_WOp4]*Ch<>[]) then
  1777. begin
  1778. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1779. Result := True
  1780. else
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. end;
  1791. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1792. case getsupreg(reg) of
  1793. RS_EAX:
  1794. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1795. begin
  1796. Result := True;
  1797. Exit;
  1798. end;
  1799. RS_ECX:
  1800. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1801. begin
  1802. Result := True;
  1803. Exit;
  1804. end;
  1805. RS_EDX:
  1806. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1807. begin
  1808. Result := True;
  1809. Exit;
  1810. end;
  1811. RS_EBX:
  1812. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1813. begin
  1814. Result := True;
  1815. Exit;
  1816. end;
  1817. RS_ESP:
  1818. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1819. begin
  1820. Result := True;
  1821. Exit;
  1822. end;
  1823. RS_EBP:
  1824. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1825. begin
  1826. Result := True;
  1827. Exit;
  1828. end;
  1829. RS_ESI:
  1830. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1831. begin
  1832. Result := True;
  1833. Exit;
  1834. end;
  1835. RS_EDI:
  1836. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1837. begin
  1838. Result := True;
  1839. Exit;
  1840. end;
  1841. else
  1842. ;
  1843. end;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1850. var
  1851. hp2,hp3 : tai;
  1852. begin
  1853. { some x86-64 issue a NOP before the real exit code }
  1854. if MatchInstruction(p,A_NOP,[]) then
  1855. GetNextInstruction(p,p);
  1856. result:=assigned(p) and (p.typ=ait_instruction) and
  1857. ((taicpu(p).opcode = A_RET) or
  1858. ((taicpu(p).opcode=A_LEAVE) and
  1859. GetNextInstruction(p,hp2) and
  1860. MatchInstruction(hp2,A_RET,[S_NO])
  1861. ) or
  1862. (((taicpu(p).opcode=A_LEA) and
  1863. MatchOpType(taicpu(p),top_ref,top_reg) and
  1864. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1865. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1866. ) and
  1867. GetNextInstruction(p,hp2) and
  1868. MatchInstruction(hp2,A_RET,[S_NO])
  1869. ) or
  1870. ((((taicpu(p).opcode=A_MOV) and
  1871. MatchOpType(taicpu(p),top_reg,top_reg) and
  1872. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1873. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1874. ((taicpu(p).opcode=A_LEA) and
  1875. MatchOpType(taicpu(p),top_ref,top_reg) and
  1876. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1877. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1878. )
  1879. ) and
  1880. GetNextInstruction(p,hp2) and
  1881. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1882. MatchOpType(taicpu(hp2),top_reg) and
  1883. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1884. GetNextInstruction(hp2,hp3) and
  1885. MatchInstruction(hp3,A_RET,[S_NO])
  1886. )
  1887. );
  1888. end;
  1889. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1890. begin
  1891. isFoldableArithOp := False;
  1892. case hp1.opcode of
  1893. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1894. isFoldableArithOp :=
  1895. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1896. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1897. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1898. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1899. (taicpu(hp1).oper[1]^.reg = reg);
  1900. A_INC,A_DEC,A_NEG,A_NOT:
  1901. isFoldableArithOp :=
  1902. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1903. (taicpu(hp1).oper[0]^.reg = reg);
  1904. else
  1905. ;
  1906. end;
  1907. end;
  1908. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1909. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1910. var
  1911. hp2: tai;
  1912. begin
  1913. hp2 := p;
  1914. repeat
  1915. hp2 := tai(hp2.previous);
  1916. if assigned(hp2) and
  1917. (hp2.typ = ait_regalloc) and
  1918. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1919. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1920. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1921. begin
  1922. RemoveInstruction(hp2);
  1923. break;
  1924. end;
  1925. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1926. end;
  1927. begin
  1928. case current_procinfo.procdef.returndef.typ of
  1929. arraydef,recorddef,pointerdef,
  1930. stringdef,enumdef,procdef,objectdef,errordef,
  1931. filedef,setdef,procvardef,
  1932. classrefdef,forwarddef:
  1933. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1934. orddef:
  1935. if current_procinfo.procdef.returndef.size <> 0 then
  1936. begin
  1937. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1938. { for int64/qword }
  1939. if current_procinfo.procdef.returndef.size = 8 then
  1940. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1941. end;
  1942. else
  1943. ;
  1944. end;
  1945. end;
  1946. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1947. var
  1948. hp1,hp2 : tai;
  1949. begin
  1950. result:=false;
  1951. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1952. begin
  1953. { vmova* reg1,reg1
  1954. =>
  1955. <nop> }
  1956. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1957. begin
  1958. RemoveCurrentP(p);
  1959. result:=true;
  1960. exit;
  1961. end
  1962. else if GetNextInstruction(p,hp1) then
  1963. begin
  1964. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1965. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1966. begin
  1967. { vmova* reg1,reg2
  1968. vmova* reg2,reg3
  1969. dealloc reg2
  1970. =>
  1971. vmova* reg1,reg3 }
  1972. TransferUsedRegs(TmpUsedRegs);
  1973. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1974. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1975. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1976. begin
  1977. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1978. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1979. RemoveInstruction(hp1);
  1980. result:=true;
  1981. exit;
  1982. end
  1983. { special case:
  1984. vmova* reg1,<op>
  1985. vmova* <op>,reg1
  1986. =>
  1987. vmova* reg1,<op> }
  1988. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1989. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1990. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1991. ) then
  1992. begin
  1993. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1994. RemoveInstruction(hp1);
  1995. result:=true;
  1996. exit;
  1997. end
  1998. end
  1999. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2000. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2001. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2002. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2003. ) and
  2004. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2005. begin
  2006. { vmova* reg1,reg2
  2007. vmovs* reg2,<op>
  2008. dealloc reg2
  2009. =>
  2010. vmovs* reg1,reg3 }
  2011. TransferUsedRegs(TmpUsedRegs);
  2012. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2013. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2014. begin
  2015. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2016. taicpu(p).opcode:=taicpu(hp1).opcode;
  2017. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2018. RemoveInstruction(hp1);
  2019. result:=true;
  2020. exit;
  2021. end
  2022. end;
  2023. end;
  2024. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2025. begin
  2026. if MatchInstruction(hp1,[A_VFMADDPD,
  2027. A_VFMADD132PD,
  2028. A_VFMADD132PS,
  2029. A_VFMADD132SD,
  2030. A_VFMADD132SS,
  2031. A_VFMADD213PD,
  2032. A_VFMADD213PS,
  2033. A_VFMADD213SD,
  2034. A_VFMADD213SS,
  2035. A_VFMADD231PD,
  2036. A_VFMADD231PS,
  2037. A_VFMADD231SD,
  2038. A_VFMADD231SS,
  2039. A_VFMADDSUB132PD,
  2040. A_VFMADDSUB132PS,
  2041. A_VFMADDSUB213PD,
  2042. A_VFMADDSUB213PS,
  2043. A_VFMADDSUB231PD,
  2044. A_VFMADDSUB231PS,
  2045. A_VFMSUB132PD,
  2046. A_VFMSUB132PS,
  2047. A_VFMSUB132SD,
  2048. A_VFMSUB132SS,
  2049. A_VFMSUB213PD,
  2050. A_VFMSUB213PS,
  2051. A_VFMSUB213SD,
  2052. A_VFMSUB213SS,
  2053. A_VFMSUB231PD,
  2054. A_VFMSUB231PS,
  2055. A_VFMSUB231SD,
  2056. A_VFMSUB231SS,
  2057. A_VFMSUBADD132PD,
  2058. A_VFMSUBADD132PS,
  2059. A_VFMSUBADD213PD,
  2060. A_VFMSUBADD213PS,
  2061. A_VFMSUBADD231PD,
  2062. A_VFMSUBADD231PS,
  2063. A_VFNMADD132PD,
  2064. A_VFNMADD132PS,
  2065. A_VFNMADD132SD,
  2066. A_VFNMADD132SS,
  2067. A_VFNMADD213PD,
  2068. A_VFNMADD213PS,
  2069. A_VFNMADD213SD,
  2070. A_VFNMADD213SS,
  2071. A_VFNMADD231PD,
  2072. A_VFNMADD231PS,
  2073. A_VFNMADD231SD,
  2074. A_VFNMADD231SS,
  2075. A_VFNMSUB132PD,
  2076. A_VFNMSUB132PS,
  2077. A_VFNMSUB132SD,
  2078. A_VFNMSUB132SS,
  2079. A_VFNMSUB213PD,
  2080. A_VFNMSUB213PS,
  2081. A_VFNMSUB213SD,
  2082. A_VFNMSUB213SS,
  2083. A_VFNMSUB231PD,
  2084. A_VFNMSUB231PS,
  2085. A_VFNMSUB231SD,
  2086. A_VFNMSUB231SS],[S_NO]) and
  2087. { we mix single and double opperations here because we assume that the compiler
  2088. generates vmovapd only after double operations and vmovaps only after single operations }
  2089. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2090. GetNextInstruction(hp1,hp2) and
  2091. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2092. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2093. begin
  2094. TransferUsedRegs(TmpUsedRegs);
  2095. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2096. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2097. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2098. begin
  2099. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2100. RemoveCurrentP(p);
  2101. RemoveInstruction(hp2);
  2102. end;
  2103. end
  2104. else if (hp1.typ = ait_instruction) and
  2105. GetNextInstruction(hp1, hp2) and
  2106. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2107. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2108. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2109. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2110. (((taicpu(p).opcode=A_MOVAPS) and
  2111. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2112. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2113. ((taicpu(p).opcode=A_MOVAPD) and
  2114. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2115. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2116. ) then
  2117. { change
  2118. movapX reg,reg2
  2119. addsX/subsX/... reg3, reg2
  2120. movapX reg2,reg
  2121. to
  2122. addsX/subsX/... reg3,reg
  2123. }
  2124. begin
  2125. TransferUsedRegs(TmpUsedRegs);
  2126. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2127. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+' '+
  2133. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2134. { we cannot eliminate the first move if
  2135. the operations uses the same register for source and dest }
  2136. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2137. { Remember that hp1 is not necessarily the immediate
  2138. next instruction }
  2139. RemoveCurrentP(p);
  2140. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2141. RemoveInstruction(hp2);
  2142. result:=true;
  2143. end;
  2144. end
  2145. else if (hp1.typ = ait_instruction) and
  2146. (((taicpu(p).opcode=A_VMOVAPD) and
  2147. (taicpu(hp1).opcode=A_VCOMISD)) or
  2148. ((taicpu(p).opcode=A_VMOVAPS) and
  2149. ((taicpu(hp1).opcode=A_VCOMISS))
  2150. )
  2151. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2152. { change
  2153. movapX reg,reg1
  2154. vcomisX reg1,reg1
  2155. to
  2156. vcomisX reg,reg
  2157. }
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2161. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2164. debug_op2str(taicpu(p).opcode)+' '+
  2165. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2166. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2167. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2168. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2169. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2170. RemoveCurrentP(p);
  2171. result:=true;
  2172. exit;
  2173. end;
  2174. end
  2175. end;
  2176. end;
  2177. end;
  2178. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2179. var
  2180. hp1 : tai;
  2181. begin
  2182. result:=false;
  2183. { replace
  2184. V<Op>X %mreg1,%mreg2,%mreg3
  2185. VMovX %mreg3,%mreg4
  2186. dealloc %mreg3
  2187. by
  2188. V<Op>X %mreg1,%mreg2,%mreg4
  2189. ?
  2190. }
  2191. if GetNextInstruction(p,hp1) and
  2192. { we mix single and double operations here because we assume that the compiler
  2193. generates vmovapd only after double operations and vmovaps only after single operations }
  2194. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2195. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2196. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2197. begin
  2198. TransferUsedRegs(TmpUsedRegs);
  2199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2200. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2201. begin
  2202. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2203. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2204. RemoveInstruction(hp1);
  2205. result:=true;
  2206. end;
  2207. end;
  2208. end;
  2209. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2210. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2211. begin
  2212. Result := False;
  2213. { For safety reasons, only check for exact register matches }
  2214. { Check base register }
  2215. if (ref.base = AOldReg) then
  2216. begin
  2217. ref.base := ANewReg;
  2218. Result := True;
  2219. end;
  2220. { Check index register }
  2221. if (ref.index = AOldReg) then
  2222. begin
  2223. ref.index := ANewReg;
  2224. Result := True;
  2225. end;
  2226. end;
  2227. { Replaces all references to AOldReg in an operand to ANewReg }
  2228. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2229. var
  2230. OldSupReg, NewSupReg: TSuperRegister;
  2231. OldSubReg, NewSubReg: TSubRegister;
  2232. OldRegType: TRegisterType;
  2233. ThisOper: POper;
  2234. begin
  2235. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2236. Result := False;
  2237. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2238. InternalError(2020011801);
  2239. OldSupReg := getsupreg(AOldReg);
  2240. OldSubReg := getsubreg(AOldReg);
  2241. OldRegType := getregtype(AOldReg);
  2242. NewSupReg := getsupreg(ANewReg);
  2243. NewSubReg := getsubreg(ANewReg);
  2244. if OldRegType <> getregtype(ANewReg) then
  2245. InternalError(2020011802);
  2246. if OldSubReg <> NewSubReg then
  2247. InternalError(2020011803);
  2248. case ThisOper^.typ of
  2249. top_reg:
  2250. if (
  2251. (ThisOper^.reg = AOldReg) or
  2252. (
  2253. (OldRegType = R_INTREGISTER) and
  2254. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2255. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2256. (
  2257. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2258. {$ifndef x86_64}
  2259. and (
  2260. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2261. don't have an 8-bit representation }
  2262. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2263. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2264. )
  2265. {$endif x86_64}
  2266. )
  2267. )
  2268. ) then
  2269. begin
  2270. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2271. Result := True;
  2272. end;
  2273. top_ref:
  2274. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2275. Result := True;
  2276. else
  2277. ;
  2278. end;
  2279. end;
  2280. { Replaces all references to AOldReg in an instruction to ANewReg }
  2281. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2282. const
  2283. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2284. var
  2285. OperIdx: Integer;
  2286. begin
  2287. Result := False;
  2288. for OperIdx := 0 to p.ops - 1 do
  2289. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2290. begin
  2291. { The shift and rotate instructions can only use CL }
  2292. if not (
  2293. (OperIdx = 0) and
  2294. { This second condition just helps to avoid unnecessarily
  2295. calling MatchInstruction for 10 different opcodes }
  2296. (p.oper[0]^.reg = NR_CL) and
  2297. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2298. ) then
  2299. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2300. end
  2301. else if p.oper[OperIdx]^.typ = top_ref then
  2302. { It's okay to replace registers in references that get written to }
  2303. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2304. end;
  2305. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2306. begin
  2307. with ref^ do
  2308. Result :=
  2309. (index = NR_NO) and
  2310. (
  2311. {$ifdef x86_64}
  2312. (
  2313. (base = NR_RIP) and
  2314. (refaddr in [addr_pic, addr_pic_no_got])
  2315. ) or
  2316. {$endif x86_64}
  2317. (base = NR_STACK_POINTER_REG) or
  2318. (base = current_procinfo.framepointer)
  2319. );
  2320. end;
  2321. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2322. var
  2323. l: asizeint;
  2324. begin
  2325. Result := False;
  2326. { Should have been checked previously }
  2327. if p.opcode <> A_LEA then
  2328. InternalError(2020072501);
  2329. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2330. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2331. not(cs_opt_size in current_settings.optimizerswitches) then
  2332. exit;
  2333. with p.oper[0]^.ref^ do
  2334. begin
  2335. if (base <> p.oper[1]^.reg) or
  2336. (index <> NR_NO) or
  2337. assigned(symbol) then
  2338. exit;
  2339. l:=offset;
  2340. if (l=1) and UseIncDec then
  2341. begin
  2342. p.opcode:=A_INC;
  2343. p.loadreg(0,p.oper[1]^.reg);
  2344. p.ops:=1;
  2345. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2346. end
  2347. else if (l=-1) and UseIncDec then
  2348. begin
  2349. p.opcode:=A_DEC;
  2350. p.loadreg(0,p.oper[1]^.reg);
  2351. p.ops:=1;
  2352. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2353. end
  2354. else
  2355. begin
  2356. if (l<0) and (l<>-2147483648) then
  2357. begin
  2358. p.opcode:=A_SUB;
  2359. p.loadConst(0,-l);
  2360. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2361. end
  2362. else
  2363. begin
  2364. p.opcode:=A_ADD;
  2365. p.loadConst(0,l);
  2366. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2367. end;
  2368. end;
  2369. end;
  2370. Result := True;
  2371. end;
  2372. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2373. var
  2374. CurrentReg, ReplaceReg: TRegister;
  2375. begin
  2376. Result := False;
  2377. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2378. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2379. case hp.opcode of
  2380. A_FSTSW, A_FNSTSW,
  2381. A_IN, A_INS, A_OUT, A_OUTS,
  2382. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2383. { These routines have explicit operands, but they are restricted in
  2384. what they can be (e.g. IN and OUT can only read from AL, AX or
  2385. EAX. }
  2386. Exit;
  2387. A_IMUL:
  2388. begin
  2389. { The 1-operand version writes to implicit registers
  2390. The 2-operand version reads from the first operator, and reads
  2391. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2392. the 3-operand version reads from a register that it doesn't write to
  2393. }
  2394. case hp.ops of
  2395. 1:
  2396. if (
  2397. (
  2398. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2399. ) or
  2400. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2401. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2402. begin
  2403. Result := True;
  2404. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2405. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2406. end;
  2407. 2:
  2408. { Only modify the first parameter }
  2409. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2410. begin
  2411. Result := True;
  2412. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2413. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2414. end;
  2415. 3:
  2416. { Only modify the second parameter }
  2417. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2418. begin
  2419. Result := True;
  2420. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2421. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2422. end;
  2423. else
  2424. InternalError(2020012901);
  2425. end;
  2426. end;
  2427. else
  2428. if (hp.ops > 0) and
  2429. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2430. begin
  2431. Result := True;
  2432. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2433. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2434. end;
  2435. end;
  2436. end;
  2437. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2438. var
  2439. hp2: tai;
  2440. p_SourceReg, p_TargetReg: TRegister;
  2441. begin
  2442. Result := False;
  2443. { Backward optimisation. If we have:
  2444. func. %reg1,%reg2
  2445. mov %reg2,%reg3
  2446. (dealloc %reg2)
  2447. Change to:
  2448. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2449. Perform similar optimisations with 1, 3 and 4-operand instructions
  2450. that only have one output.
  2451. }
  2452. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2453. begin
  2454. p_SourceReg := taicpu(p).oper[0]^.reg;
  2455. p_TargetReg := taicpu(p).oper[1]^.reg;
  2456. TransferUsedRegs(TmpUsedRegs);
  2457. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2458. GetLastInstruction(p, hp2) and
  2459. (hp2.typ = ait_instruction) and
  2460. { Have to make sure it's an instruction that only reads from
  2461. the first operands and only writes (not reads or modifies) to
  2462. the last one; in essence, a pure function such as BSR, POPCNT
  2463. or ANDN }
  2464. (
  2465. (
  2466. (taicpu(hp2).ops = 1) and
  2467. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2468. ) or
  2469. (
  2470. (taicpu(hp2).ops = 2) and
  2471. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2472. ) or
  2473. (
  2474. (taicpu(hp2).ops = 3) and
  2475. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2476. ) or
  2477. (
  2478. (taicpu(hp2).ops = 4) and
  2479. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2480. )
  2481. ) and
  2482. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2483. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2484. begin
  2485. case taicpu(hp2).opcode of
  2486. A_FSTSW, A_FNSTSW,
  2487. A_IN, A_INS, A_OUT, A_OUTS,
  2488. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2489. { These routines have explicit operands, but they are restricted in
  2490. what they can be (e.g. IN and OUT can only read from AL, AX or
  2491. EAX. }
  2492. ;
  2493. else
  2494. begin
  2495. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2496. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2497. if not RegInInstruction(p_TargetReg, hp2) then
  2498. begin
  2499. { Since we're allocating from an earlier point, we
  2500. need to remove the register from the tracking }
  2501. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2502. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2503. end;
  2504. RemoveCurrentp(p, hp1);
  2505. { If the Func was another MOV instruction, we might get
  2506. "mov %reg,%reg" that doesn't get removed in Pass 2
  2507. otherwise, so deal with it here (also do something
  2508. similar with lea (%reg),%reg}
  2509. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2510. begin
  2511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2512. if p = hp2 then
  2513. RemoveCurrentp(p)
  2514. else
  2515. RemoveInstruction(hp2);
  2516. end;
  2517. Result := True;
  2518. Exit;
  2519. end;
  2520. end;
  2521. end;
  2522. end;
  2523. end;
  2524. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2525. var
  2526. hp1, hp2, hp3: tai;
  2527. DoOptimisation, TempBool: Boolean;
  2528. {$ifdef x86_64}
  2529. NewConst: TCGInt;
  2530. {$endif x86_64}
  2531. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2532. begin
  2533. if taicpu(hp1).opcode = signed_movop then
  2534. begin
  2535. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2536. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2537. end
  2538. else
  2539. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2540. end;
  2541. function TryConstMerge(var p1, p2: tai): Boolean;
  2542. var
  2543. ThisRef: TReference;
  2544. begin
  2545. Result := False;
  2546. ThisRef := taicpu(p2).oper[1]^.ref^;
  2547. { Only permit writes to the stack, since we can guarantee alignment with that }
  2548. if (ThisRef.index = NR_NO) and
  2549. (
  2550. (ThisRef.base = NR_STACK_POINTER_REG) or
  2551. (ThisRef.base = current_procinfo.framepointer)
  2552. ) then
  2553. begin
  2554. case taicpu(p).opsize of
  2555. S_B:
  2556. begin
  2557. { Word writes must be on a 2-byte boundary }
  2558. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2559. begin
  2560. { Reduce offset of second reference to see if it is sequential with the first }
  2561. Dec(ThisRef.offset, 1);
  2562. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2563. begin
  2564. { Make sure the constants aren't represented as a
  2565. negative number, as these won't merge properly }
  2566. taicpu(p1).opsize := S_W;
  2567. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2568. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2569. RemoveInstruction(p2);
  2570. Result := True;
  2571. end;
  2572. end;
  2573. end;
  2574. S_W:
  2575. begin
  2576. { Longword writes must be on a 4-byte boundary }
  2577. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2578. begin
  2579. { Reduce offset of second reference to see if it is sequential with the first }
  2580. Dec(ThisRef.offset, 2);
  2581. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2582. begin
  2583. { Make sure the constants aren't represented as a
  2584. negative number, as these won't merge properly }
  2585. taicpu(p1).opsize := S_L;
  2586. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2587. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2588. RemoveInstruction(p2);
  2589. Result := True;
  2590. end;
  2591. end;
  2592. end;
  2593. {$ifdef x86_64}
  2594. S_L:
  2595. begin
  2596. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2597. see if the constants can be encoded this way. }
  2598. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2599. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2600. { Quadword writes must be on an 8-byte boundary }
  2601. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2602. begin
  2603. { Reduce offset of second reference to see if it is sequential with the first }
  2604. Dec(ThisRef.offset, 4);
  2605. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2606. begin
  2607. { Make sure the constants aren't represented as a
  2608. negative number, as these won't merge properly }
  2609. taicpu(p1).opsize := S_Q;
  2610. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2611. taicpu(p1).oper[0]^.val := NewConst;
  2612. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2613. RemoveInstruction(p2);
  2614. Result := True;
  2615. end;
  2616. end;
  2617. end;
  2618. {$endif x86_64}
  2619. else
  2620. ;
  2621. end;
  2622. end;
  2623. end;
  2624. var
  2625. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2626. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2627. NewSize: topsize; NewOffset: asizeint;
  2628. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2629. SourceRef, TargetRef: TReference;
  2630. MovAligned, MovUnaligned: TAsmOp;
  2631. ThisRef: TReference;
  2632. JumpTracking: TLinkedList;
  2633. begin
  2634. Result:=false;
  2635. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2636. { remove mov reg1,reg1? }
  2637. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2638. then
  2639. begin
  2640. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2641. { take care of the register (de)allocs following p }
  2642. RemoveCurrentP(p, hp1);
  2643. Result:=true;
  2644. exit;
  2645. end;
  2646. { All the next optimisations require a next instruction }
  2647. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2648. Exit;
  2649. { Prevent compiler warnings }
  2650. p_TargetReg := NR_NO;
  2651. if taicpu(p).oper[1]^.typ = top_reg then
  2652. begin
  2653. { Saves on a large number of dereferences }
  2654. p_TargetReg := taicpu(p).oper[1]^.reg;
  2655. { Look for:
  2656. mov %reg1,%reg2
  2657. ??? %reg2,r/m
  2658. Change to:
  2659. mov %reg1,%reg2
  2660. ??? %reg1,r/m
  2661. }
  2662. if taicpu(p).oper[0]^.typ = top_reg then
  2663. begin
  2664. if RegReadByInstruction(p_TargetReg, hp1) and
  2665. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2666. begin
  2667. { A change has occurred, just not in p }
  2668. Result := True;
  2669. TransferUsedRegs(TmpUsedRegs);
  2670. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2671. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2672. { Just in case something didn't get modified (e.g. an
  2673. implicit register) }
  2674. not RegReadByInstruction(p_TargetReg, hp1) then
  2675. begin
  2676. { We can remove the original MOV }
  2677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2678. RemoveCurrentp(p, hp1);
  2679. { UsedRegs got updated by RemoveCurrentp }
  2680. Result := True;
  2681. Exit;
  2682. end;
  2683. { If we know a MOV instruction has become a null operation, we might as well
  2684. get rid of it now to save time. }
  2685. if (taicpu(hp1).opcode = A_MOV) and
  2686. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2687. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2688. { Just being a register is enough to confirm it's a null operation }
  2689. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2690. begin
  2691. Result := True;
  2692. { Speed-up to reduce a pipeline stall... if we had something like...
  2693. movl %eax,%edx
  2694. movw %dx,%ax
  2695. ... the second instruction would change to movw %ax,%ax, but
  2696. given that it is now %ax that's active rather than %eax,
  2697. penalties might occur due to a partial register write, so instead,
  2698. change it to a MOVZX instruction when optimising for speed.
  2699. }
  2700. if not (cs_opt_size in current_settings.optimizerswitches) and
  2701. IsMOVZXAcceptable and
  2702. (taicpu(hp1).opsize < taicpu(p).opsize)
  2703. {$ifdef x86_64}
  2704. { operations already implicitly set the upper 64 bits to zero }
  2705. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2706. {$endif x86_64}
  2707. then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2710. case taicpu(p).opsize of
  2711. S_W:
  2712. if taicpu(hp1).opsize = S_B then
  2713. taicpu(hp1).opsize := S_BL
  2714. else
  2715. InternalError(2020012911);
  2716. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2717. case taicpu(hp1).opsize of
  2718. S_B:
  2719. taicpu(hp1).opsize := S_BL;
  2720. S_W:
  2721. taicpu(hp1).opsize := S_WL;
  2722. else
  2723. InternalError(2020012912);
  2724. end;
  2725. else
  2726. InternalError(2020012910);
  2727. end;
  2728. taicpu(hp1).opcode := A_MOVZX;
  2729. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2730. end
  2731. else
  2732. begin
  2733. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2734. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2735. RemoveInstruction(hp1);
  2736. { The instruction after what was hp1 is now the immediate next instruction,
  2737. so we can continue to make optimisations if it's present }
  2738. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2739. Exit;
  2740. hp1 := hp2;
  2741. end;
  2742. end;
  2743. end;
  2744. end;
  2745. end;
  2746. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2747. overwrites the original destination register. e.g.
  2748. movl ###,%reg2d
  2749. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2750. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2751. }
  2752. if (taicpu(p).oper[1]^.typ = top_reg) and
  2753. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2754. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2755. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2756. begin
  2757. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2758. begin
  2759. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2760. case taicpu(p).oper[0]^.typ of
  2761. top_const:
  2762. { We have something like:
  2763. movb $x, %regb
  2764. movzbl %regb,%regd
  2765. Change to:
  2766. movl $x, %regd
  2767. }
  2768. begin
  2769. case taicpu(hp1).opsize of
  2770. S_BW:
  2771. begin
  2772. convert_mov_value(A_MOVSX, $FF);
  2773. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2774. taicpu(p).opsize := S_W;
  2775. end;
  2776. S_BL:
  2777. begin
  2778. convert_mov_value(A_MOVSX, $FF);
  2779. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2780. taicpu(p).opsize := S_L;
  2781. end;
  2782. S_WL:
  2783. begin
  2784. convert_mov_value(A_MOVSX, $FFFF);
  2785. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2786. taicpu(p).opsize := S_L;
  2787. end;
  2788. {$ifdef x86_64}
  2789. S_BQ:
  2790. begin
  2791. convert_mov_value(A_MOVSX, $FF);
  2792. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2793. taicpu(p).opsize := S_Q;
  2794. end;
  2795. S_WQ:
  2796. begin
  2797. convert_mov_value(A_MOVSX, $FFFF);
  2798. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2799. taicpu(p).opsize := S_Q;
  2800. end;
  2801. S_LQ:
  2802. begin
  2803. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2804. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2805. taicpu(p).opsize := S_Q;
  2806. end;
  2807. {$endif x86_64}
  2808. else
  2809. { If hp1 was a MOV instruction, it should have been
  2810. optimised already }
  2811. InternalError(2020021001);
  2812. end;
  2813. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2814. RemoveInstruction(hp1);
  2815. Result := True;
  2816. Exit;
  2817. end;
  2818. top_ref:
  2819. begin
  2820. { We have something like:
  2821. movb mem, %regb
  2822. movzbl %regb,%regd
  2823. Change to:
  2824. movzbl mem, %regd
  2825. }
  2826. ThisRef := taicpu(p).oper[0]^.ref^;
  2827. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2828. begin
  2829. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2830. taicpu(hp1).loadref(0, ThisRef);
  2831. { Make sure any registers in the references are properly tracked }
  2832. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2833. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2834. if (ThisRef.index <> NR_NO) then
  2835. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2836. RemoveCurrentP(p, hp1);
  2837. Result := True;
  2838. Exit;
  2839. end;
  2840. end;
  2841. else
  2842. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2843. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2844. Exit;
  2845. end;
  2846. end
  2847. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2848. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2849. optimised }
  2850. else
  2851. begin
  2852. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2853. RemoveCurrentP(p, hp1);
  2854. Result := True;
  2855. Exit;
  2856. end;
  2857. end;
  2858. if (taicpu(hp1).opcode = A_AND) and
  2859. (taicpu(p).oper[1]^.typ = top_reg) and
  2860. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2861. begin
  2862. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2863. begin
  2864. case taicpu(p).opsize of
  2865. S_L:
  2866. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2867. begin
  2868. { Optimize out:
  2869. mov x, %reg
  2870. and ffffffffh, %reg
  2871. }
  2872. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2873. RemoveInstruction(hp1);
  2874. Result:=true;
  2875. exit;
  2876. end;
  2877. S_Q: { TODO: Confirm if this is even possible }
  2878. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2879. begin
  2880. { Optimize out:
  2881. mov x, %reg
  2882. and ffffffffffffffffh, %reg
  2883. }
  2884. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2885. RemoveInstruction(hp1);
  2886. Result:=true;
  2887. exit;
  2888. end;
  2889. else
  2890. ;
  2891. end;
  2892. if (
  2893. (taicpu(p).oper[0]^.typ=top_reg) or
  2894. (
  2895. (taicpu(p).oper[0]^.typ=top_ref) and
  2896. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2897. )
  2898. ) and
  2899. GetNextInstruction(hp1,hp2) and
  2900. MatchInstruction(hp2,A_TEST,[]) and
  2901. (
  2902. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2903. (
  2904. { If the register being tested is smaller than the one
  2905. that received a bitwise AND, permit it if the constant
  2906. fits into the smaller size }
  2907. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2908. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2909. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2910. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2911. (
  2912. (
  2913. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2914. (taicpu(hp1).oper[0]^.val <= $FF)
  2915. ) or
  2916. (
  2917. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2918. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2919. {$ifdef x86_64}
  2920. ) or
  2921. (
  2922. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2923. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2924. {$endif x86_64}
  2925. )
  2926. )
  2927. )
  2928. ) and
  2929. (
  2930. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2931. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2932. ) and
  2933. GetNextInstruction(hp2,hp3) and
  2934. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2935. (taicpu(hp3).condition in [C_E,C_NE]) then
  2936. begin
  2937. TransferUsedRegs(TmpUsedRegs);
  2938. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2939. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2940. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2941. begin
  2942. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2943. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2944. taicpu(hp1).opcode:=A_TEST;
  2945. { Shrink the TEST instruction down to the smallest possible size }
  2946. case taicpu(hp1).oper[0]^.val of
  2947. 0..255:
  2948. if (taicpu(hp1).opsize <> S_B)
  2949. {$ifndef x86_64}
  2950. and (
  2951. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2952. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2953. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2954. )
  2955. {$endif x86_64}
  2956. then
  2957. begin
  2958. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2959. { Only print debug message if the TEST instruction
  2960. is a different size before and after }
  2961. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2962. taicpu(hp1).opsize := S_B;
  2963. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2965. end;
  2966. 256..65535:
  2967. if (taicpu(hp1).opsize <> S_W) then
  2968. begin
  2969. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2970. { Only print debug message if the TEST instruction
  2971. is a different size before and after }
  2972. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2973. taicpu(hp1).opsize := S_W;
  2974. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2975. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2976. end;
  2977. {$ifdef x86_64}
  2978. 65536..$7FFFFFFF:
  2979. if (taicpu(hp1).opsize <> S_L) then
  2980. begin
  2981. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2982. { Only print debug message if the TEST instruction
  2983. is a different size before and after }
  2984. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2985. taicpu(hp1).opsize := S_L;
  2986. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2987. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2988. end;
  2989. {$endif x86_64}
  2990. else
  2991. ;
  2992. end;
  2993. RemoveInstruction(hp2);
  2994. RemoveCurrentP(p, hp1);
  2995. Result:=true;
  2996. exit;
  2997. end;
  2998. end;
  2999. end
  3000. else if IsMOVZXAcceptable and
  3001. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3002. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3003. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3004. then
  3005. begin
  3006. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3007. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3008. case taicpu(p).opsize of
  3009. S_B:
  3010. if (taicpu(hp1).oper[0]^.val = $ff) then
  3011. begin
  3012. { Convert:
  3013. movb x, %regl movb x, %regl
  3014. andw ffh, %regw andl ffh, %regd
  3015. To:
  3016. movzbw x, %regd movzbl x, %regd
  3017. (Identical registers, just different sizes)
  3018. }
  3019. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3020. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3021. case taicpu(hp1).opsize of
  3022. S_W: NewSize := S_BW;
  3023. S_L: NewSize := S_BL;
  3024. {$ifdef x86_64}
  3025. S_Q: NewSize := S_BQ;
  3026. {$endif x86_64}
  3027. else
  3028. InternalError(2018011510);
  3029. end;
  3030. end
  3031. else
  3032. NewSize := S_NO;
  3033. S_W:
  3034. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3035. begin
  3036. { Convert:
  3037. movw x, %regw
  3038. andl ffffh, %regd
  3039. To:
  3040. movzwl x, %regd
  3041. (Identical registers, just different sizes)
  3042. }
  3043. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3044. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3045. case taicpu(hp1).opsize of
  3046. S_L: NewSize := S_WL;
  3047. {$ifdef x86_64}
  3048. S_Q: NewSize := S_WQ;
  3049. {$endif x86_64}
  3050. else
  3051. InternalError(2018011511);
  3052. end;
  3053. end
  3054. else
  3055. NewSize := S_NO;
  3056. else
  3057. NewSize := S_NO;
  3058. end;
  3059. if NewSize <> S_NO then
  3060. begin
  3061. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3062. { The actual optimization }
  3063. taicpu(p).opcode := A_MOVZX;
  3064. taicpu(p).changeopsize(NewSize);
  3065. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3066. { Safeguard if "and" is followed by a conditional command }
  3067. TransferUsedRegs(TmpUsedRegs);
  3068. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3069. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3070. begin
  3071. { At this point, the "and" command is effectively equivalent to
  3072. "test %reg,%reg". This will be handled separately by the
  3073. Peephole Optimizer. [Kit] }
  3074. DebugMsg(SPeepholeOptimization + PreMessage +
  3075. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3076. end
  3077. else
  3078. begin
  3079. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3080. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3081. RemoveInstruction(hp1);
  3082. end;
  3083. Result := True;
  3084. Exit;
  3085. end;
  3086. end;
  3087. end;
  3088. if (taicpu(hp1).opcode = A_OR) and
  3089. (taicpu(p).oper[1]^.typ = top_reg) and
  3090. MatchOperand(taicpu(p).oper[0]^, 0) and
  3091. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3092. begin
  3093. { mov 0, %reg
  3094. or ###,%reg
  3095. Change to (only if the flags are not used):
  3096. mov ###,%reg
  3097. }
  3098. TransferUsedRegs(TmpUsedRegs);
  3099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3100. DoOptimisation := True;
  3101. { Even if the flags are used, we might be able to do the optimisation
  3102. if the conditions are predictable }
  3103. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3104. begin
  3105. { Only perform if ### = %reg (the same register) or equal to 0,
  3106. so %reg is guaranteed to still have a value of zero }
  3107. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3108. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3109. begin
  3110. hp2 := hp1;
  3111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3112. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3113. GetNextInstruction(hp2, hp3) do
  3114. begin
  3115. { Don't continue modifying if the flags state is getting changed }
  3116. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3117. Break;
  3118. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3119. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3120. begin
  3121. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3122. begin
  3123. { Condition is always true }
  3124. case taicpu(hp3).opcode of
  3125. A_Jcc:
  3126. begin
  3127. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3128. { Check for jump shortcuts before we destroy the condition }
  3129. DoJumpOptimizations(hp3, TempBool);
  3130. MakeUnconditional(taicpu(hp3));
  3131. Result := True;
  3132. end;
  3133. A_CMOVcc:
  3134. begin
  3135. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3136. taicpu(hp3).opcode := A_MOV;
  3137. taicpu(hp3).condition := C_None;
  3138. Result := True;
  3139. end;
  3140. A_SETcc:
  3141. begin
  3142. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3143. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3144. taicpu(hp3).opcode := A_MOV;
  3145. taicpu(hp3).ops := 2;
  3146. taicpu(hp3).condition := C_None;
  3147. taicpu(hp3).opsize := S_B;
  3148. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3149. taicpu(hp3).loadconst(0, 1);
  3150. Result := True;
  3151. end;
  3152. else
  3153. InternalError(2021090701);
  3154. end;
  3155. end
  3156. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3157. begin
  3158. { Condition is always false }
  3159. case taicpu(hp3).opcode of
  3160. A_Jcc:
  3161. begin
  3162. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3163. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3164. RemoveInstruction(hp3);
  3165. Result := True;
  3166. { Since hp3 was deleted, hp2 must not be updated }
  3167. Continue;
  3168. end;
  3169. A_CMOVcc:
  3170. begin
  3171. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3172. RemoveInstruction(hp3);
  3173. Result := True;
  3174. { Since hp3 was deleted, hp2 must not be updated }
  3175. Continue;
  3176. end;
  3177. A_SETcc:
  3178. begin
  3179. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3180. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3181. taicpu(hp3).opcode := A_MOV;
  3182. taicpu(hp3).ops := 2;
  3183. taicpu(hp3).condition := C_None;
  3184. taicpu(hp3).opsize := S_B;
  3185. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3186. taicpu(hp3).loadconst(0, 0);
  3187. Result := True;
  3188. end;
  3189. else
  3190. InternalError(2021090702);
  3191. end;
  3192. end
  3193. else
  3194. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3195. DoOptimisation := False;
  3196. end;
  3197. hp2 := hp3;
  3198. end;
  3199. { Flags are still in use - don't optimise }
  3200. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3201. DoOptimisation := False;
  3202. end
  3203. else
  3204. DoOptimisation := False;
  3205. end;
  3206. if DoOptimisation then
  3207. begin
  3208. {$ifdef x86_64}
  3209. { OR only supports 32-bit sign-extended constants for 64-bit
  3210. instructions, so compensate for this if the constant is
  3211. encoded as a value greater than or equal to 2^31 }
  3212. if (taicpu(hp1).opsize = S_Q) and
  3213. (taicpu(hp1).oper[0]^.typ = top_const) and
  3214. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3215. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3216. {$endif x86_64}
  3217. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3218. taicpu(hp1).opcode := A_MOV;
  3219. RemoveCurrentP(p, hp1);
  3220. Result := True;
  3221. Exit;
  3222. end;
  3223. end;
  3224. { Next instruction is also a MOV ? }
  3225. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3226. begin
  3227. if MatchOpType(taicpu(p), top_const, top_ref) and
  3228. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3229. TryConstMerge(p, hp1) then
  3230. begin
  3231. Result := True;
  3232. { In case we have four byte writes in a row, check for 2 more
  3233. right now so we don't have to wait for another iteration of
  3234. pass 1
  3235. }
  3236. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3237. case taicpu(p).opsize of
  3238. S_W:
  3239. begin
  3240. if GetNextInstruction(p, hp1) and
  3241. MatchInstruction(hp1, A_MOV, [S_B]) and
  3242. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3243. GetNextInstruction(hp1, hp2) and
  3244. MatchInstruction(hp2, A_MOV, [S_B]) and
  3245. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3246. { Try to merge the two bytes }
  3247. TryConstMerge(hp1, hp2) then
  3248. { Now try to merge the two words (hp2 will get deleted) }
  3249. TryConstMerge(p, hp1);
  3250. end;
  3251. S_L:
  3252. begin
  3253. { Though this only really benefits x86_64 and not i386, it
  3254. gets a potential optimisation done faster and hence
  3255. reduces the number of times OptPass1MOV is entered }
  3256. if GetNextInstruction(p, hp1) and
  3257. MatchInstruction(hp1, A_MOV, [S_W]) and
  3258. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3259. GetNextInstruction(hp1, hp2) and
  3260. MatchInstruction(hp2, A_MOV, [S_W]) and
  3261. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3262. { Try to merge the two words }
  3263. TryConstMerge(hp1, hp2) then
  3264. { This will always fail on i386, so don't bother
  3265. calling it unless we're doing x86_64 }
  3266. {$ifdef x86_64}
  3267. { Now try to merge the two longwords (hp2 will get deleted) }
  3268. TryConstMerge(p, hp1)
  3269. {$endif x86_64}
  3270. ;
  3271. end;
  3272. else
  3273. ;
  3274. end;
  3275. Exit;
  3276. end;
  3277. if (taicpu(p).oper[1]^.typ = top_reg) and
  3278. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3279. begin
  3280. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3281. TransferUsedRegs(TmpUsedRegs);
  3282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3283. { we have
  3284. mov x, %treg
  3285. mov %treg, y
  3286. }
  3287. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3288. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3289. { we've got
  3290. mov x, %treg
  3291. mov %treg, y
  3292. with %treg is not used after }
  3293. case taicpu(p).oper[0]^.typ Of
  3294. { top_reg is covered by DeepMOVOpt }
  3295. top_const:
  3296. begin
  3297. { change
  3298. mov const, %treg
  3299. mov %treg, y
  3300. to
  3301. mov const, y
  3302. }
  3303. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3304. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3305. begin
  3306. if taicpu(hp1).oper[1]^.typ=top_reg then
  3307. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3308. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3309. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3310. RemoveInstruction(hp1);
  3311. Result:=true;
  3312. Exit;
  3313. end;
  3314. end;
  3315. top_ref:
  3316. case taicpu(hp1).oper[1]^.typ of
  3317. top_reg:
  3318. begin
  3319. { change
  3320. mov mem, %treg
  3321. mov %treg, %reg
  3322. to
  3323. mov mem, %reg"
  3324. }
  3325. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3326. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3327. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3328. RemoveInstruction(hp1);
  3329. Result:=true;
  3330. Exit;
  3331. end;
  3332. top_ref:
  3333. begin
  3334. {$ifdef x86_64}
  3335. { Look for the following to simplify:
  3336. mov x(mem1), %reg
  3337. mov %reg, y(mem2)
  3338. mov x+8(mem1), %reg
  3339. mov %reg, y+8(mem2)
  3340. Change to:
  3341. movdqu x(mem1), %xmmreg
  3342. movdqu %xmmreg, y(mem2)
  3343. ...but only as long as the memory blocks don't overlap
  3344. }
  3345. SourceRef := taicpu(p).oper[0]^.ref^;
  3346. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3347. if (taicpu(p).opsize = S_Q) and
  3348. GetNextInstruction(hp1, hp2) and
  3349. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3350. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3351. begin
  3352. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3353. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3354. Inc(SourceRef.offset, 8);
  3355. if UseAVX then
  3356. begin
  3357. MovAligned := A_VMOVDQA;
  3358. MovUnaligned := A_VMOVDQU;
  3359. end
  3360. else
  3361. begin
  3362. MovAligned := A_MOVDQA;
  3363. MovUnaligned := A_MOVDQU;
  3364. end;
  3365. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3366. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3367. begin
  3368. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3369. Inc(TargetRef.offset, 8);
  3370. if GetNextInstruction(hp2, hp3) and
  3371. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3372. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3373. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3374. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3375. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3376. begin
  3377. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3378. if NewMMReg <> NR_NO then
  3379. begin
  3380. { Remember that the offsets are 8 ahead }
  3381. if ((SourceRef.offset mod 16) = 8) and
  3382. (
  3383. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3384. (SourceRef.base = current_procinfo.framepointer) or
  3385. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3386. ) then
  3387. taicpu(p).opcode := MovAligned
  3388. else
  3389. taicpu(p).opcode := MovUnaligned;
  3390. taicpu(p).opsize := S_XMM;
  3391. taicpu(p).oper[1]^.reg := NewMMReg;
  3392. if ((TargetRef.offset mod 16) = 8) and
  3393. (
  3394. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3395. (TargetRef.base = current_procinfo.framepointer) or
  3396. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3397. ) then
  3398. taicpu(hp1).opcode := MovAligned
  3399. else
  3400. taicpu(hp1).opcode := MovUnaligned;
  3401. taicpu(hp1).opsize := S_XMM;
  3402. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3403. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3404. RemoveInstruction(hp2);
  3405. RemoveInstruction(hp3);
  3406. Result := True;
  3407. Exit;
  3408. end;
  3409. end;
  3410. end
  3411. else
  3412. begin
  3413. { See if the next references are 8 less rather than 8 greater }
  3414. Dec(SourceRef.offset, 16); { -8 the other way }
  3415. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3416. begin
  3417. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3418. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3419. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3420. GetNextInstruction(hp2, hp3) and
  3421. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3422. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3423. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3424. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3425. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3426. begin
  3427. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3428. if NewMMReg <> NR_NO then
  3429. begin
  3430. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3431. if ((SourceRef.offset mod 16) = 0) and
  3432. (
  3433. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3434. (SourceRef.base = current_procinfo.framepointer) or
  3435. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3436. ) then
  3437. taicpu(hp2).opcode := MovAligned
  3438. else
  3439. taicpu(hp2).opcode := MovUnaligned;
  3440. taicpu(hp2).opsize := S_XMM;
  3441. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3442. if ((TargetRef.offset mod 16) = 0) and
  3443. (
  3444. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3445. (TargetRef.base = current_procinfo.framepointer) or
  3446. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3447. ) then
  3448. taicpu(hp3).opcode := MovAligned
  3449. else
  3450. taicpu(hp3).opcode := MovUnaligned;
  3451. taicpu(hp3).opsize := S_XMM;
  3452. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3453. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3454. RemoveInstruction(hp1);
  3455. RemoveCurrentP(p, hp2);
  3456. Result := True;
  3457. Exit;
  3458. end;
  3459. end;
  3460. end;
  3461. end;
  3462. end;
  3463. {$endif x86_64}
  3464. end;
  3465. else
  3466. { The write target should be a reg or a ref }
  3467. InternalError(2021091601);
  3468. end;
  3469. else
  3470. ;
  3471. end
  3472. else
  3473. { %treg is used afterwards, but all eventualities
  3474. other than the first MOV instruction being a constant
  3475. are covered by DeepMOVOpt, so only check for that }
  3476. if (taicpu(p).oper[0]^.typ = top_const) and
  3477. (
  3478. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3479. not (cs_opt_size in current_settings.optimizerswitches) or
  3480. (taicpu(hp1).opsize = S_B)
  3481. ) and
  3482. (
  3483. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3484. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3485. ) then
  3486. begin
  3487. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3488. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3489. end;
  3490. end;
  3491. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3492. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3493. { mov reg1, mem1 or mov mem1, reg1
  3494. mov mem2, reg2 mov reg2, mem2}
  3495. begin
  3496. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3497. { mov reg1, mem1 or mov mem1, reg1
  3498. mov mem2, reg1 mov reg2, mem1}
  3499. begin
  3500. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3501. { Removes the second statement from
  3502. mov reg1, mem1/reg2
  3503. mov mem1/reg2, reg1 }
  3504. begin
  3505. if taicpu(p).oper[0]^.typ=top_reg then
  3506. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3507. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3508. RemoveInstruction(hp1);
  3509. Result:=true;
  3510. exit;
  3511. end
  3512. else
  3513. begin
  3514. TransferUsedRegs(TmpUsedRegs);
  3515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3516. if (taicpu(p).oper[1]^.typ = top_ref) and
  3517. { mov reg1, mem1
  3518. mov mem2, reg1 }
  3519. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3520. GetNextInstruction(hp1, hp2) and
  3521. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3522. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3523. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3524. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3525. { change to
  3526. mov reg1, mem1 mov reg1, mem1
  3527. mov mem2, reg1 cmp reg1, mem2
  3528. cmp mem1, reg1
  3529. }
  3530. begin
  3531. RemoveInstruction(hp2);
  3532. taicpu(hp1).opcode := A_CMP;
  3533. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3534. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3535. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3536. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3537. end;
  3538. end;
  3539. end
  3540. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3541. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3542. begin
  3543. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3544. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3545. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3546. end
  3547. else
  3548. begin
  3549. TransferUsedRegs(TmpUsedRegs);
  3550. if GetNextInstruction(hp1, hp2) and
  3551. MatchOpType(taicpu(p),top_ref,top_reg) and
  3552. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3553. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3554. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3555. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3556. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3557. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3558. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3559. { mov mem1, %reg1
  3560. mov %reg1, mem2
  3561. mov mem2, reg2
  3562. to:
  3563. mov mem1, reg2
  3564. mov reg2, mem2}
  3565. begin
  3566. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3567. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3568. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3569. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3570. RemoveInstruction(hp2);
  3571. Result := True;
  3572. end
  3573. {$ifdef i386}
  3574. { this is enabled for i386 only, as the rules to create the reg sets below
  3575. are too complicated for x86-64, so this makes this code too error prone
  3576. on x86-64
  3577. }
  3578. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3579. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3580. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3581. { mov mem1, reg1 mov mem1, reg1
  3582. mov reg1, mem2 mov reg1, mem2
  3583. mov mem2, reg2 mov mem2, reg1
  3584. to: to:
  3585. mov mem1, reg1 mov mem1, reg1
  3586. mov mem1, reg2 mov reg1, mem2
  3587. mov reg1, mem2
  3588. or (if mem1 depends on reg1
  3589. and/or if mem2 depends on reg2)
  3590. to:
  3591. mov mem1, reg1
  3592. mov reg1, mem2
  3593. mov reg1, reg2
  3594. }
  3595. begin
  3596. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3597. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3598. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3599. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3600. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3601. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3602. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3603. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3604. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3605. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3606. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3607. end
  3608. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3609. begin
  3610. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3611. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3612. end
  3613. else
  3614. begin
  3615. RemoveInstruction(hp2);
  3616. end
  3617. {$endif i386}
  3618. ;
  3619. end;
  3620. end
  3621. { movl [mem1],reg1
  3622. movl [mem1],reg2
  3623. to
  3624. movl [mem1],reg1
  3625. movl reg1,reg2
  3626. }
  3627. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3628. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3629. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3630. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3631. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3632. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3633. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3634. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3635. begin
  3636. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3637. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3638. end;
  3639. { movl const1,[mem1]
  3640. movl [mem1],reg1
  3641. to
  3642. movl const1,reg1
  3643. movl reg1,[mem1]
  3644. }
  3645. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3646. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3647. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3648. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3649. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3650. begin
  3651. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3652. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3653. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3654. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3655. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3656. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3657. Result:=true;
  3658. exit;
  3659. end;
  3660. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3661. { Change:
  3662. movl %reg1,%reg2
  3663. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3664. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3665. To:
  3666. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3667. movl x(%reg1),%reg1
  3668. movl %reg1,%regX
  3669. }
  3670. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3671. begin
  3672. p_SourceReg := taicpu(p).oper[0]^.reg;
  3673. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3674. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3675. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3676. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3679. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3680. begin
  3681. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3682. if RegInRef(p_TargetReg, SourceRef) and
  3683. { If %reg1 also appears in the second reference, then it will
  3684. not refer to the same memory block as the first reference }
  3685. not RegInRef(p_SourceReg, SourceRef) then
  3686. begin
  3687. { Check to see if the references match if %reg2 is changed to %reg1 }
  3688. if SourceRef.base = p_TargetReg then
  3689. SourceRef.base := p_SourceReg;
  3690. if SourceRef.index = p_TargetReg then
  3691. SourceRef.index := p_SourceReg;
  3692. { RefsEqual also checks to ensure both references are non-volatile }
  3693. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3694. begin
  3695. taicpu(hp2).loadreg(0, p_SourceReg);
  3696. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3697. Result := True;
  3698. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3701. RemoveCurrentP(p, hp1);
  3702. Exit;
  3703. end
  3704. else
  3705. begin
  3706. { Check to see if %reg2 is no longer in use }
  3707. TransferUsedRegs(TmpUsedRegs);
  3708. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3709. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3710. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3711. begin
  3712. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3713. RemoveCurrentP(p, hp1);
  3714. Exit;
  3715. end;
  3716. end;
  3717. { If we reach this point, p and hp1 weren't actually modified,
  3718. so we can do a bit more work on this pass }
  3719. end;
  3720. end;
  3721. end;
  3722. end;
  3723. end;
  3724. { search further than the next instruction for a mov (as long as it's not a jump) }
  3725. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3726. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3727. (taicpu(p).oper[1]^.typ = top_reg) and
  3728. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3729. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3730. begin
  3731. { we work with hp2 here, so hp1 can be still used later on when
  3732. checking for GetNextInstruction_p }
  3733. hp3 := hp1;
  3734. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3735. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3736. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3737. TransferUsedRegs(TmpUsedRegs);
  3738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3739. if NotFirstIteration then
  3740. JumpTracking := TLinkedList.Create
  3741. else
  3742. JumpTracking := nil;
  3743. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3744. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3745. (hp2.typ=ait_instruction) do
  3746. begin
  3747. case taicpu(hp2).opcode of
  3748. A_POP:
  3749. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3750. begin
  3751. if not CrossJump and
  3752. not RegUsedBetween(p_TargetReg, p, hp2) then
  3753. begin
  3754. { We can remove the original MOV since the register
  3755. wasn't used between it and its popping from the stack }
  3756. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3757. RemoveCurrentp(p, hp1);
  3758. Result := True;
  3759. JumpTracking.Free;
  3760. Exit;
  3761. end;
  3762. { Can't go any further }
  3763. Break;
  3764. end;
  3765. A_MOV:
  3766. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3767. ((taicpu(p).oper[0]^.typ=top_const) or
  3768. ((taicpu(p).oper[0]^.typ=top_reg) and
  3769. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3770. )
  3771. ) then
  3772. begin
  3773. { we have
  3774. mov x, %treg
  3775. mov %treg, y
  3776. }
  3777. { We don't need to call UpdateUsedRegs for every instruction between
  3778. p and hp2 because the register we're concerned about will not
  3779. become deallocated (otherwise GetNextInstructionUsingReg would
  3780. have stopped at an earlier instruction). [Kit] }
  3781. TempRegUsed :=
  3782. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3783. RegReadByInstruction(p_TargetReg, hp3) or
  3784. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3785. case taicpu(p).oper[0]^.typ Of
  3786. top_reg:
  3787. begin
  3788. { change
  3789. mov %reg, %treg
  3790. mov %treg, y
  3791. to
  3792. mov %reg, y
  3793. }
  3794. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3795. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3796. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3797. begin
  3798. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3799. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3800. if TempRegUsed then
  3801. begin
  3802. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3803. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3804. { Set the start of the next GetNextInstructionUsingRegCond search
  3805. to start at the entry right before hp2 (which is about to be removed) }
  3806. hp3 := tai(hp2.Previous);
  3807. RemoveInstruction(hp2);
  3808. { See if there's more we can optimise }
  3809. Continue;
  3810. end
  3811. else
  3812. begin
  3813. RemoveInstruction(hp2);
  3814. { We can remove the original MOV too }
  3815. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3816. RemoveCurrentP(p, hp1);
  3817. Result:=true;
  3818. JumpTracking.Free;
  3819. Exit;
  3820. end;
  3821. end
  3822. else
  3823. begin
  3824. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3825. taicpu(hp2).loadReg(0, p_SourceReg);
  3826. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3827. { Check to see if the register also appears in the reference }
  3828. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3829. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3830. { Don't remove the first instruction if the temporary register is in use }
  3831. if not TempRegUsed and
  3832. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3833. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3834. begin
  3835. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3836. RemoveCurrentP(p, hp1);
  3837. Result:=true;
  3838. JumpTracking.Free;
  3839. Exit;
  3840. end;
  3841. { No need to set Result to True here. If there's another instruction later
  3842. on that can be optimised, it will be detected when the main Pass 1 loop
  3843. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3844. end;
  3845. end;
  3846. top_const:
  3847. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3848. begin
  3849. { change
  3850. mov const, %treg
  3851. mov %treg, y
  3852. to
  3853. mov const, y
  3854. }
  3855. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3856. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3857. begin
  3858. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3859. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3860. if TempRegUsed then
  3861. begin
  3862. { Don't remove the first instruction if the temporary register is in use }
  3863. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3864. { No need to set Result to True. If there's another instruction later on
  3865. that can be optimised, it will be detected when the main Pass 1 loop
  3866. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3867. end
  3868. else
  3869. begin
  3870. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3871. RemoveCurrentP(p, hp1);
  3872. Result:=true;
  3873. Exit;
  3874. end;
  3875. end;
  3876. end;
  3877. else
  3878. Internalerror(2019103001);
  3879. end;
  3880. end
  3881. else
  3882. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3883. begin
  3884. if not CrossJump and
  3885. not RegUsedBetween(p_TargetReg, p, hp2) and
  3886. not RegReadByInstruction(p_TargetReg, hp2) then
  3887. begin
  3888. { Register is not used before it is overwritten }
  3889. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3890. RemoveCurrentp(p, hp1);
  3891. Result := True;
  3892. Exit;
  3893. end;
  3894. if (taicpu(p).oper[0]^.typ = top_const) and
  3895. (taicpu(hp2).oper[0]^.typ = top_const) then
  3896. begin
  3897. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3898. begin
  3899. { Same value - register hasn't changed }
  3900. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3901. RemoveInstruction(hp2);
  3902. Result := True;
  3903. { See if there's more we can optimise }
  3904. Continue;
  3905. end;
  3906. end;
  3907. end;
  3908. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3909. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3910. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3911. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3912. begin
  3913. {
  3914. Change from:
  3915. mov ###, %reg
  3916. ...
  3917. movs/z %reg,%reg (Same register, just different sizes)
  3918. To:
  3919. movs/z ###, %reg (Longer version)
  3920. ...
  3921. (remove)
  3922. }
  3923. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3924. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3925. { Keep the first instruction as mov if ### is a constant }
  3926. if taicpu(p).oper[0]^.typ = top_const then
  3927. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3928. else
  3929. begin
  3930. taicpu(p).opcode := taicpu(hp2).opcode;
  3931. taicpu(p).opsize := taicpu(hp2).opsize;
  3932. end;
  3933. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3934. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3935. RemoveInstruction(hp2);
  3936. Result := True;
  3937. JumpTracking.Free;
  3938. Exit;
  3939. end;
  3940. else
  3941. { Move down to the MatchOpType if-block below };
  3942. end;
  3943. { Also catches MOV/S/Z instructions that aren't modified }
  3944. if taicpu(p).oper[0]^.typ = top_reg then
  3945. begin
  3946. p_SourceReg := taicpu(p).oper[0]^.reg;
  3947. if
  3948. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3949. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3950. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3951. begin
  3952. Result := True;
  3953. { Just in case something didn't get modified (e.g. an
  3954. implicit register). Also, if it does read from this
  3955. register, then there's no longer an advantage to
  3956. changing the register on subsequent instructions.}
  3957. if not RegReadByInstruction(p_TargetReg, hp2) then
  3958. begin
  3959. { If a conditional jump was crossed, do not delete
  3960. the original MOV no matter what }
  3961. if not CrossJump and
  3962. { RegEndOfLife returns True if the register is
  3963. deallocated before the next instruction or has
  3964. been loaded with a new value }
  3965. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3966. begin
  3967. { We can remove the original MOV }
  3968. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3969. RemoveCurrentp(p, hp1);
  3970. JumpTracking.Free;
  3971. Result := True;
  3972. Exit;
  3973. end;
  3974. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3975. begin
  3976. { See if there's more we can optimise }
  3977. hp3 := hp2;
  3978. Continue;
  3979. end;
  3980. end;
  3981. end;
  3982. end;
  3983. { Break out of the while loop under normal circumstances }
  3984. Break;
  3985. end;
  3986. JumpTracking.Free;
  3987. end;
  3988. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3989. (taicpu(p).oper[1]^.typ = top_reg) and
  3990. (taicpu(p).opsize = S_L) and
  3991. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3992. (hp2.typ = ait_instruction) and
  3993. (taicpu(hp2).opcode = A_AND) and
  3994. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3995. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3996. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3997. ) then
  3998. begin
  3999. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4000. begin
  4001. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4002. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4003. begin
  4004. { Optimize out:
  4005. mov x, %reg
  4006. and ffffffffh, %reg
  4007. }
  4008. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4009. RemoveInstruction(hp2);
  4010. Result:=true;
  4011. exit;
  4012. end;
  4013. end;
  4014. end;
  4015. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4016. x >= RetOffset) as it doesn't do anything (it writes either to a
  4017. parameter or to the temporary storage room for the function
  4018. result)
  4019. }
  4020. if IsExitCode(hp1) and
  4021. (taicpu(p).oper[1]^.typ = top_ref) and
  4022. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4023. (
  4024. (
  4025. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4026. not (
  4027. assigned(current_procinfo.procdef.funcretsym) and
  4028. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4029. )
  4030. ) or
  4031. { Also discard writes to the stack that are below the base pointer,
  4032. as this is temporary storage rather than a function result on the
  4033. stack, say. }
  4034. (
  4035. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4036. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4037. )
  4038. ) then
  4039. begin
  4040. RemoveCurrentp(p, hp1);
  4041. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4042. RemoveLastDeallocForFuncRes(p);
  4043. Result:=true;
  4044. exit;
  4045. end;
  4046. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4047. begin
  4048. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4049. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4050. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4051. begin
  4052. { change
  4053. mov reg1, mem1
  4054. test/cmp x, mem1
  4055. to
  4056. mov reg1, mem1
  4057. test/cmp x, reg1
  4058. }
  4059. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4060. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4062. Result := True;
  4063. Exit;
  4064. end;
  4065. if DoMovCmpMemOpt(p, hp1, True) then
  4066. begin
  4067. Result := True;
  4068. Exit;
  4069. end;
  4070. end;
  4071. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4072. { If the flags register is in use, don't change the instruction to an
  4073. ADD otherwise this will scramble the flags. [Kit] }
  4074. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4075. begin
  4076. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4077. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4078. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4079. ) or
  4080. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4081. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4082. )
  4083. ) then
  4084. { mov reg1,ref
  4085. lea reg2,[reg1,reg2]
  4086. to
  4087. add reg2,ref}
  4088. begin
  4089. TransferUsedRegs(TmpUsedRegs);
  4090. { reg1 may not be used afterwards }
  4091. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4092. begin
  4093. Taicpu(hp1).opcode:=A_ADD;
  4094. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4095. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4096. RemoveCurrentp(p, hp1);
  4097. result:=true;
  4098. exit;
  4099. end;
  4100. end;
  4101. { If the LEA instruction can be converted into an arithmetic instruction,
  4102. it may be possible to then fold it in the next optimisation, otherwise
  4103. there's nothing more that can be optimised here. }
  4104. if not ConvertLEA(taicpu(hp1)) then
  4105. Exit;
  4106. end;
  4107. if (taicpu(p).oper[1]^.typ = top_reg) and
  4108. (hp1.typ = ait_instruction) and
  4109. GetNextInstruction(hp1, hp2) and
  4110. MatchInstruction(hp2,A_MOV,[]) and
  4111. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4112. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4113. (
  4114. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4115. {$ifdef x86_64}
  4116. or
  4117. (
  4118. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4119. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4120. )
  4121. {$endif x86_64}
  4122. ) then
  4123. begin
  4124. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4125. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4126. { change movsX/movzX reg/ref, reg2
  4127. add/sub/or/... reg3/$const, reg2
  4128. mov reg2 reg/ref
  4129. dealloc reg2
  4130. to
  4131. add/sub/or/... reg3/$const, reg/ref }
  4132. begin
  4133. TransferUsedRegs(TmpUsedRegs);
  4134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4137. begin
  4138. { by example:
  4139. movswl %si,%eax movswl %si,%eax p
  4140. decl %eax addl %edx,%eax hp1
  4141. movw %ax,%si movw %ax,%si hp2
  4142. ->
  4143. movswl %si,%eax movswl %si,%eax p
  4144. decw %eax addw %edx,%eax hp1
  4145. movw %ax,%si movw %ax,%si hp2
  4146. }
  4147. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4148. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4149. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4150. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4151. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4152. {
  4153. ->
  4154. movswl %si,%eax movswl %si,%eax p
  4155. decw %si addw %dx,%si hp1
  4156. movw %ax,%si movw %ax,%si hp2
  4157. }
  4158. case taicpu(hp1).ops of
  4159. 1:
  4160. begin
  4161. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4162. if taicpu(hp1).oper[0]^.typ=top_reg then
  4163. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4164. end;
  4165. 2:
  4166. begin
  4167. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4168. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4169. (taicpu(hp1).opcode<>A_SHL) and
  4170. (taicpu(hp1).opcode<>A_SHR) and
  4171. (taicpu(hp1).opcode<>A_SAR) then
  4172. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4173. end;
  4174. else
  4175. internalerror(2008042701);
  4176. end;
  4177. {
  4178. ->
  4179. decw %si addw %dx,%si p
  4180. }
  4181. RemoveInstruction(hp2);
  4182. RemoveCurrentP(p, hp1);
  4183. Result:=True;
  4184. Exit;
  4185. end;
  4186. end;
  4187. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4188. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4189. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4190. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4191. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4192. )
  4193. {$ifdef i386}
  4194. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4195. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4196. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4197. {$endif i386}
  4198. then
  4199. { change movsX/movzX reg/ref, reg2
  4200. add/sub/or/... regX/$const, reg2
  4201. mov reg2, reg3
  4202. dealloc reg2
  4203. to
  4204. movsX/movzX reg/ref, reg3
  4205. add/sub/or/... reg3/$const, reg3
  4206. }
  4207. begin
  4208. TransferUsedRegs(TmpUsedRegs);
  4209. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4210. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4211. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4212. begin
  4213. { by example:
  4214. movswl %si,%eax movswl %si,%eax p
  4215. decl %eax addl %edx,%eax hp1
  4216. movw %ax,%si movw %ax,%si hp2
  4217. ->
  4218. movswl %si,%eax movswl %si,%eax p
  4219. decw %eax addw %edx,%eax hp1
  4220. movw %ax,%si movw %ax,%si hp2
  4221. }
  4222. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4223. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4224. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4225. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4226. { limit size of constants as well to avoid assembler errors, but
  4227. check opsize to avoid overflow when left shifting the 1 }
  4228. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4229. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4230. {$ifdef x86_64}
  4231. { Be careful of, for example:
  4232. movl %reg1,%reg2
  4233. addl %reg3,%reg2
  4234. movq %reg2,%reg4
  4235. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4236. }
  4237. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4238. begin
  4239. taicpu(hp2).changeopsize(S_L);
  4240. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4241. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4242. end;
  4243. {$endif x86_64}
  4244. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4245. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4246. if taicpu(p).oper[0]^.typ=top_reg then
  4247. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4248. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4249. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4250. {
  4251. ->
  4252. movswl %si,%eax movswl %si,%eax p
  4253. decw %si addw %dx,%si hp1
  4254. movw %ax,%si movw %ax,%si hp2
  4255. }
  4256. case taicpu(hp1).ops of
  4257. 1:
  4258. begin
  4259. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4260. if taicpu(hp1).oper[0]^.typ=top_reg then
  4261. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4262. end;
  4263. 2:
  4264. begin
  4265. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4266. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4267. (taicpu(hp1).opcode<>A_SHL) and
  4268. (taicpu(hp1).opcode<>A_SHR) and
  4269. (taicpu(hp1).opcode<>A_SAR) then
  4270. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4271. end;
  4272. else
  4273. internalerror(2018111801);
  4274. end;
  4275. {
  4276. ->
  4277. decw %si addw %dx,%si p
  4278. }
  4279. RemoveInstruction(hp2);
  4280. end;
  4281. end;
  4282. end;
  4283. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4284. GetNextInstruction(hp1, hp2) and
  4285. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4286. MatchOperand(Taicpu(p).oper[0]^,0) and
  4287. (Taicpu(p).oper[1]^.typ = top_reg) and
  4288. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4289. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4290. { mov reg1,0
  4291. bts reg1,operand1 --> mov reg1,operand2
  4292. or reg1,operand2 bts reg1,operand1}
  4293. begin
  4294. Taicpu(hp2).opcode:=A_MOV;
  4295. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4296. asml.remove(hp1);
  4297. insertllitem(hp2,hp2.next,hp1);
  4298. RemoveCurrentp(p, hp1);
  4299. Result:=true;
  4300. exit;
  4301. end;
  4302. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4303. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4304. GetNextInstruction(hp1, hp2) and
  4305. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4306. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4307. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4308. { change
  4309. mov reg1,reg2
  4310. sub reg3,reg2
  4311. cmp reg3,reg1
  4312. into
  4313. mov reg1,reg2
  4314. sub reg3,reg2
  4315. }
  4316. begin
  4317. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4318. RemoveInstruction(hp2);
  4319. Result:=true;
  4320. exit;
  4321. end;
  4322. {
  4323. mov ref,reg0
  4324. <op> reg0,reg1
  4325. dealloc reg0
  4326. to
  4327. <op> ref,reg1
  4328. }
  4329. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4330. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4331. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4332. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4333. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4334. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4335. begin
  4336. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4337. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4338. RemoveCurrentp(p, hp1);
  4339. Result:=true;
  4340. exit;
  4341. end;
  4342. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4343. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4344. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4345. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4346. begin
  4347. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4348. {$ifdef x86_64}
  4349. { Convert:
  4350. movq x(ref),%reg64
  4351. shrq y,%reg64
  4352. To:
  4353. movl x+4(ref),%reg32
  4354. shrl y-32,%reg32 (Remove if y = 32)
  4355. }
  4356. if (taicpu(p).opsize = S_Q) and
  4357. (taicpu(hp1).opcode = A_SHR) and
  4358. (taicpu(hp1).oper[0]^.val >= 32) then
  4359. begin
  4360. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4361. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4362. { Convert to 32-bit }
  4363. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4364. taicpu(p).opsize := S_L;
  4365. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4366. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4367. if (taicpu(hp1).oper[0]^.val = 32) then
  4368. begin
  4369. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4370. RemoveInstruction(hp1);
  4371. end
  4372. else
  4373. begin
  4374. { This will potentially open up more arithmetic operations since
  4375. the peephole optimizer now has a big hint that only the lower
  4376. 32 bits are currently in use (and opcodes are smaller in size) }
  4377. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4378. taicpu(hp1).opsize := S_L;
  4379. Dec(taicpu(hp1).oper[0]^.val, 32);
  4380. DebugMsg(SPeepholeOptimization + PreMessage +
  4381. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4382. end;
  4383. Result := True;
  4384. Exit;
  4385. end;
  4386. {$endif x86_64}
  4387. { Convert:
  4388. movl x(ref),%reg
  4389. shrl $24,%reg
  4390. To:
  4391. movzbl x+3(ref),%reg
  4392. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4393. Also accept sar instead of shr, but convert to movsx instead of movzx
  4394. }
  4395. if taicpu(hp1).opcode = A_SHR then
  4396. MovUnaligned := A_MOVZX
  4397. else
  4398. MovUnaligned := A_MOVSX;
  4399. NewSize := S_NO;
  4400. NewOffset := 0;
  4401. case taicpu(p).opsize of
  4402. S_B:
  4403. { No valid combinations };
  4404. S_W:
  4405. if (taicpu(hp1).oper[0]^.val = 8) then
  4406. begin
  4407. NewSize := S_BW;
  4408. NewOffset := 1;
  4409. end;
  4410. S_L:
  4411. case taicpu(hp1).oper[0]^.val of
  4412. 16:
  4413. begin
  4414. NewSize := S_WL;
  4415. NewOffset := 2;
  4416. end;
  4417. 24:
  4418. begin
  4419. NewSize := S_BL;
  4420. NewOffset := 3;
  4421. end;
  4422. else
  4423. ;
  4424. end;
  4425. {$ifdef x86_64}
  4426. S_Q:
  4427. case taicpu(hp1).oper[0]^.val of
  4428. 32:
  4429. begin
  4430. if taicpu(hp1).opcode = A_SAR then
  4431. begin
  4432. { 32-bit to 64-bit is a distinct instruction }
  4433. MovUnaligned := A_MOVSXD;
  4434. NewSize := S_LQ;
  4435. NewOffset := 4;
  4436. end
  4437. else
  4438. { Should have been handled by MovShr2Mov above }
  4439. InternalError(2022081811);
  4440. end;
  4441. 48:
  4442. begin
  4443. NewSize := S_WQ;
  4444. NewOffset := 6;
  4445. end;
  4446. 56:
  4447. begin
  4448. NewSize := S_BQ;
  4449. NewOffset := 7;
  4450. end;
  4451. else
  4452. ;
  4453. end;
  4454. {$endif x86_64}
  4455. else
  4456. InternalError(2022081810);
  4457. end;
  4458. if (NewSize <> S_NO) and
  4459. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4460. begin
  4461. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4462. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4463. debug_op2str(MovUnaligned);
  4464. {$ifdef x86_64}
  4465. if MovUnaligned <> A_MOVSXD then
  4466. { Don't add size suffix for MOVSXD }
  4467. {$endif x86_64}
  4468. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4469. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4470. taicpu(p).opcode := MovUnaligned;
  4471. taicpu(p).opsize := NewSize;
  4472. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4473. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4474. RemoveInstruction(hp1);
  4475. Result := True;
  4476. Exit;
  4477. end;
  4478. end;
  4479. { Backward optimisation shared with OptPass2MOV }
  4480. if FuncMov2Func(p, hp1) then
  4481. begin
  4482. Result := True;
  4483. Exit;
  4484. end;
  4485. end;
  4486. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4487. var
  4488. hp1 : tai;
  4489. begin
  4490. Result:=false;
  4491. if taicpu(p).ops <> 2 then
  4492. exit;
  4493. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4494. GetNextInstruction(p,hp1) then
  4495. begin
  4496. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4497. (taicpu(hp1).ops = 2) then
  4498. begin
  4499. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4500. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4501. { movXX reg1, mem1 or movXX mem1, reg1
  4502. movXX mem2, reg2 movXX reg2, mem2}
  4503. begin
  4504. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4505. { movXX reg1, mem1 or movXX mem1, reg1
  4506. movXX mem2, reg1 movXX reg2, mem1}
  4507. begin
  4508. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4509. begin
  4510. { Removes the second statement from
  4511. movXX reg1, mem1/reg2
  4512. movXX mem1/reg2, reg1
  4513. }
  4514. if taicpu(p).oper[0]^.typ=top_reg then
  4515. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4516. { Removes the second statement from
  4517. movXX mem1/reg1, reg2
  4518. movXX reg2, mem1/reg1
  4519. }
  4520. if (taicpu(p).oper[1]^.typ=top_reg) and
  4521. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4522. begin
  4523. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4524. RemoveInstruction(hp1);
  4525. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4526. Result:=true;
  4527. exit;
  4528. end
  4529. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4530. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4531. begin
  4532. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4533. RemoveInstruction(hp1);
  4534. Result:=true;
  4535. exit;
  4536. end;
  4537. end
  4538. end;
  4539. end;
  4540. end;
  4541. end;
  4542. end;
  4543. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4544. var
  4545. hp1 : tai;
  4546. begin
  4547. result:=false;
  4548. { replace
  4549. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4550. MovX %mreg2,%mreg1
  4551. dealloc %mreg2
  4552. by
  4553. <Op>X %mreg2,%mreg1
  4554. ?
  4555. }
  4556. if GetNextInstruction(p,hp1) and
  4557. { we mix single and double opperations here because we assume that the compiler
  4558. generates vmovapd only after double operations and vmovaps only after single operations }
  4559. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4560. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4561. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4562. (taicpu(p).oper[0]^.typ=top_reg) then
  4563. begin
  4564. TransferUsedRegs(TmpUsedRegs);
  4565. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4566. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4567. begin
  4568. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4569. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4570. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4571. RemoveInstruction(hp1);
  4572. result:=true;
  4573. end;
  4574. end;
  4575. end;
  4576. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4577. var
  4578. hp1, p_label, p_dist, hp1_dist: tai;
  4579. JumpLabel, JumpLabel_dist: TAsmLabel;
  4580. FirstValue, SecondValue: TCGInt;
  4581. TempBool: Boolean;
  4582. begin
  4583. Result := False;
  4584. if (taicpu(p).oper[0]^.typ = top_const) and
  4585. (taicpu(p).oper[0]^.val <> -1) then
  4586. begin
  4587. { Convert unsigned maximum constants to -1 to aid optimisation }
  4588. case taicpu(p).opsize of
  4589. S_B:
  4590. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4591. begin
  4592. taicpu(p).oper[0]^.val := -1;
  4593. Result := True;
  4594. Exit;
  4595. end;
  4596. S_W:
  4597. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4598. begin
  4599. taicpu(p).oper[0]^.val := -1;
  4600. Result := True;
  4601. Exit;
  4602. end;
  4603. S_L:
  4604. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4605. begin
  4606. taicpu(p).oper[0]^.val := -1;
  4607. Result := True;
  4608. Exit;
  4609. end;
  4610. {$ifdef x86_64}
  4611. S_Q:
  4612. { Storing anything greater than $7FFFFFFF is not possible so do
  4613. nothing };
  4614. {$endif x86_64}
  4615. else
  4616. InternalError(2021121001);
  4617. end;
  4618. end;
  4619. if GetNextInstruction(p, hp1) and
  4620. TrySwapMovCmp(p, hp1) then
  4621. begin
  4622. Result := True;
  4623. Exit;
  4624. end;
  4625. if MatchInstruction(hp1, A_Jcc, []) then
  4626. begin
  4627. TempBool := True;
  4628. if DoJumpOptimizations(hp1, TempBool) or
  4629. not TempBool then
  4630. begin
  4631. Result := True;
  4632. if Assigned(hp1) then
  4633. begin
  4634. if (hp1.typ in [ait_align]) then
  4635. SkipAligns(hp1, hp1);
  4636. { CollapseZeroDistJump will be set to the label after the
  4637. jump if it optimises, whether or not it's live or dead }
  4638. if (hp1.typ in [ait_label]) and
  4639. not (tai_label(hp1).labsym.is_used) then
  4640. GetNextInstruction(hp1, hp1);
  4641. end;
  4642. TransferUsedRegs(TmpUsedRegs);
  4643. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4644. if not Assigned(hp1) or
  4645. (
  4646. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4647. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4648. ) then
  4649. begin
  4650. { No more conditional jumps; conditional statement is no longer required }
  4651. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4652. RemoveCurrentP(p);
  4653. end;
  4654. Exit;
  4655. end;
  4656. end;
  4657. { Search for:
  4658. test $x,(reg/ref)
  4659. jne @lbl1
  4660. test $y,(reg/ref) (same register or reference)
  4661. jne @lbl1
  4662. Change to:
  4663. test $(x or y),(reg/ref)
  4664. jne @lbl1
  4665. (Note, this doesn't work with je instead of jne)
  4666. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4667. Also search for:
  4668. test $x,(reg/ref)
  4669. je @lbl1
  4670. test $y,(reg/ref)
  4671. je/jne @lbl2
  4672. If (x or y) = x, then the second jump is deterministic
  4673. }
  4674. if (
  4675. (
  4676. (taicpu(p).oper[0]^.typ = top_const) or
  4677. (
  4678. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4679. (taicpu(p).oper[0]^.typ = top_reg) and
  4680. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4681. )
  4682. ) and
  4683. MatchInstruction(hp1, A_JCC, [])
  4684. ) then
  4685. begin
  4686. if (taicpu(p).oper[0]^.typ = top_reg) and
  4687. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4688. FirstValue := -1
  4689. else
  4690. FirstValue := taicpu(p).oper[0]^.val;
  4691. { If we have several test/jne's in a row, it might be the case that
  4692. the second label doesn't go to the same location, but the one
  4693. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4694. so accommodate for this with a while loop.
  4695. }
  4696. hp1_dist := hp1;
  4697. if GetNextInstruction(hp1, p_dist) and
  4698. (p_dist.typ = ait_instruction) and
  4699. (
  4700. (
  4701. (taicpu(p_dist).opcode = A_TEST) and
  4702. (
  4703. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4704. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4705. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4706. )
  4707. ) or
  4708. (
  4709. { cmp 0,%reg = test %reg,%reg }
  4710. (taicpu(p_dist).opcode = A_CMP) and
  4711. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4712. )
  4713. ) and
  4714. { Make sure the destination operands are actually the same }
  4715. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4716. GetNextInstruction(p_dist, hp1_dist) and
  4717. MatchInstruction(hp1_dist, A_JCC, []) then
  4718. begin
  4719. if
  4720. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4721. (
  4722. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4723. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4724. ) then
  4725. SecondValue := -1
  4726. else
  4727. SecondValue := taicpu(p_dist).oper[0]^.val;
  4728. { If both of the TEST constants are identical, delete the second
  4729. TEST that is unnecessary. }
  4730. if (FirstValue = SecondValue) then
  4731. begin
  4732. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4733. RemoveInstruction(p_dist);
  4734. { Don't let the flags register become deallocated and reallocated between the jumps }
  4735. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4736. Result := True;
  4737. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4738. begin
  4739. { Since the second jump's condition is a subset of the first, we
  4740. know it will never branch because the first jump dominates it.
  4741. Get it out of the way now rather than wait for the jump
  4742. optimisations for a speed boost. }
  4743. if IsJumpToLabel(taicpu(hp1_dist)) then
  4744. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4745. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4746. RemoveInstruction(hp1_dist);
  4747. end
  4748. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4749. begin
  4750. { If the inverse of the first condition is a subset of the second,
  4751. the second one will definitely branch if the first one doesn't }
  4752. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4753. MakeUnconditional(taicpu(hp1_dist));
  4754. RemoveDeadCodeAfterJump(hp1_dist);
  4755. end;
  4756. Exit;
  4757. end;
  4758. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4759. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4760. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4761. then the second jump will never branch, so it can also be
  4762. removed regardless of where it goes }
  4763. (
  4764. (FirstValue = -1) or
  4765. (SecondValue = -1) or
  4766. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4767. ) then
  4768. begin
  4769. { Same jump location... can be a register since nothing's changed }
  4770. { If any of the entries are equivalent to test %reg,%reg, then the
  4771. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4772. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4773. if IsJumpToLabel(taicpu(hp1_dist)) then
  4774. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4775. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4776. RemoveInstruction(hp1_dist);
  4777. { Only remove the second test if no jumps or other conditional instructions follow }
  4778. TransferUsedRegs(TmpUsedRegs);
  4779. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4780. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4781. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4782. RemoveInstruction(p_dist);
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. end;
  4787. end;
  4788. { Search for:
  4789. test %reg,%reg
  4790. j(c1) @lbl1
  4791. ...
  4792. @lbl:
  4793. test %reg,%reg (same register)
  4794. j(c2) @lbl2
  4795. If c2 is a subset of c1, change to:
  4796. test %reg,%reg
  4797. j(c1) @lbl2
  4798. (@lbl1 may become a dead label as a result)
  4799. }
  4800. if (taicpu(p).oper[1]^.typ = top_reg) and
  4801. (taicpu(p).oper[0]^.typ = top_reg) and
  4802. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4803. MatchInstruction(hp1, A_JCC, []) and
  4804. IsJumpToLabel(taicpu(hp1)) then
  4805. begin
  4806. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4807. p_label := nil;
  4808. if Assigned(JumpLabel) then
  4809. p_label := getlabelwithsym(JumpLabel);
  4810. if Assigned(p_label) and
  4811. GetNextInstruction(p_label, p_dist) and
  4812. MatchInstruction(p_dist, A_TEST, []) and
  4813. { It's fine if the second test uses smaller sub-registers }
  4814. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4815. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4816. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4817. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4818. GetNextInstruction(p_dist, hp1_dist) and
  4819. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4820. begin
  4821. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4822. if JumpLabel = JumpLabel_dist then
  4823. { This is an infinite loop }
  4824. Exit;
  4825. { Best optimisation when the first condition is a subset (or equal) of the second }
  4826. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4827. begin
  4828. { Any registers used here will already be allocated }
  4829. if Assigned(JumpLabel) then
  4830. JumpLabel.DecRefs;
  4831. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4832. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4833. Result := True;
  4834. Exit;
  4835. end;
  4836. end;
  4837. end;
  4838. end;
  4839. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4840. var
  4841. hp1, hp2: tai;
  4842. ActiveReg: TRegister;
  4843. OldOffset: asizeint;
  4844. ThisConst: TCGInt;
  4845. function RegDeallocated: Boolean;
  4846. begin
  4847. TransferUsedRegs(TmpUsedRegs);
  4848. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4849. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4850. end;
  4851. begin
  4852. result:=false;
  4853. hp1 := nil;
  4854. { replace
  4855. addX const,%reg1
  4856. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4857. dealloc %reg1
  4858. by
  4859. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4860. }
  4861. if MatchOpType(taicpu(p),top_const,top_reg) then
  4862. begin
  4863. ActiveReg := taicpu(p).oper[1]^.reg;
  4864. { Ensures the entire register was updated }
  4865. if (taicpu(p).opsize >= S_L) and
  4866. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4867. MatchInstruction(hp1,A_LEA,[]) and
  4868. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4869. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4870. (
  4871. { Cover the case where the register in the reference is also the destination register }
  4872. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4873. (
  4874. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4875. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4876. RegDeallocated
  4877. )
  4878. ) then
  4879. begin
  4880. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4881. {$push}
  4882. {$R-}{$Q-}
  4883. { Explicitly disable overflow checking for these offset calculation
  4884. as those do not matter for the final result }
  4885. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4886. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4887. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4888. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4889. {$pop}
  4890. {$ifdef x86_64}
  4891. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4892. begin
  4893. { Overflow; abort }
  4894. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4895. end
  4896. else
  4897. {$endif x86_64}
  4898. begin
  4899. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4900. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4901. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4902. RemoveCurrentP(p, hp1)
  4903. else
  4904. RemoveCurrentP(p);
  4905. result:=true;
  4906. Exit;
  4907. end;
  4908. end;
  4909. if (
  4910. { Save calling GetNextInstructionUsingReg again }
  4911. Assigned(hp1) or
  4912. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4913. ) and
  4914. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4915. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4916. begin
  4917. if taicpu(hp1).oper[0]^.typ = top_const then
  4918. begin
  4919. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4920. if taicpu(hp1).opcode = A_ADD then
  4921. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4922. else
  4923. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4924. Result := True;
  4925. { Handle any overflows }
  4926. case taicpu(p).opsize of
  4927. S_B:
  4928. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4929. S_W:
  4930. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4931. S_L:
  4932. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4933. {$ifdef x86_64}
  4934. S_Q:
  4935. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4936. { Overflow; abort }
  4937. Result := False
  4938. else
  4939. taicpu(p).oper[0]^.val := ThisConst;
  4940. {$endif x86_64}
  4941. else
  4942. InternalError(2021102610);
  4943. end;
  4944. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4945. if Result then
  4946. begin
  4947. if (taicpu(p).oper[0]^.val < 0) and
  4948. (
  4949. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4950. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4951. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4952. ) then
  4953. begin
  4954. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4955. taicpu(p).opcode := A_SUB;
  4956. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4957. end
  4958. else
  4959. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4960. RemoveInstruction(hp1);
  4961. end;
  4962. end
  4963. else
  4964. begin
  4965. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4966. TransferUsedRegs(TmpUsedRegs);
  4967. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4968. hp2 := p;
  4969. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4970. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4971. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4972. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4973. begin
  4974. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4975. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4976. Asml.Remove(p);
  4977. Asml.InsertAfter(p, hp1);
  4978. p := hp1;
  4979. Result := True;
  4980. Exit;
  4981. end;
  4982. end;
  4983. end;
  4984. if DoArithCombineOpt(p) then
  4985. Result:=true;
  4986. end;
  4987. end;
  4988. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4989. var
  4990. hp1: tai;
  4991. ref: Integer;
  4992. saveref: treference;
  4993. Multiple: TCGInt;
  4994. Adjacent: Boolean;
  4995. begin
  4996. Result:=false;
  4997. { play save and throw an error if LEA uses a seg register prefix,
  4998. this is most likely an error somewhere else }
  4999. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5000. internalerror(2022022001);
  5001. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5002. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5003. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5004. (
  5005. { do not mess with leas accessing the stack pointer
  5006. unless it's a null operation }
  5007. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5008. (
  5009. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5010. (taicpu(p).oper[0]^.ref^.offset = 0)
  5011. )
  5012. ) and
  5013. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5014. begin
  5015. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5016. begin
  5017. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5018. begin
  5019. taicpu(p).opcode := A_MOV;
  5020. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5021. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5022. end
  5023. else
  5024. begin
  5025. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5026. RemoveCurrentP(p);
  5027. end;
  5028. Result:=true;
  5029. exit;
  5030. end
  5031. else if (
  5032. { continue to use lea to adjust the stack pointer,
  5033. it is the recommended way, but only if not optimizing for size }
  5034. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5035. (cs_opt_size in current_settings.optimizerswitches)
  5036. ) and
  5037. { If the flags register is in use, don't change the instruction
  5038. to an ADD otherwise this will scramble the flags. [Kit] }
  5039. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5040. ConvertLEA(taicpu(p)) then
  5041. begin
  5042. Result:=true;
  5043. exit;
  5044. end;
  5045. end;
  5046. { Don't optimise if the stack or frame pointer is the destination register }
  5047. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5048. Exit;
  5049. if GetNextInstruction(p,hp1) and
  5050. (hp1.typ=ait_instruction) then
  5051. begin
  5052. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5053. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5054. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5055. begin
  5056. TransferUsedRegs(TmpUsedRegs);
  5057. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5058. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5059. begin
  5060. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5061. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5062. RemoveInstruction(hp1);
  5063. result:=true;
  5064. exit;
  5065. end;
  5066. end;
  5067. { changes
  5068. lea <ref1>, reg1
  5069. <op> ...,<ref. with reg1>,...
  5070. to
  5071. <op> ...,<ref1>,... }
  5072. { find a reference which uses reg1 }
  5073. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5074. ref:=0
  5075. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5076. ref:=1
  5077. else
  5078. ref:=-1;
  5079. if (ref<>-1) and
  5080. { reg1 must be either the base or the index }
  5081. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5082. begin
  5083. { reg1 can be removed from the reference }
  5084. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5085. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5086. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5087. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5088. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5089. else
  5090. Internalerror(2019111201);
  5091. { check if the can insert all data of the lea into the second instruction }
  5092. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5093. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5094. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5095. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5096. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5097. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5098. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5099. {$ifdef x86_64}
  5100. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5101. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5102. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5103. )
  5104. {$endif x86_64}
  5105. then
  5106. begin
  5107. { reg1 might not used by the second instruction after it is remove from the reference }
  5108. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5109. begin
  5110. TransferUsedRegs(TmpUsedRegs);
  5111. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5112. { reg1 is not updated so it might not be used afterwards }
  5113. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5114. begin
  5115. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5116. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5117. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5118. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5119. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5120. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5121. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5122. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5123. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5124. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5125. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5126. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5127. RemoveCurrentP(p, hp1);
  5128. result:=true;
  5129. exit;
  5130. end
  5131. end;
  5132. end;
  5133. { recover }
  5134. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5135. end;
  5136. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5137. if Adjacent or
  5138. { Check further ahead (up to 2 instructions ahead for -O2) }
  5139. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5140. begin
  5141. { Check common LEA/LEA conditions }
  5142. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5143. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5144. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5145. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5146. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5147. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5148. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5149. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5150. (
  5151. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5152. calling it (since it calls GetNextInstruction) }
  5153. Adjacent or
  5154. (
  5155. (
  5156. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5157. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5158. ) and (
  5159. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5160. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5161. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5162. )
  5163. )
  5164. ) then
  5165. begin
  5166. { changes
  5167. lea (regX,scale), reg1
  5168. lea offset(reg1,reg1), reg1
  5169. to
  5170. lea offset(regX,scale*2), reg1
  5171. and
  5172. lea (regX,scale1), reg1
  5173. lea offset(reg1,scale2), reg1
  5174. to
  5175. lea offset(regX,scale1*scale2), reg1
  5176. ... so long as the final scale does not exceed 8
  5177. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5178. }
  5179. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5180. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5181. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5182. (
  5183. (
  5184. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5185. ) or (
  5186. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5187. (
  5188. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5189. (
  5190. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5191. Adjacent or
  5192. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5193. )
  5194. )
  5195. )
  5196. ) and (
  5197. (
  5198. { lea (reg1,scale2), reg1 variant }
  5199. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5200. (
  5201. (
  5202. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5203. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5204. ) or (
  5205. { lea (regX,regX), reg1 variant }
  5206. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5207. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5208. )
  5209. )
  5210. ) or (
  5211. { lea (reg1,reg1), reg1 variant }
  5212. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5213. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5214. )
  5215. ) then
  5216. begin
  5217. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5218. { Make everything homogeneous to make calculations easier }
  5219. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5220. begin
  5221. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5222. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5223. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5224. else
  5225. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5226. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5227. end;
  5228. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5229. begin
  5230. { Just to prevent miscalculations }
  5231. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5232. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5233. else
  5234. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5235. end
  5236. else
  5237. begin
  5238. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5239. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5240. end;
  5241. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5242. RemoveCurrentP(p);
  5243. result:=true;
  5244. exit;
  5245. end
  5246. { changes
  5247. lea offset1(regX), reg1
  5248. lea offset2(reg1), reg1
  5249. to
  5250. lea offset1+offset2(regX), reg1 }
  5251. else if
  5252. (
  5253. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5254. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5255. ) or (
  5256. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5257. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5258. (
  5259. (
  5260. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5261. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5262. ) or (
  5263. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5264. (
  5265. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5266. (
  5267. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5268. (
  5269. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5270. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5271. )
  5272. )
  5273. )
  5274. )
  5275. )
  5276. ) then
  5277. begin
  5278. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5279. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5280. begin
  5281. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5282. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5283. { if the register is used as index and base, we have to increase for base as well
  5284. and adapt base }
  5285. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5286. begin
  5287. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5288. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5289. end;
  5290. end
  5291. else
  5292. begin
  5293. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5294. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5295. end;
  5296. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5297. begin
  5298. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5299. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5300. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5301. end;
  5302. RemoveCurrentP(p);
  5303. result:=true;
  5304. exit;
  5305. end;
  5306. end;
  5307. { Change:
  5308. leal/q $x(%reg1),%reg2
  5309. ...
  5310. shll/q $y,%reg2
  5311. To:
  5312. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5313. }
  5314. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5315. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5316. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5317. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5318. (taicpu(hp1).oper[0]^.val <= 3) then
  5319. begin
  5320. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5321. TransferUsedRegs(TmpUsedRegs);
  5322. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5323. if
  5324. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5325. (this works even if scalefactor is zero) }
  5326. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5327. { Ensure offset doesn't go out of bounds }
  5328. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5329. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5330. (
  5331. (
  5332. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5333. (
  5334. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5335. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5336. (
  5337. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5338. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5339. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5340. )
  5341. )
  5342. ) or (
  5343. (
  5344. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5345. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5346. ) and
  5347. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5348. )
  5349. ) then
  5350. begin
  5351. repeat
  5352. with taicpu(p).oper[0]^.ref^ do
  5353. begin
  5354. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5355. if index = base then
  5356. begin
  5357. if Multiple > 4 then
  5358. { Optimisation will no longer work because resultant
  5359. scale factor will exceed 8 }
  5360. Break;
  5361. base := NR_NO;
  5362. scalefactor := 2;
  5363. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5364. end
  5365. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5366. begin
  5367. { Scale factor only works on the index register }
  5368. index := base;
  5369. base := NR_NO;
  5370. end;
  5371. { For safety }
  5372. if scalefactor <= 1 then
  5373. begin
  5374. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5375. scalefactor := Multiple;
  5376. end
  5377. else
  5378. begin
  5379. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5380. scalefactor := scalefactor * Multiple;
  5381. end;
  5382. offset := offset * Multiple;
  5383. end;
  5384. RemoveInstruction(hp1);
  5385. Result := True;
  5386. Exit;
  5387. { This repeat..until loop exists for the benefit of Break }
  5388. until True;
  5389. end;
  5390. end;
  5391. end;
  5392. end;
  5393. end;
  5394. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5395. var
  5396. hp1 : tai;
  5397. SubInstr: Boolean;
  5398. ThisConst: TCGInt;
  5399. const
  5400. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5401. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5402. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5403. begin
  5404. Result := False;
  5405. if taicpu(p).oper[0]^.typ <> top_const then
  5406. { Should have been confirmed before calling }
  5407. InternalError(2021102601);
  5408. SubInstr := (taicpu(p).opcode = A_SUB);
  5409. if GetLastInstruction(p, hp1) and
  5410. (hp1.typ = ait_instruction) and
  5411. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5412. begin
  5413. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5414. { Bad size }
  5415. InternalError(2022042001);
  5416. case taicpu(hp1).opcode Of
  5417. A_INC:
  5418. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5419. begin
  5420. if SubInstr then
  5421. ThisConst := taicpu(p).oper[0]^.val - 1
  5422. else
  5423. ThisConst := taicpu(p).oper[0]^.val + 1;
  5424. end
  5425. else
  5426. Exit;
  5427. A_DEC:
  5428. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5429. begin
  5430. if SubInstr then
  5431. ThisConst := taicpu(p).oper[0]^.val + 1
  5432. else
  5433. ThisConst := taicpu(p).oper[0]^.val - 1;
  5434. end
  5435. else
  5436. Exit;
  5437. A_SUB:
  5438. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5439. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5440. begin
  5441. if SubInstr then
  5442. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5443. else
  5444. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5445. end
  5446. else
  5447. Exit;
  5448. A_ADD:
  5449. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5450. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5451. begin
  5452. if SubInstr then
  5453. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5454. else
  5455. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5456. end
  5457. else
  5458. Exit;
  5459. else
  5460. Exit;
  5461. end;
  5462. { Check that the values are in range }
  5463. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5464. { Overflow; abort }
  5465. Exit;
  5466. if (ThisConst = 0) then
  5467. begin
  5468. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5469. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5470. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5471. RemoveInstruction(hp1);
  5472. hp1 := tai(p.next);
  5473. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5474. if not GetLastInstruction(hp1, p) then
  5475. p := hp1;
  5476. end
  5477. else
  5478. begin
  5479. if taicpu(hp1).opercnt=1 then
  5480. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5481. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5482. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5483. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5484. else
  5485. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5486. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5487. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5488. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5489. RemoveInstruction(hp1);
  5490. taicpu(p).loadconst(0, ThisConst);
  5491. end;
  5492. Result := True;
  5493. end;
  5494. end;
  5495. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5496. begin
  5497. Result := False;
  5498. if UpdateTmpUsedRegs then
  5499. TransferUsedRegs(TmpUsedRegs);
  5500. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5501. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5502. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5503. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5504. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5505. (
  5506. (
  5507. (taicpu(hp1).opcode = A_TEST)
  5508. ) or (
  5509. (taicpu(hp1).opcode = A_CMP) and
  5510. { A sanity check more than anything }
  5511. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5512. )
  5513. ) then
  5514. begin
  5515. { change
  5516. mov mem, %reg
  5517. cmp/test x, %reg / test %reg,%reg
  5518. (reg deallocated)
  5519. to
  5520. cmp/test x, mem / cmp 0, mem
  5521. }
  5522. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5523. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5524. begin
  5525. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5526. if (taicpu(hp1).opcode = A_TEST) and
  5527. (
  5528. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5529. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5530. ) then
  5531. begin
  5532. taicpu(hp1).opcode := A_CMP;
  5533. taicpu(hp1).loadconst(0, 0);
  5534. end;
  5535. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5536. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5537. RemoveCurrentP(p, hp1);
  5538. Result := True;
  5539. Exit;
  5540. end;
  5541. end;
  5542. end;
  5543. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5544. var
  5545. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5546. ThisReg, SecondReg: TRegister;
  5547. JumpLoc: TAsmLabel;
  5548. NewSize: TOpSize;
  5549. begin
  5550. Result := False;
  5551. {
  5552. Convert:
  5553. j<c> .L1
  5554. .L2:
  5555. mov 1,reg
  5556. jmp .L3 (or ret, although it might not be a RET yet)
  5557. .L1:
  5558. mov 0,reg
  5559. jmp .L3 (or ret)
  5560. ( As long as .L3 <> .L1 or .L2)
  5561. To:
  5562. mov 0,reg
  5563. set<not(c)> reg
  5564. jmp .L3 (or ret)
  5565. .L2:
  5566. mov 1,reg
  5567. jmp .L3 (or ret)
  5568. .L1:
  5569. mov 0,reg
  5570. jmp .L3 (or ret)
  5571. }
  5572. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5573. Exit;
  5574. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5575. if GetNextInstruction(hp_label, hp2) and
  5576. MatchInstruction(hp2,A_MOV,[]) and
  5577. (taicpu(hp2).oper[0]^.typ = top_const) and
  5578. (
  5579. (
  5580. (taicpu(hp2).oper[1]^.typ = top_reg)
  5581. {$ifdef i386}
  5582. { Under i386, ESI, EDI, EBP and ESP
  5583. don't have an 8-bit representation }
  5584. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5585. {$endif i386}
  5586. ) or (
  5587. {$ifdef i386}
  5588. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5589. {$endif i386}
  5590. (taicpu(hp2).opsize = S_B)
  5591. )
  5592. ) and
  5593. GetNextInstruction(hp2, hp3) and
  5594. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5595. (
  5596. (taicpu(hp3).opcode=A_RET) or
  5597. (
  5598. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5599. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5600. )
  5601. ) and
  5602. GetNextInstruction(hp3, hp4) and
  5603. SkipAligns(hp4, hp4) and
  5604. (hp4.typ=ait_label) and
  5605. (tai_label(hp4).labsym=JumpLoc) and
  5606. (
  5607. not (cs_opt_size in current_settings.optimizerswitches) or
  5608. { If the initial jump is the label's only reference, then it will
  5609. become a dead label if the other conditions are met and hence
  5610. remove at least 2 instructions, including a jump }
  5611. (JumpLoc.getrefs = 1)
  5612. ) and
  5613. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5614. that will be optimised out }
  5615. GetNextInstruction(hp4, hp5) and
  5616. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5617. (taicpu(hp5).oper[0]^.typ = top_const) and
  5618. (
  5619. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5620. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5621. ) and
  5622. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5623. GetNextInstruction(hp5,hp6) and
  5624. (
  5625. (hp6.typ<>ait_label) or
  5626. SkipLabels(hp6, hp6)
  5627. ) and
  5628. (hp6.typ=ait_instruction) then
  5629. begin
  5630. { First, let's look at the two jumps that are hp3 and hp6 }
  5631. if not
  5632. (
  5633. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5634. (
  5635. (taicpu(hp6).opcode=A_RET) or
  5636. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5637. )
  5638. ) then
  5639. { If condition is False, then the JMP/RET instructions matched conventionally }
  5640. begin
  5641. { See if one of the jumps can be instantly converted into a RET }
  5642. if (taicpu(hp3).opcode=A_JMP) then
  5643. begin
  5644. { Reuse hp5 }
  5645. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5646. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5647. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5648. Exit;
  5649. if MatchInstruction(hp5, A_RET, []) then
  5650. begin
  5651. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5652. ConvertJumpToRET(hp3, hp5);
  5653. Result := True;
  5654. end
  5655. else
  5656. Exit;
  5657. end;
  5658. if (taicpu(hp6).opcode=A_JMP) then
  5659. begin
  5660. { Reuse hp5 }
  5661. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5662. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5663. Exit;
  5664. if MatchInstruction(hp5, A_RET, []) then
  5665. begin
  5666. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5667. ConvertJumpToRET(hp6, hp5);
  5668. Result := True;
  5669. end
  5670. else
  5671. Exit;
  5672. end;
  5673. if not
  5674. (
  5675. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5676. (
  5677. (taicpu(hp6).opcode=A_RET) or
  5678. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5679. )
  5680. ) then
  5681. { Still doesn't match }
  5682. Exit;
  5683. end;
  5684. if (taicpu(hp2).oper[0]^.val = 1) then
  5685. begin
  5686. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5687. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5688. end
  5689. else
  5690. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5691. if taicpu(hp2).opsize=S_B then
  5692. begin
  5693. if taicpu(hp2).oper[1]^.typ = top_reg then
  5694. begin
  5695. SecondReg := taicpu(hp2).oper[1]^.reg;
  5696. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5697. end
  5698. else
  5699. begin
  5700. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5701. SecondReg := NR_NO;
  5702. end;
  5703. hp_pos := p;
  5704. hp_allocstart := hp4;
  5705. end
  5706. else
  5707. begin
  5708. { Will be a register because the size can't be S_B otherwise }
  5709. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5710. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5711. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5712. if (cs_opt_size in current_settings.optimizerswitches) then
  5713. begin
  5714. { Favour using MOVZX when optimising for size }
  5715. case taicpu(hp2).opsize of
  5716. S_W:
  5717. NewSize := S_BW;
  5718. S_L:
  5719. NewSize := S_BL;
  5720. {$ifdef x86_64}
  5721. S_Q:
  5722. begin
  5723. NewSize := S_BL;
  5724. { Will implicitly zero-extend to 64-bit }
  5725. setsubreg(SecondReg, R_SUBD);
  5726. end;
  5727. {$endif x86_64}
  5728. else
  5729. InternalError(2022101301);
  5730. end;
  5731. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5732. { Inserting it right before p will guarantee that the flags are also tracked }
  5733. Asml.InsertBefore(hp5, p);
  5734. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5735. hp_pos := hp5;
  5736. hp_allocstart := hp4;
  5737. end
  5738. else
  5739. begin
  5740. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5741. { Inserting it right before p will guarantee that the flags are also tracked }
  5742. Asml.InsertBefore(hp5, p);
  5743. hp_pos := p;
  5744. hp_allocstart := hp5;
  5745. end;
  5746. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5747. end;
  5748. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5749. taicpu(hp4).condition := taicpu(p).condition;
  5750. asml.InsertBefore(hp4, hp_pos);
  5751. if taicpu(hp3).is_jmp then
  5752. begin
  5753. JumpLoc.decrefs;
  5754. MakeUnconditional(taicpu(p));
  5755. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5756. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5757. end
  5758. else
  5759. ConvertJumpToRET(p, hp3);
  5760. if SecondReg <> NR_NO then
  5761. { Ensure the destination register is allocated over this region }
  5762. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5763. if (JumpLoc.getrefs = 0) then
  5764. RemoveDeadCodeAfterJump(hp3);
  5765. Result:=true;
  5766. exit;
  5767. end;
  5768. end;
  5769. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5770. var
  5771. hp1, hp2: tai;
  5772. ActiveReg: TRegister;
  5773. OldOffset: asizeint;
  5774. ThisConst: TCGInt;
  5775. function RegDeallocated: Boolean;
  5776. begin
  5777. TransferUsedRegs(TmpUsedRegs);
  5778. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5779. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5780. end;
  5781. begin
  5782. Result:=false;
  5783. hp1 := nil;
  5784. { replace
  5785. subX const,%reg1
  5786. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5787. dealloc %reg1
  5788. by
  5789. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5790. }
  5791. if MatchOpType(taicpu(p),top_const,top_reg) then
  5792. begin
  5793. ActiveReg := taicpu(p).oper[1]^.reg;
  5794. { Ensures the entire register was updated }
  5795. if (taicpu(p).opsize >= S_L) and
  5796. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5797. MatchInstruction(hp1,A_LEA,[]) and
  5798. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5799. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5800. (
  5801. { Cover the case where the register in the reference is also the destination register }
  5802. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5803. (
  5804. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5805. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5806. RegDeallocated
  5807. )
  5808. ) then
  5809. begin
  5810. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5811. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5812. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5813. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5814. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5815. {$ifdef x86_64}
  5816. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5817. begin
  5818. { Overflow; abort }
  5819. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5820. end
  5821. else
  5822. {$endif x86_64}
  5823. begin
  5824. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5825. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5826. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5827. RemoveCurrentP(p, hp1)
  5828. else
  5829. RemoveCurrentP(p);
  5830. result:=true;
  5831. Exit;
  5832. end;
  5833. end;
  5834. if (
  5835. { Save calling GetNextInstructionUsingReg again }
  5836. Assigned(hp1) or
  5837. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5838. ) and
  5839. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5840. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5841. begin
  5842. if taicpu(hp1).oper[0]^.typ = top_const then
  5843. begin
  5844. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5845. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5846. Result := True;
  5847. { Handle any overflows }
  5848. case taicpu(p).opsize of
  5849. S_B:
  5850. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5851. S_W:
  5852. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5853. S_L:
  5854. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5855. {$ifdef x86_64}
  5856. S_Q:
  5857. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5858. { Overflow; abort }
  5859. Result := False
  5860. else
  5861. taicpu(p).oper[0]^.val := ThisConst;
  5862. {$endif x86_64}
  5863. else
  5864. InternalError(2021102611);
  5865. end;
  5866. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5867. if Result then
  5868. begin
  5869. if (taicpu(p).oper[0]^.val < 0) and
  5870. (
  5871. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5872. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5873. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5874. ) then
  5875. begin
  5876. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5877. taicpu(p).opcode := A_SUB;
  5878. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5879. end
  5880. else
  5881. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5882. RemoveInstruction(hp1);
  5883. end;
  5884. end
  5885. else
  5886. begin
  5887. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5888. TransferUsedRegs(TmpUsedRegs);
  5889. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5890. hp2 := p;
  5891. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5892. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5893. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5894. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5895. begin
  5896. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5897. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5898. Asml.Remove(p);
  5899. Asml.InsertAfter(p, hp1);
  5900. p := hp1;
  5901. Result := True;
  5902. Exit;
  5903. end;
  5904. end;
  5905. end;
  5906. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5907. { * change "sub/add const1, reg" or "dec reg" followed by
  5908. "sub const2, reg" to one "sub ..., reg" }
  5909. {$ifdef i386}
  5910. if (taicpu(p).oper[0]^.val = 2) and
  5911. (ActiveReg = NR_ESP) and
  5912. { Don't do the sub/push optimization if the sub }
  5913. { comes from setting up the stack frame (JM) }
  5914. (not(GetLastInstruction(p,hp1)) or
  5915. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5916. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5917. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5918. begin
  5919. hp1 := tai(p.next);
  5920. while Assigned(hp1) and
  5921. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5922. not RegReadByInstruction(NR_ESP,hp1) and
  5923. not RegModifiedByInstruction(NR_ESP,hp1) do
  5924. hp1 := tai(hp1.next);
  5925. if Assigned(hp1) and
  5926. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5927. begin
  5928. taicpu(hp1).changeopsize(S_L);
  5929. if taicpu(hp1).oper[0]^.typ=top_reg then
  5930. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5931. hp1 := tai(p.next);
  5932. RemoveCurrentp(p, hp1);
  5933. Result:=true;
  5934. exit;
  5935. end;
  5936. end;
  5937. {$endif i386}
  5938. if DoArithCombineOpt(p) then
  5939. Result:=true;
  5940. end;
  5941. end;
  5942. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5943. var
  5944. TmpBool1,TmpBool2 : Boolean;
  5945. tmpref : treference;
  5946. hp1,hp2: tai;
  5947. mask: tcgint;
  5948. begin
  5949. Result:=false;
  5950. { All these optimisations work on "shl/sal const,%reg" }
  5951. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5952. Exit;
  5953. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5954. (taicpu(p).oper[0]^.val <= 3) then
  5955. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5956. begin
  5957. { should we check the next instruction? }
  5958. TmpBool1 := True;
  5959. { have we found an add/sub which could be
  5960. integrated in the lea? }
  5961. TmpBool2 := False;
  5962. reference_reset(tmpref,2,[]);
  5963. TmpRef.index := taicpu(p).oper[1]^.reg;
  5964. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5965. while TmpBool1 and
  5966. GetNextInstruction(p, hp1) and
  5967. (tai(hp1).typ = ait_instruction) and
  5968. ((((taicpu(hp1).opcode = A_ADD) or
  5969. (taicpu(hp1).opcode = A_SUB)) and
  5970. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5971. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5972. (((taicpu(hp1).opcode = A_INC) or
  5973. (taicpu(hp1).opcode = A_DEC)) and
  5974. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5975. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5976. ((taicpu(hp1).opcode = A_LEA) and
  5977. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5978. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5979. (not GetNextInstruction(hp1,hp2) or
  5980. not instrReadsFlags(hp2)) Do
  5981. begin
  5982. TmpBool1 := False;
  5983. if taicpu(hp1).opcode=A_LEA then
  5984. begin
  5985. if (TmpRef.base = NR_NO) and
  5986. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5987. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5988. { Segment register isn't a concern here }
  5989. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5990. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5991. begin
  5992. TmpBool1 := True;
  5993. TmpBool2 := True;
  5994. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5995. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5996. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5997. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5998. RemoveInstruction(hp1);
  5999. end
  6000. end
  6001. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6002. begin
  6003. TmpBool1 := True;
  6004. TmpBool2 := True;
  6005. case taicpu(hp1).opcode of
  6006. A_ADD:
  6007. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6008. A_SUB:
  6009. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6010. else
  6011. internalerror(2019050536);
  6012. end;
  6013. RemoveInstruction(hp1);
  6014. end
  6015. else
  6016. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6017. (((taicpu(hp1).opcode = A_ADD) and
  6018. (TmpRef.base = NR_NO)) or
  6019. (taicpu(hp1).opcode = A_INC) or
  6020. (taicpu(hp1).opcode = A_DEC)) then
  6021. begin
  6022. TmpBool1 := True;
  6023. TmpBool2 := True;
  6024. case taicpu(hp1).opcode of
  6025. A_ADD:
  6026. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6027. A_INC:
  6028. inc(TmpRef.offset);
  6029. A_DEC:
  6030. dec(TmpRef.offset);
  6031. else
  6032. internalerror(2019050535);
  6033. end;
  6034. RemoveInstruction(hp1);
  6035. end;
  6036. end;
  6037. if TmpBool2
  6038. {$ifndef x86_64}
  6039. or
  6040. ((current_settings.optimizecputype < cpu_Pentium2) and
  6041. (taicpu(p).oper[0]^.val <= 3) and
  6042. not(cs_opt_size in current_settings.optimizerswitches))
  6043. {$endif x86_64}
  6044. then
  6045. begin
  6046. if not(TmpBool2) and
  6047. (taicpu(p).oper[0]^.val=1) then
  6048. begin
  6049. taicpu(p).opcode := A_ADD;
  6050. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6051. end
  6052. else
  6053. begin
  6054. taicpu(p).opcode := A_LEA;
  6055. taicpu(p).loadref(0, TmpRef);
  6056. end;
  6057. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6058. Result := True;
  6059. end;
  6060. end
  6061. {$ifndef x86_64}
  6062. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6063. begin
  6064. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6065. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6066. (unlike shl, which is only Tairable in the U pipe) }
  6067. if taicpu(p).oper[0]^.val=1 then
  6068. begin
  6069. taicpu(p).opcode := A_ADD;
  6070. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6071. Result := True;
  6072. end
  6073. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6074. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6075. else if (taicpu(p).opsize = S_L) and
  6076. (taicpu(p).oper[0]^.val<= 3) then
  6077. begin
  6078. reference_reset(tmpref,2,[]);
  6079. TmpRef.index := taicpu(p).oper[1]^.reg;
  6080. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6081. taicpu(p).opcode := A_LEA;
  6082. taicpu(p).loadref(0, TmpRef);
  6083. Result := True;
  6084. end;
  6085. end
  6086. {$endif x86_64}
  6087. else if
  6088. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6089. (
  6090. (
  6091. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6092. SetAndTest(hp1, hp2)
  6093. {$ifdef x86_64}
  6094. ) or
  6095. (
  6096. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6097. GetNextInstruction(hp1, hp2) and
  6098. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6099. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6100. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6101. {$endif x86_64}
  6102. )
  6103. ) and
  6104. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6105. begin
  6106. { Change:
  6107. shl x, %reg1
  6108. mov -(1<<x), %reg2
  6109. and %reg2, %reg1
  6110. Or:
  6111. shl x, %reg1
  6112. and -(1<<x), %reg1
  6113. To just:
  6114. shl x, %reg1
  6115. Since the and operation only zeroes bits that are already zero from the shl operation
  6116. }
  6117. case taicpu(p).oper[0]^.val of
  6118. 8:
  6119. mask:=$FFFFFFFFFFFFFF00;
  6120. 16:
  6121. mask:=$FFFFFFFFFFFF0000;
  6122. 32:
  6123. mask:=$FFFFFFFF00000000;
  6124. 63:
  6125. { Constant pre-calculated to prevent overflow errors with Int64 }
  6126. mask:=$8000000000000000;
  6127. else
  6128. begin
  6129. if taicpu(p).oper[0]^.val >= 64 then
  6130. { Shouldn't happen realistically, since the register
  6131. is guaranteed to be set to zero at this point }
  6132. mask := 0
  6133. else
  6134. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6135. end;
  6136. end;
  6137. if taicpu(hp1).oper[0]^.val = mask then
  6138. begin
  6139. { Everything checks out, perform the optimisation, as long as
  6140. the FLAGS register isn't being used}
  6141. TransferUsedRegs(TmpUsedRegs);
  6142. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6143. {$ifdef x86_64}
  6144. if (hp1 <> hp2) then
  6145. begin
  6146. { "shl/mov/and" version }
  6147. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6148. { Don't do the optimisation if the FLAGS register is in use }
  6149. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6150. begin
  6151. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6152. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6153. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6154. begin
  6155. RemoveInstruction(hp1);
  6156. Result := True;
  6157. end;
  6158. { Only set Result to True if the 'mov' instruction was removed }
  6159. RemoveInstruction(hp2);
  6160. end;
  6161. end
  6162. else
  6163. {$endif x86_64}
  6164. begin
  6165. { "shl/and" version }
  6166. { Don't do the optimisation if the FLAGS register is in use }
  6167. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6168. begin
  6169. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6170. RemoveInstruction(hp1);
  6171. Result := True;
  6172. end;
  6173. end;
  6174. Exit;
  6175. end
  6176. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6177. begin
  6178. { Even if the mask doesn't allow for its removal, we might be
  6179. able to optimise the mask for the "shl/and" version, which
  6180. may permit other peephole optimisations }
  6181. {$ifdef DEBUG_AOPTCPU}
  6182. mask := taicpu(hp1).oper[0]^.val and mask;
  6183. if taicpu(hp1).oper[0]^.val <> mask then
  6184. begin
  6185. DebugMsg(
  6186. SPeepholeOptimization +
  6187. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6188. ' to $' + debug_tostr(mask) +
  6189. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6190. taicpu(hp1).oper[0]^.val := mask;
  6191. end;
  6192. {$else DEBUG_AOPTCPU}
  6193. { If debugging is off, just set the operand even if it's the same }
  6194. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6195. {$endif DEBUG_AOPTCPU}
  6196. end;
  6197. end;
  6198. {
  6199. change
  6200. shl/sal const,reg
  6201. <op> ...(...,reg,1),...
  6202. into
  6203. <op> ...(...,reg,1 shl const),...
  6204. if const in 1..3
  6205. }
  6206. if MatchOpType(taicpu(p), top_const, top_reg) and
  6207. (taicpu(p).oper[0]^.val in [1..3]) and
  6208. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6209. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6210. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6211. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6212. MatchOpType(taicpu(hp1),top_ref))
  6213. ) and
  6214. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6215. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6216. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6217. begin
  6218. TransferUsedRegs(TmpUsedRegs);
  6219. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6220. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6221. begin
  6222. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6223. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6224. RemoveCurrentP(p);
  6225. Result:=true;
  6226. end;
  6227. end;
  6228. end;
  6229. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6230. begin
  6231. case shr_size of
  6232. S_B:
  6233. { No valid combinations }
  6234. Result := False;
  6235. S_W:
  6236. Result := (Shift >= 8) and (movz_size = S_BW);
  6237. S_L:
  6238. Result :=
  6239. (Shift >= 24) { Any opsize is valid for this shift } or
  6240. ((Shift >= 16) and (movz_size = S_WL));
  6241. {$ifdef x86_64}
  6242. S_Q:
  6243. Result :=
  6244. (Shift >= 56) { Any opsize is valid for this shift } or
  6245. ((Shift >= 48) and (movz_size = S_WL));
  6246. {$endif x86_64}
  6247. else
  6248. InternalError(2022081510);
  6249. end;
  6250. end;
  6251. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6252. var
  6253. hp1, hp2: tai;
  6254. Shift: TCGInt;
  6255. LimitSize: Topsize;
  6256. DoNotMerge: Boolean;
  6257. begin
  6258. Result := False;
  6259. { All these optimisations work on "shr const,%reg" }
  6260. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6261. Exit;
  6262. DoNotMerge := False;
  6263. Shift := taicpu(p).oper[0]^.val;
  6264. LimitSize := taicpu(p).opsize;
  6265. hp1 := p;
  6266. repeat
  6267. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6268. Exit;
  6269. case taicpu(hp1).opcode of
  6270. A_TEST, A_CMP, A_Jcc:
  6271. { Skip over conditional jumps and relevant comparisons }
  6272. Continue;
  6273. A_MOVZX:
  6274. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6275. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6276. begin
  6277. { Since the original register is being read as is, subsequent
  6278. SHRs must not be merged at this point }
  6279. DoNotMerge := True;
  6280. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6281. begin
  6282. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6283. begin
  6284. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6285. taicpu(hp1).opcode := A_MOV;
  6286. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6287. case taicpu(hp1).opsize of
  6288. S_BW:
  6289. taicpu(hp1).opsize := S_W;
  6290. S_BL, S_WL:
  6291. taicpu(hp1).opsize := S_L;
  6292. else
  6293. InternalError(2022081503);
  6294. end;
  6295. { p itself hasn't changed, so no need to set Result to True }
  6296. Include(OptsToCheck, aoc_ForceNewIteration);
  6297. { See if there's anything afterwards that can be
  6298. optimised, since the input register hasn't changed }
  6299. Continue;
  6300. end;
  6301. { NOTE: If the MOVZX instruction reads and writes the same
  6302. register, defer this to the post-peephole optimisation stage }
  6303. Exit;
  6304. end;
  6305. end;
  6306. A_SHL, A_SAL, A_SHR:
  6307. if (taicpu(hp1).opsize <= LimitSize) and
  6308. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6309. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6310. begin
  6311. { Make sure the sizes don't exceed the register size limit
  6312. (measured by the shift value falling below the limit) }
  6313. if taicpu(hp1).opsize < LimitSize then
  6314. LimitSize := taicpu(hp1).opsize;
  6315. if taicpu(hp1).opcode = A_SHR then
  6316. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6317. else
  6318. begin
  6319. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6320. DoNotMerge := True;
  6321. end;
  6322. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6323. Exit;
  6324. { Since we've established that the combined shift is within
  6325. limits, we can actually combine the adjacent SHR
  6326. instructions even if they're different sizes }
  6327. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6328. begin
  6329. hp2 := tai(hp1.Previous);
  6330. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6331. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6332. RemoveInstruction(hp1);
  6333. hp1 := hp2;
  6334. { Though p has changed, only the constant has, and its
  6335. effects can still be detected on the next iteration of
  6336. the repeat..until loop }
  6337. Include(OptsToCheck, aoc_ForceNewIteration);
  6338. end;
  6339. { Move onto the next instruction }
  6340. Continue;
  6341. end;
  6342. else
  6343. ;
  6344. end;
  6345. Break;
  6346. until False;
  6347. end;
  6348. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6349. var
  6350. CurrentRef: TReference;
  6351. FullReg: TRegister;
  6352. hp1, hp2: tai;
  6353. begin
  6354. Result := False;
  6355. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6356. Exit;
  6357. { We assume you've checked if the operand is actually a reference by
  6358. this point. If it isn't, you'll most likely get an access violation }
  6359. CurrentRef := first_mov.oper[1]^.ref^;
  6360. { Memory must be aligned }
  6361. if (CurrentRef.offset mod 4) <> 0 then
  6362. Exit;
  6363. Inc(CurrentRef.offset);
  6364. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6365. if MatchOperand(second_mov.oper[0]^, 0) and
  6366. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6367. GetNextInstruction(second_mov, hp1) and
  6368. (hp1.typ = ait_instruction) and
  6369. (taicpu(hp1).opcode = A_MOV) and
  6370. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6371. (taicpu(hp1).oper[0]^.val = 0) then
  6372. begin
  6373. Inc(CurrentRef.offset);
  6374. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6375. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6376. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6377. begin
  6378. case taicpu(hp1).opsize of
  6379. S_B:
  6380. if GetNextInstruction(hp1, hp2) and
  6381. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6382. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6383. (taicpu(hp2).oper[0]^.val = 0) then
  6384. begin
  6385. Inc(CurrentRef.offset);
  6386. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6387. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6388. (taicpu(hp2).opsize = S_B) then
  6389. begin
  6390. RemoveInstruction(hp1);
  6391. RemoveInstruction(hp2);
  6392. first_mov.opsize := S_L;
  6393. if first_mov.oper[0]^.typ = top_reg then
  6394. begin
  6395. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6396. { Reuse second_mov as a MOVZX instruction }
  6397. second_mov.opcode := A_MOVZX;
  6398. second_mov.opsize := S_BL;
  6399. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6400. second_mov.loadreg(1, FullReg);
  6401. first_mov.oper[0]^.reg := FullReg;
  6402. asml.Remove(second_mov);
  6403. asml.InsertBefore(second_mov, first_mov);
  6404. end
  6405. else
  6406. { It's a value }
  6407. begin
  6408. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6409. RemoveInstruction(second_mov);
  6410. end;
  6411. Result := True;
  6412. Exit;
  6413. end;
  6414. end;
  6415. S_W:
  6416. begin
  6417. RemoveInstruction(hp1);
  6418. first_mov.opsize := S_L;
  6419. if first_mov.oper[0]^.typ = top_reg then
  6420. begin
  6421. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6422. { Reuse second_mov as a MOVZX instruction }
  6423. second_mov.opcode := A_MOVZX;
  6424. second_mov.opsize := S_BL;
  6425. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6426. second_mov.loadreg(1, FullReg);
  6427. first_mov.oper[0]^.reg := FullReg;
  6428. asml.Remove(second_mov);
  6429. asml.InsertBefore(second_mov, first_mov);
  6430. end
  6431. else
  6432. { It's a value }
  6433. begin
  6434. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6435. RemoveInstruction(second_mov);
  6436. end;
  6437. Result := True;
  6438. Exit;
  6439. end;
  6440. else
  6441. ;
  6442. end;
  6443. end;
  6444. end;
  6445. end;
  6446. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6447. { returns true if a "continue" should be done after this optimization }
  6448. var
  6449. hp1, hp2, hp3: tai;
  6450. begin
  6451. Result := false;
  6452. hp3 := nil;
  6453. if MatchOpType(taicpu(p),top_ref) and
  6454. GetNextInstruction(p, hp1) and
  6455. (hp1.typ = ait_instruction) and
  6456. (((taicpu(hp1).opcode = A_FLD) and
  6457. (taicpu(p).opcode = A_FSTP)) or
  6458. ((taicpu(p).opcode = A_FISTP) and
  6459. (taicpu(hp1).opcode = A_FILD))) and
  6460. MatchOpType(taicpu(hp1),top_ref) and
  6461. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6462. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6463. begin
  6464. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6465. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6466. GetNextInstruction(hp1, hp2) and
  6467. (((hp2.typ = ait_instruction) and
  6468. IsExitCode(hp2) and
  6469. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6470. not(assigned(current_procinfo.procdef.funcretsym) and
  6471. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6472. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6473. { fstp <temp>
  6474. fld <temp>
  6475. <dealloc> <temp>
  6476. }
  6477. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6478. (tai_tempalloc(hp2).allocation=false) and
  6479. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6480. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6481. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6482. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6483. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6484. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6485. )
  6486. )
  6487. ) then
  6488. begin
  6489. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6490. RemoveInstruction(hp1);
  6491. RemoveCurrentP(p, hp2);
  6492. { first case: exit code }
  6493. if hp2.typ = ait_instruction then
  6494. RemoveLastDeallocForFuncRes(p);
  6495. Result := true;
  6496. end
  6497. else
  6498. { we can do this only in fast math mode as fstp is rounding ...
  6499. ... still disabled as it breaks the compiler and/or rtl }
  6500. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6501. { ... or if another fstp equal to the first one follows }
  6502. GetNextInstruction(hp1,hp2) and
  6503. (hp2.typ = ait_instruction) and
  6504. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6505. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6506. begin
  6507. if SetAndTest(tai(hp2.next),hp3) and (hp3.typ = ait_tempalloc) and
  6508. (tai_tempalloc(hp3).allocation=false) and
  6509. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6510. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6511. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6512. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6513. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6514. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6515. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6516. ) then
  6517. begin
  6518. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6519. RemoveCurrentP(p,hp2);
  6520. RemoveInstruction(hp1);
  6521. Result := true;
  6522. end
  6523. else if { fst can't store an extended/comp value }
  6524. (taicpu(p).opsize <> S_FX) and
  6525. (taicpu(p).opsize <> S_IQ) then
  6526. begin
  6527. if (taicpu(p).opcode = A_FSTP) then
  6528. taicpu(p).opcode := A_FST
  6529. else
  6530. taicpu(p).opcode := A_FIST;
  6531. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6532. RemoveInstruction(hp1);
  6533. Result := true;
  6534. end;
  6535. end;
  6536. end;
  6537. end;
  6538. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6539. var
  6540. hp1, hp2, hp3: tai;
  6541. begin
  6542. result:=false;
  6543. if MatchOpType(taicpu(p),top_reg) and
  6544. GetNextInstruction(p, hp1) and
  6545. (hp1.typ = Ait_Instruction) and
  6546. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6547. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6548. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6549. { change to
  6550. fld reg fxxx reg,st
  6551. fxxxp st, st1 (hp1)
  6552. Remark: non commutative operations must be reversed!
  6553. }
  6554. begin
  6555. case taicpu(hp1).opcode Of
  6556. A_FMULP,A_FADDP,
  6557. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6558. begin
  6559. case taicpu(hp1).opcode Of
  6560. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6561. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6562. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6563. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6564. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6565. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6566. else
  6567. internalerror(2019050534);
  6568. end;
  6569. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6570. taicpu(hp1).oper[1]^.reg := NR_ST;
  6571. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6572. RemoveCurrentP(p, hp1);
  6573. Result:=true;
  6574. exit;
  6575. end;
  6576. else
  6577. ;
  6578. end;
  6579. end
  6580. else
  6581. if MatchOpType(taicpu(p),top_ref) and
  6582. GetNextInstruction(p, hp2) and
  6583. (hp2.typ = Ait_Instruction) and
  6584. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6585. (taicpu(p).opsize in [S_FS, S_FL]) and
  6586. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6587. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6588. if GetLastInstruction(p, hp1) and
  6589. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6590. MatchOpType(taicpu(hp1),top_ref) and
  6591. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6592. if ((taicpu(hp2).opcode = A_FMULP) or
  6593. (taicpu(hp2).opcode = A_FADDP)) then
  6594. { change to
  6595. fld/fst mem1 (hp1) fld/fst mem1
  6596. fld mem1 (p) fadd/
  6597. faddp/ fmul st, st
  6598. fmulp st, st1 (hp2) }
  6599. begin
  6600. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6601. RemoveCurrentP(p, hp1);
  6602. if (taicpu(hp2).opcode = A_FADDP) then
  6603. taicpu(hp2).opcode := A_FADD
  6604. else
  6605. taicpu(hp2).opcode := A_FMUL;
  6606. taicpu(hp2).oper[1]^.reg := NR_ST;
  6607. end
  6608. else
  6609. { change to
  6610. fld/fst mem1 (hp1) fld/fst mem1
  6611. fld mem1 (p) fld st
  6612. }
  6613. begin
  6614. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6615. taicpu(p).changeopsize(S_FL);
  6616. taicpu(p).loadreg(0,NR_ST);
  6617. end
  6618. else
  6619. begin
  6620. case taicpu(hp2).opcode Of
  6621. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6622. { change to
  6623. fld/fst mem1 (hp1) fld/fst mem1
  6624. fld mem2 (p) fxxx mem2
  6625. fxxxp st, st1 (hp2) }
  6626. begin
  6627. case taicpu(hp2).opcode Of
  6628. A_FADDP: taicpu(p).opcode := A_FADD;
  6629. A_FMULP: taicpu(p).opcode := A_FMUL;
  6630. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6631. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6632. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6633. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6634. else
  6635. internalerror(2019050533);
  6636. end;
  6637. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6638. RemoveInstruction(hp2);
  6639. end
  6640. else
  6641. ;
  6642. end
  6643. end
  6644. end;
  6645. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6646. begin
  6647. Result := condition_in(cond1, cond2) or
  6648. { Not strictly subsets due to the actual flags checked, but because we're
  6649. comparing integers, E is a subset of AE and GE and their aliases }
  6650. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6651. end;
  6652. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6653. var
  6654. v: TCGInt;
  6655. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6656. FirstMatch, TempBool: Boolean;
  6657. NewReg: TRegister;
  6658. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6659. begin
  6660. Result:=false;
  6661. { All these optimisations need a next instruction }
  6662. if not GetNextInstruction(p, hp1) then
  6663. Exit;
  6664. { Search for:
  6665. cmp ###,###
  6666. j(c1) @lbl1
  6667. ...
  6668. @lbl:
  6669. cmp ###,### (same comparison as above)
  6670. j(c2) @lbl2
  6671. If c1 is a subset of c2, change to:
  6672. cmp ###,###
  6673. j(c1) @lbl2
  6674. (@lbl1 may become a dead label as a result)
  6675. }
  6676. { Also handle cases where there are multiple jumps in a row }
  6677. p_jump := hp1;
  6678. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6679. begin
  6680. if IsJumpToLabel(taicpu(p_jump)) then
  6681. begin
  6682. { Do jump optimisations first in case the condition becomes
  6683. unnecessary }
  6684. TempBool := True;
  6685. if DoJumpOptimizations(p_jump, TempBool) or
  6686. not TempBool then
  6687. begin
  6688. if Assigned(p_jump) then
  6689. begin
  6690. hp1 := p_jump;
  6691. if (p_jump.typ in [ait_align]) then
  6692. SkipAligns(p_jump, p_jump);
  6693. { CollapseZeroDistJump will be set to the label after the
  6694. jump if it optimises, whether or not it's live or dead }
  6695. if (p_jump.typ in [ait_label]) and
  6696. not (tai_label(p_jump).labsym.is_used) then
  6697. GetNextInstruction(p_jump, p_jump);
  6698. end;
  6699. TransferUsedRegs(TmpUsedRegs);
  6700. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6701. if not Assigned(p_jump) or
  6702. (
  6703. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6704. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6705. ) then
  6706. begin
  6707. { No more conditional jumps; conditional statement is no longer required }
  6708. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6709. RemoveCurrentP(p);
  6710. Result := True;
  6711. Exit;
  6712. end;
  6713. hp1 := p_jump;
  6714. Include(OptsToCheck, aoc_ForceNewIteration);
  6715. Continue;
  6716. end;
  6717. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6718. if GetNextInstruction(p_jump, hp2) and
  6719. (
  6720. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6721. not TempBool
  6722. ) then
  6723. begin
  6724. hp1 := p_jump;
  6725. Include(OptsToCheck, aoc_ForceNewIteration);
  6726. Continue;
  6727. end;
  6728. p_label := nil;
  6729. if Assigned(JumpLabel) then
  6730. p_label := getlabelwithsym(JumpLabel);
  6731. if Assigned(p_label) and
  6732. GetNextInstruction(p_label, p_dist) and
  6733. MatchInstruction(p_dist, A_CMP, []) and
  6734. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6735. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6736. GetNextInstruction(p_dist, hp1_dist) and
  6737. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6738. begin
  6739. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6740. if JumpLabel = JumpLabel_dist then
  6741. { This is an infinite loop }
  6742. Exit;
  6743. { Best optimisation when the first condition is a subset (or equal) of the second }
  6744. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6745. begin
  6746. { Any registers used here will already be allocated }
  6747. if Assigned(JumpLabel) then
  6748. JumpLabel.DecRefs;
  6749. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6750. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6751. Result := True;
  6752. { Don't exit yet. Since p and p_jump haven't actually been
  6753. removed, we can check for more on this iteration }
  6754. end
  6755. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6756. GetNextInstruction(hp1_dist, hp1_label) and
  6757. SkipAligns(hp1_label, hp1_label) and
  6758. (hp1_label.typ = ait_label) then
  6759. begin
  6760. JumpLabel_far := tai_label(hp1_label).labsym;
  6761. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6762. { This is an infinite loop }
  6763. Exit;
  6764. if Assigned(JumpLabel_far) then
  6765. begin
  6766. { In this situation, if the first jump branches, the second one will never,
  6767. branch so change the destination label to after the second jump }
  6768. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6769. if Assigned(JumpLabel) then
  6770. JumpLabel.DecRefs;
  6771. JumpLabel_far.IncRefs;
  6772. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6773. Result := True;
  6774. { Don't exit yet. Since p and p_jump haven't actually been
  6775. removed, we can check for more on this iteration }
  6776. Continue;
  6777. end;
  6778. end;
  6779. end;
  6780. end;
  6781. { Search for:
  6782. cmp ###,###
  6783. j(c1) @lbl1
  6784. cmp ###,### (same as first)
  6785. Remove second cmp
  6786. }
  6787. if GetNextInstruction(p_jump, hp2) and
  6788. (
  6789. (
  6790. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6791. (
  6792. (
  6793. MatchOpType(taicpu(p), top_const, top_reg) and
  6794. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6795. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6796. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6797. ) or (
  6798. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6799. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6800. )
  6801. )
  6802. ) or (
  6803. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6804. MatchOperand(taicpu(p).oper[0]^, 0) and
  6805. (taicpu(p).oper[1]^.typ = top_reg) and
  6806. MatchInstruction(hp2, A_TEST, []) and
  6807. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6808. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6809. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6810. )
  6811. ) then
  6812. begin
  6813. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6814. RemoveInstruction(hp2);
  6815. Result := True;
  6816. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6817. end;
  6818. GetNextInstruction(p_jump, p_jump);
  6819. end;
  6820. {
  6821. Try to optimise the following:
  6822. cmp $x,### ($x and $y can be registers or constants)
  6823. je @lbl1 (only reference)
  6824. cmp $y,### (### are identical)
  6825. @Lbl:
  6826. sete %reg1
  6827. Change to:
  6828. cmp $x,###
  6829. sete %reg2 (allocate new %reg2)
  6830. cmp $y,###
  6831. sete %reg1
  6832. orb %reg2,%reg1
  6833. (dealloc %reg2)
  6834. This adds an instruction (so don't perform under -Os), but it removes
  6835. a conditional branch.
  6836. }
  6837. if not (cs_opt_size in current_settings.optimizerswitches) and
  6838. (
  6839. (hp1 = p_jump) or
  6840. GetNextInstruction(p, hp1)
  6841. ) and
  6842. MatchInstruction(hp1, A_Jcc, []) and
  6843. IsJumpToLabel(taicpu(hp1)) and
  6844. (taicpu(hp1).condition in [C_E, C_Z]) and
  6845. GetNextInstruction(hp1, hp2) and
  6846. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6847. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6848. { The first operand of CMP instructions can only be a register or
  6849. immediate anyway, so no need to check }
  6850. GetNextInstruction(hp2, p_label) and
  6851. (
  6852. (p_label.typ = ait_label) or
  6853. (
  6854. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6855. to potentially cut down on the iterations of Pass 1 }
  6856. MatchInstruction(p_label, A_Jcc, []) and
  6857. IsJumpToLabel(taicpu(p_label)) and
  6858. { Use p_dist to hold the jump briefly }
  6859. SetAndTest(p_label, p_dist) and
  6860. GetNextInstruction(p_dist, p_label) and
  6861. (p_label.typ = ait_label) and
  6862. (tai_label(p_label).labsym.getrefs >= 2) and
  6863. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6864. { We might as well collapse the jump now }
  6865. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6866. )
  6867. ) and
  6868. (tai_label(p_label).labsym.getrefs = 1) and
  6869. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6870. GetNextInstruction(p_label, p_dist) and
  6871. MatchInstruction(p_dist, A_SETcc, []) and
  6872. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6873. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6874. { Get the instruction after the SETcc instruction so we can
  6875. allocate a new register over the entire range }
  6876. GetNextInstruction(p_dist, hp1_dist) then
  6877. begin
  6878. TransferUsedRegs(TmpUsedRegs);
  6879. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6880. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6881. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6882. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6883. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6884. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6885. begin
  6886. { Register can appear in p if it's not used afterwards, so only
  6887. allocate between hp1 and hp1_dist }
  6888. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6889. if NewReg <> NR_NO then
  6890. begin
  6891. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6892. { Change the jump instruction into a SETcc instruction }
  6893. taicpu(hp1).opcode := A_SETcc;
  6894. taicpu(hp1).opsize := S_B;
  6895. taicpu(hp1).loadreg(0, NewReg);
  6896. { This is now a dead label }
  6897. tai_label(p_label).labsym.decrefs;
  6898. { Prefer adding before the next instruction so the FLAGS
  6899. register is deallocated first }
  6900. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6901. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6902. AsmL.InsertBefore(
  6903. hp2,
  6904. hp1_dist
  6905. );
  6906. { Make sure the new register is in use over the new instruction
  6907. (long-winded, but things work best when the FLAGS register
  6908. is not allocated here) }
  6909. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6910. Result := True;
  6911. { Don't exit yet, as p wasn't changed and hp1, while
  6912. modified, is still intact and might be optimised by the
  6913. SETcc optimisation below }
  6914. end;
  6915. end;
  6916. end;
  6917. if taicpu(p).oper[0]^.typ = top_const then
  6918. begin
  6919. if (taicpu(p).oper[0]^.val = 0) and
  6920. (taicpu(p).oper[1]^.typ = top_reg) and
  6921. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6922. begin
  6923. hp2 := p;
  6924. FirstMatch := True;
  6925. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6926. anything meaningful once it's converted to "test %reg,%reg";
  6927. additionally, some jumps will always (or never) branch, so
  6928. evaluate every jump immediately following the
  6929. comparison, optimising the conditions if possible.
  6930. Similarly with SETcc... those that are always set to 0 or 1
  6931. are changed to MOV instructions }
  6932. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6933. (
  6934. GetNextInstruction(hp2, hp1) and
  6935. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6936. ) do
  6937. begin
  6938. FirstMatch := False;
  6939. case taicpu(hp1).condition of
  6940. C_B, C_C, C_NAE, C_O:
  6941. { For B/NAE:
  6942. Will never branch since an unsigned integer can never be below zero
  6943. For C/O:
  6944. Result cannot overflow because 0 is being subtracted
  6945. }
  6946. begin
  6947. if taicpu(hp1).opcode = A_Jcc then
  6948. begin
  6949. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6950. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6951. RemoveInstruction(hp1);
  6952. { Since hp1 was deleted, hp2 must not be updated }
  6953. Continue;
  6954. end
  6955. else
  6956. begin
  6957. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6958. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6959. taicpu(hp1).opcode := A_MOV;
  6960. taicpu(hp1).ops := 2;
  6961. taicpu(hp1).condition := C_None;
  6962. taicpu(hp1).opsize := S_B;
  6963. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6964. taicpu(hp1).loadconst(0, 0);
  6965. end;
  6966. end;
  6967. C_BE, C_NA:
  6968. begin
  6969. { Will only branch if equal to zero }
  6970. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6971. taicpu(hp1).condition := C_E;
  6972. end;
  6973. C_A, C_NBE:
  6974. begin
  6975. { Will only branch if not equal to zero }
  6976. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6977. taicpu(hp1).condition := C_NE;
  6978. end;
  6979. C_AE, C_NB, C_NC, C_NO:
  6980. begin
  6981. { Will always branch }
  6982. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6983. if taicpu(hp1).opcode = A_Jcc then
  6984. begin
  6985. MakeUnconditional(taicpu(hp1));
  6986. { Any jumps/set that follow will now be dead code }
  6987. RemoveDeadCodeAfterJump(taicpu(hp1));
  6988. Break;
  6989. end
  6990. else
  6991. begin
  6992. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6993. taicpu(hp1).opcode := A_MOV;
  6994. taicpu(hp1).ops := 2;
  6995. taicpu(hp1).condition := C_None;
  6996. taicpu(hp1).opsize := S_B;
  6997. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6998. taicpu(hp1).loadconst(0, 1);
  6999. end;
  7000. end;
  7001. C_None:
  7002. InternalError(2020012201);
  7003. C_P, C_PE, C_NP, C_PO:
  7004. { We can't handle parity checks and they should never be generated
  7005. after a general-purpose CMP (it's used in some floating-point
  7006. comparisons that don't use CMP) }
  7007. InternalError(2020012202);
  7008. else
  7009. { Zero/Equality, Sign, their complements and all of the
  7010. signed comparisons do not need to be converted };
  7011. end;
  7012. hp2 := hp1;
  7013. end;
  7014. { Convert the instruction to a TEST }
  7015. taicpu(p).opcode := A_TEST;
  7016. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7017. Result := True;
  7018. Exit;
  7019. end
  7020. else if (taicpu(p).oper[0]^.val = 1) and
  7021. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7022. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7023. begin
  7024. { Convert; To:
  7025. cmp $1,r/m cmp $0,r/m
  7026. jl @lbl jle @lbl
  7027. (Also do inverted conditions)
  7028. }
  7029. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7030. taicpu(p).oper[0]^.val := 0;
  7031. if taicpu(hp1).condition in [C_L, C_NGE] then
  7032. taicpu(hp1).condition := C_LE
  7033. else
  7034. taicpu(hp1).condition := C_NLE;
  7035. { If the instruction is now "cmp $0,%reg", convert it to a
  7036. TEST (and effectively do the work of the "cmp $0,%reg" in
  7037. the block above)
  7038. }
  7039. if (taicpu(p).oper[1]^.typ = top_reg) then
  7040. begin
  7041. taicpu(p).opcode := A_TEST;
  7042. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7043. end;
  7044. Result := True;
  7045. Exit;
  7046. end
  7047. else if (taicpu(p).oper[1]^.typ = top_reg)
  7048. {$ifdef x86_64}
  7049. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7050. {$endif x86_64}
  7051. then
  7052. begin
  7053. { cmp register,$8000 neg register
  7054. je target --> jo target
  7055. .... only if register is deallocated before jump.}
  7056. case Taicpu(p).opsize of
  7057. S_B: v:=$80;
  7058. S_W: v:=$8000;
  7059. S_L: v:=qword($80000000);
  7060. else
  7061. internalerror(2013112905);
  7062. end;
  7063. if (taicpu(p).oper[0]^.val=v) and
  7064. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7065. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7066. begin
  7067. TransferUsedRegs(TmpUsedRegs);
  7068. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7069. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7070. begin
  7071. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7072. Taicpu(p).opcode:=A_NEG;
  7073. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7074. Taicpu(p).clearop(1);
  7075. Taicpu(p).ops:=1;
  7076. if Taicpu(hp1).condition=C_E then
  7077. Taicpu(hp1).condition:=C_O
  7078. else
  7079. Taicpu(hp1).condition:=C_NO;
  7080. Result:=true;
  7081. exit;
  7082. end;
  7083. end;
  7084. end;
  7085. end;
  7086. if TrySwapMovCmp(p, hp1) then
  7087. begin
  7088. Result := True;
  7089. Exit;
  7090. end;
  7091. end;
  7092. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7093. var
  7094. hp1: tai;
  7095. begin
  7096. {
  7097. remove the second (v)pxor from
  7098. pxor reg,reg
  7099. ...
  7100. pxor reg,reg
  7101. }
  7102. Result:=false;
  7103. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7104. MatchOpType(taicpu(p),top_reg,top_reg) and
  7105. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7106. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7107. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7108. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7109. begin
  7110. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7111. RemoveInstruction(hp1);
  7112. Result:=true;
  7113. Exit;
  7114. end
  7115. {
  7116. replace
  7117. pxor reg1,reg1
  7118. movapd/s reg1,reg2
  7119. dealloc reg1
  7120. by
  7121. pxor reg2,reg2
  7122. }
  7123. else if GetNextInstruction(p,hp1) and
  7124. { we mix single and double opperations here because we assume that the compiler
  7125. generates vmovapd only after double operations and vmovaps only after single operations }
  7126. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7127. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7128. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7129. (taicpu(p).oper[0]^.typ=top_reg) then
  7130. begin
  7131. TransferUsedRegs(TmpUsedRegs);
  7132. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7133. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7134. begin
  7135. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7136. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7137. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7138. RemoveInstruction(hp1);
  7139. result:=true;
  7140. end;
  7141. end;
  7142. end;
  7143. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7144. var
  7145. hp1: tai;
  7146. begin
  7147. {
  7148. remove the second (v)pxor from
  7149. (v)pxor reg,reg
  7150. ...
  7151. (v)pxor reg,reg
  7152. }
  7153. Result:=false;
  7154. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7155. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7156. begin
  7157. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7158. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7159. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7160. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7161. begin
  7162. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7163. RemoveInstruction(hp1);
  7164. Result:=true;
  7165. Exit;
  7166. end;
  7167. {$ifdef x86_64}
  7168. {
  7169. replace
  7170. vpxor reg1,reg1,reg1
  7171. vmov reg,mem
  7172. by
  7173. movq $0,mem
  7174. }
  7175. if GetNextInstruction(p,hp1) and
  7176. MatchInstruction(hp1,A_VMOVSD,[]) and
  7177. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7178. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7179. begin
  7180. TransferUsedRegs(TmpUsedRegs);
  7181. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7182. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7183. begin
  7184. taicpu(hp1).loadconst(0,0);
  7185. taicpu(hp1).opcode:=A_MOV;
  7186. taicpu(hp1).opsize:=S_Q;
  7187. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7188. RemoveCurrentP(p);
  7189. result:=true;
  7190. Exit;
  7191. end;
  7192. end;
  7193. {$endif x86_64}
  7194. end
  7195. {
  7196. replace
  7197. vpxor reg1,reg1,reg2
  7198. by
  7199. vpxor reg2,reg2,reg2
  7200. to avoid unncessary data dependencies
  7201. }
  7202. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7203. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7204. begin
  7205. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7206. { avoid unncessary data dependency }
  7207. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7208. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7209. result:=true;
  7210. exit;
  7211. end;
  7212. Result:=OptPass1VOP(p);
  7213. end;
  7214. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7215. var
  7216. hp1 : tai;
  7217. begin
  7218. result:=false;
  7219. { replace
  7220. IMul const,%mreg1,%mreg2
  7221. Mov %reg2,%mreg3
  7222. dealloc %mreg3
  7223. by
  7224. Imul const,%mreg1,%mreg23
  7225. }
  7226. if (taicpu(p).ops=3) and
  7227. GetNextInstruction(p,hp1) and
  7228. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7229. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7230. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7231. begin
  7232. TransferUsedRegs(TmpUsedRegs);
  7233. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7234. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7235. begin
  7236. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7237. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7238. RemoveInstruction(hp1);
  7239. result:=true;
  7240. end;
  7241. end;
  7242. end;
  7243. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7244. var
  7245. hp1 : tai;
  7246. begin
  7247. result:=false;
  7248. { replace
  7249. IMul %reg0,%reg1,%reg2
  7250. Mov %reg2,%reg3
  7251. dealloc %reg2
  7252. by
  7253. Imul %reg0,%reg1,%reg3
  7254. }
  7255. if GetNextInstruction(p,hp1) and
  7256. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7257. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7258. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7259. begin
  7260. TransferUsedRegs(TmpUsedRegs);
  7261. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7262. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7263. begin
  7264. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7265. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7266. RemoveInstruction(hp1);
  7267. result:=true;
  7268. end;
  7269. end;
  7270. end;
  7271. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7272. var
  7273. hp1: tai;
  7274. begin
  7275. Result:=false;
  7276. { get rid of
  7277. (v)cvtss2sd reg0,<reg1,>reg2
  7278. (v)cvtss2sd reg2,<reg2,>reg0
  7279. }
  7280. if GetNextInstruction(p,hp1) and
  7281. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7282. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7283. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7284. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7285. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7286. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7287. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7288. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7289. )
  7290. ) then
  7291. begin
  7292. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7293. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7294. begin
  7295. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7296. RemoveCurrentP(p);
  7297. RemoveInstruction(hp1);
  7298. end
  7299. else
  7300. begin
  7301. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7302. if taicpu(hp1).opcode=A_CVTSD2SS then
  7303. begin
  7304. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7305. taicpu(p).opcode:=A_MOVAPS;
  7306. end
  7307. else
  7308. begin
  7309. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7310. taicpu(p).opcode:=A_VMOVAPS;
  7311. end;
  7312. taicpu(p).ops:=2;
  7313. RemoveInstruction(hp1);
  7314. end;
  7315. Result:=true;
  7316. Exit;
  7317. end;
  7318. end;
  7319. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7320. var
  7321. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7322. ThisReg: TRegister;
  7323. begin
  7324. Result := False;
  7325. if not GetNextInstruction(p,hp1) then
  7326. Exit;
  7327. {
  7328. convert
  7329. j<c> .L1
  7330. mov 1,reg
  7331. jmp .L2
  7332. .L1
  7333. mov 0,reg
  7334. .L2
  7335. into
  7336. mov 0,reg
  7337. set<not(c)> reg
  7338. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7339. would destroy the flag contents
  7340. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7341. executed at the same time as a previous comparison.
  7342. set<not(c)> reg
  7343. movzx reg, reg
  7344. }
  7345. if MatchInstruction(hp1,A_MOV,[]) and
  7346. (taicpu(hp1).oper[0]^.typ = top_const) and
  7347. (
  7348. (
  7349. (taicpu(hp1).oper[1]^.typ = top_reg)
  7350. {$ifdef i386}
  7351. { Under i386, ESI, EDI, EBP and ESP
  7352. don't have an 8-bit representation }
  7353. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7354. {$endif i386}
  7355. ) or (
  7356. {$ifdef i386}
  7357. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7358. {$endif i386}
  7359. (taicpu(hp1).opsize = S_B)
  7360. )
  7361. ) and
  7362. GetNextInstruction(hp1,hp2) and
  7363. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7364. GetNextInstruction(hp2,hp3) and
  7365. SkipAligns(hp3, hp3) and
  7366. (hp3.typ=ait_label) and
  7367. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7368. GetNextInstruction(hp3,hp4) and
  7369. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7370. (taicpu(hp4).oper[0]^.typ = top_const) and
  7371. (
  7372. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7373. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7374. ) and
  7375. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7376. GetNextInstruction(hp4,hp5) and
  7377. SkipAligns(hp5, hp5) and
  7378. (hp5.typ=ait_label) and
  7379. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7380. begin
  7381. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7382. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7383. tai_label(hp3).labsym.DecRefs;
  7384. { If this isn't the only reference to the middle label, we can
  7385. still make a saving - only that the first jump and everything
  7386. that follows will remain. }
  7387. if (tai_label(hp3).labsym.getrefs = 0) then
  7388. begin
  7389. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7390. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7391. else
  7392. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7393. { remove jump, first label and second MOV (also catching any aligns) }
  7394. repeat
  7395. if not GetNextInstruction(hp2, hp3) then
  7396. InternalError(2021040810);
  7397. RemoveInstruction(hp2);
  7398. hp2 := hp3;
  7399. until hp2 = hp5;
  7400. { Don't decrement reference count before the removal loop
  7401. above, otherwise GetNextInstruction won't stop on the
  7402. the label }
  7403. tai_label(hp5).labsym.DecRefs;
  7404. end
  7405. else
  7406. begin
  7407. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7408. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7409. else
  7410. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7411. end;
  7412. taicpu(p).opcode:=A_SETcc;
  7413. taicpu(p).opsize:=S_B;
  7414. taicpu(p).is_jmp:=False;
  7415. if taicpu(hp1).opsize=S_B then
  7416. begin
  7417. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7418. if taicpu(hp1).oper[1]^.typ = top_reg then
  7419. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7420. RemoveInstruction(hp1);
  7421. end
  7422. else
  7423. begin
  7424. { Will be a register because the size can't be S_B otherwise }
  7425. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7426. taicpu(p).loadreg(0, ThisReg);
  7427. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7428. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7429. begin
  7430. case taicpu(hp1).opsize of
  7431. S_W:
  7432. taicpu(hp1).opsize := S_BW;
  7433. S_L:
  7434. taicpu(hp1).opsize := S_BL;
  7435. {$ifdef x86_64}
  7436. S_Q:
  7437. begin
  7438. taicpu(hp1).opsize := S_BL;
  7439. { Change the destination register to 32-bit }
  7440. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7441. end;
  7442. {$endif x86_64}
  7443. else
  7444. InternalError(2021040820);
  7445. end;
  7446. taicpu(hp1).opcode := A_MOVZX;
  7447. taicpu(hp1).loadreg(0, ThisReg);
  7448. end
  7449. else
  7450. begin
  7451. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7452. { hp1 is already a MOV instruction with the correct register }
  7453. taicpu(hp1).loadconst(0, 0);
  7454. { Inserting it right before p will guarantee that the flags are also tracked }
  7455. asml.Remove(hp1);
  7456. asml.InsertBefore(hp1, p);
  7457. end;
  7458. end;
  7459. Result:=true;
  7460. exit;
  7461. end
  7462. else if (hp1.typ = ait_label) then
  7463. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7464. end;
  7465. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7466. var
  7467. hp1, hp2, hp3: tai;
  7468. SourceRef, TargetRef: TReference;
  7469. CurrentReg: TRegister;
  7470. begin
  7471. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7472. if not UseAVX then
  7473. InternalError(2021100501);
  7474. Result := False;
  7475. { Look for the following to simplify:
  7476. vmovdqa/u x(mem1), %xmmreg
  7477. vmovdqa/u %xmmreg, y(mem2)
  7478. vmovdqa/u x+16(mem1), %xmmreg
  7479. vmovdqa/u %xmmreg, y+16(mem2)
  7480. Change to:
  7481. vmovdqa/u x(mem1), %ymmreg
  7482. vmovdqa/u %ymmreg, y(mem2)
  7483. vpxor %ymmreg, %ymmreg, %ymmreg
  7484. ( The VPXOR instruction is to zero the upper half, thus removing the
  7485. need to call the potentially expensive VZEROUPPER instruction. Other
  7486. peephole optimisations can remove VPXOR if it's unnecessary )
  7487. }
  7488. TransferUsedRegs(TmpUsedRegs);
  7489. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7490. { NOTE: In the optimisations below, if the references dictate that an
  7491. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7492. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7493. if (taicpu(p).opsize = S_XMM) and
  7494. MatchOpType(taicpu(p), top_ref, top_reg) and
  7495. GetNextInstruction(p, hp1) and
  7496. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7497. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7498. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7499. begin
  7500. SourceRef := taicpu(p).oper[0]^.ref^;
  7501. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7502. if GetNextInstruction(hp1, hp2) and
  7503. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7504. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7505. begin
  7506. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7507. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7508. Inc(SourceRef.offset, 16);
  7509. { Reuse the register in the first block move }
  7510. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7511. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7512. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7513. begin
  7514. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7515. Inc(TargetRef.offset, 16);
  7516. if GetNextInstruction(hp2, hp3) and
  7517. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7518. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7519. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7520. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7521. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7522. begin
  7523. { Update the register tracking to the new size }
  7524. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7525. { Remember that the offsets are 16 ahead }
  7526. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7527. if not (
  7528. ((SourceRef.offset mod 32) = 16) and
  7529. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7530. ) then
  7531. taicpu(p).opcode := A_VMOVDQU;
  7532. taicpu(p).opsize := S_YMM;
  7533. taicpu(p).oper[1]^.reg := CurrentReg;
  7534. if not (
  7535. ((TargetRef.offset mod 32) = 16) and
  7536. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7537. ) then
  7538. taicpu(hp1).opcode := A_VMOVDQU;
  7539. taicpu(hp1).opsize := S_YMM;
  7540. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7541. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7542. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7543. if (pi_uses_ymm in current_procinfo.flags) then
  7544. RemoveInstruction(hp2)
  7545. else
  7546. begin
  7547. taicpu(hp2).opcode := A_VPXOR;
  7548. taicpu(hp2).opsize := S_YMM;
  7549. taicpu(hp2).loadreg(0, CurrentReg);
  7550. taicpu(hp2).loadreg(1, CurrentReg);
  7551. taicpu(hp2).loadreg(2, CurrentReg);
  7552. taicpu(hp2).ops := 3;
  7553. end;
  7554. RemoveInstruction(hp3);
  7555. Result := True;
  7556. Exit;
  7557. end;
  7558. end
  7559. else
  7560. begin
  7561. { See if the next references are 16 less rather than 16 greater }
  7562. Dec(SourceRef.offset, 32); { -16 the other way }
  7563. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7564. begin
  7565. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7566. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7567. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7568. GetNextInstruction(hp2, hp3) and
  7569. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7570. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7571. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7572. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7573. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7574. begin
  7575. { Update the register tracking to the new size }
  7576. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7577. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7578. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7579. if not(
  7580. ((SourceRef.offset mod 32) = 0) and
  7581. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7582. ) then
  7583. taicpu(hp2).opcode := A_VMOVDQU;
  7584. taicpu(hp2).opsize := S_YMM;
  7585. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7586. if not (
  7587. ((TargetRef.offset mod 32) = 0) and
  7588. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7589. ) then
  7590. taicpu(hp3).opcode := A_VMOVDQU;
  7591. taicpu(hp3).opsize := S_YMM;
  7592. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7593. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7594. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7595. if (pi_uses_ymm in current_procinfo.flags) then
  7596. RemoveInstruction(hp1)
  7597. else
  7598. begin
  7599. taicpu(hp1).opcode := A_VPXOR;
  7600. taicpu(hp1).opsize := S_YMM;
  7601. taicpu(hp1).loadreg(0, CurrentReg);
  7602. taicpu(hp1).loadreg(1, CurrentReg);
  7603. taicpu(hp1).loadreg(2, CurrentReg);
  7604. taicpu(hp1).ops := 3;
  7605. Asml.Remove(hp1);
  7606. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7607. end;
  7608. RemoveCurrentP(p, hp2);
  7609. Result := True;
  7610. Exit;
  7611. end;
  7612. end;
  7613. end;
  7614. end;
  7615. end;
  7616. end;
  7617. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7618. var
  7619. hp2, hp3, first_assignment: tai;
  7620. IncCount, OperIdx: Integer;
  7621. OrigLabel: TAsmLabel;
  7622. begin
  7623. Count := 0;
  7624. Result := False;
  7625. first_assignment := nil;
  7626. if (LoopCount >= 20) then
  7627. begin
  7628. { Guard against infinite loops }
  7629. Exit;
  7630. end;
  7631. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7632. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7633. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7634. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7635. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7636. Exit;
  7637. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7638. {
  7639. change
  7640. jmp .L1
  7641. ...
  7642. .L1:
  7643. mov ##, ## ( multiple movs possible )
  7644. jmp/ret
  7645. into
  7646. mov ##, ##
  7647. jmp/ret
  7648. }
  7649. if not Assigned(hp1) then
  7650. begin
  7651. hp1 := GetLabelWithSym(OrigLabel);
  7652. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7653. Exit;
  7654. end;
  7655. hp2 := hp1;
  7656. while Assigned(hp2) do
  7657. begin
  7658. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7659. SkipLabels(hp2,hp2);
  7660. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7661. Break;
  7662. case taicpu(hp2).opcode of
  7663. A_MOVSS:
  7664. begin
  7665. if taicpu(hp2).ops = 0 then
  7666. { Wrong MOVSS }
  7667. Break;
  7668. Inc(Count);
  7669. if Count >= 5 then
  7670. { Too many to be worthwhile }
  7671. Break;
  7672. GetNextInstruction(hp2, hp2);
  7673. Continue;
  7674. end;
  7675. A_MOV,
  7676. A_MOVD,
  7677. A_MOVQ,
  7678. A_MOVSX,
  7679. {$ifdef x86_64}
  7680. A_MOVSXD,
  7681. {$endif x86_64}
  7682. A_MOVZX,
  7683. A_MOVAPS,
  7684. A_MOVUPS,
  7685. A_MOVSD,
  7686. A_MOVAPD,
  7687. A_MOVUPD,
  7688. A_MOVDQA,
  7689. A_MOVDQU,
  7690. A_VMOVSS,
  7691. A_VMOVAPS,
  7692. A_VMOVUPS,
  7693. A_VMOVSD,
  7694. A_VMOVAPD,
  7695. A_VMOVUPD,
  7696. A_VMOVDQA,
  7697. A_VMOVDQU:
  7698. begin
  7699. Inc(Count);
  7700. if Count >= 5 then
  7701. { Too many to be worthwhile }
  7702. Break;
  7703. GetNextInstruction(hp2, hp2);
  7704. Continue;
  7705. end;
  7706. A_JMP:
  7707. begin
  7708. { Guard against infinite loops }
  7709. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7710. Exit;
  7711. { Analyse this jump first in case it also duplicates assignments }
  7712. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7713. begin
  7714. { Something did change! }
  7715. Result := True;
  7716. Inc(Count, IncCount);
  7717. if Count >= 5 then
  7718. begin
  7719. { Too many to be worthwhile }
  7720. Exit;
  7721. end;
  7722. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7723. Break;
  7724. end;
  7725. Result := True;
  7726. Break;
  7727. end;
  7728. A_RET:
  7729. begin
  7730. Result := True;
  7731. Break;
  7732. end;
  7733. else
  7734. Break;
  7735. end;
  7736. end;
  7737. if Result then
  7738. begin
  7739. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7740. if Count = 0 then
  7741. begin
  7742. Result := False;
  7743. Exit;
  7744. end;
  7745. hp3 := p;
  7746. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7747. while True do
  7748. begin
  7749. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7750. SkipLabels(hp1,hp1);
  7751. if (hp1.typ <> ait_instruction) then
  7752. InternalError(2021040720);
  7753. case taicpu(hp1).opcode of
  7754. A_JMP:
  7755. begin
  7756. { Change the original jump to the new destination }
  7757. OrigLabel.decrefs;
  7758. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7759. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7760. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7761. if not Assigned(first_assignment) then
  7762. InternalError(2021040810)
  7763. else
  7764. p := first_assignment;
  7765. Exit;
  7766. end;
  7767. A_RET:
  7768. begin
  7769. { Now change the jump into a RET instruction }
  7770. ConvertJumpToRET(p, hp1);
  7771. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7772. if not Assigned(first_assignment) then
  7773. InternalError(2021040811)
  7774. else
  7775. p := first_assignment;
  7776. Exit;
  7777. end;
  7778. else
  7779. begin
  7780. { Duplicate the MOV instruction }
  7781. hp3:=tai(hp1.getcopy);
  7782. if first_assignment = nil then
  7783. first_assignment := hp3;
  7784. asml.InsertBefore(hp3, p);
  7785. { Make sure the compiler knows about any final registers written here }
  7786. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7787. with taicpu(hp3).oper[OperIdx]^ do
  7788. begin
  7789. case typ of
  7790. top_ref:
  7791. begin
  7792. if (ref^.base <> NR_NO) and
  7793. (getsupreg(ref^.base) <> RS_ESP) and
  7794. (getsupreg(ref^.base) <> RS_EBP)
  7795. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7796. then
  7797. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7798. if (ref^.index <> NR_NO) and
  7799. (getsupreg(ref^.index) <> RS_ESP) and
  7800. (getsupreg(ref^.index) <> RS_EBP)
  7801. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7802. (ref^.index <> ref^.base) then
  7803. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7804. end;
  7805. top_reg:
  7806. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7807. else
  7808. ;
  7809. end;
  7810. end;
  7811. end;
  7812. end;
  7813. if not GetNextInstruction(hp1, hp1) then
  7814. { Should have dropped out earlier }
  7815. InternalError(2021040710);
  7816. end;
  7817. end;
  7818. end;
  7819. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7820. var
  7821. hp2: tai;
  7822. X: Integer;
  7823. const
  7824. WriteOp: array[0..3] of set of TInsChange = (
  7825. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7826. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7827. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7828. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7829. RegWriteFlags: array[0..7] of set of TInsChange = (
  7830. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7831. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7832. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7833. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7834. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7835. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7836. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7837. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7838. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7839. begin
  7840. { If we have something like:
  7841. cmp ###,%reg1
  7842. mov 0,%reg2
  7843. And no modified registers are shared, move the instruction to before
  7844. the comparison as this means it can be optimised without worrying
  7845. about the FLAGS register. (CMP/MOV is generated by
  7846. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7847. As long as the second instruction doesn't use the flags or one of the
  7848. registers used by CMP or TEST (also check any references that use the
  7849. registers), then it can be moved prior to the comparison.
  7850. }
  7851. Result := False;
  7852. if (hp1.typ <> ait_instruction) or
  7853. taicpu(hp1).is_jmp or
  7854. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7855. Exit;
  7856. { NOP is a pipeline fence, likely marking the beginning of the function
  7857. epilogue, so drop out. Similarly, drop out if POP or RET are
  7858. encountered }
  7859. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7860. Exit;
  7861. if (taicpu(hp1).opcode = A_MOVSS) and
  7862. (taicpu(hp1).ops = 0) then
  7863. { Wrong MOVSS }
  7864. Exit;
  7865. { Check for writes to specific registers first }
  7866. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7867. for X := 0 to 7 do
  7868. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7869. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7870. Exit;
  7871. for X := 0 to taicpu(hp1).ops - 1 do
  7872. begin
  7873. { Check to see if this operand writes to something }
  7874. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7875. { And matches something in the CMP/TEST instruction }
  7876. (
  7877. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7878. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7879. (
  7880. { If it's a register, make sure the register written to doesn't
  7881. appear in the cmp instruction as part of a reference }
  7882. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7883. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7884. )
  7885. ) then
  7886. Exit;
  7887. end;
  7888. { The instruction can be safely moved }
  7889. asml.Remove(hp1);
  7890. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7891. can be optimised into "xor %reg,%reg" later }
  7892. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7893. asml.InsertBefore(hp1, hp2)
  7894. else
  7895. { Note, if p.Previous is nil (even if it should logically never be the
  7896. case), FindRegAllocBackward immediately exits with False and so we
  7897. safely land here (we can't just pass p because FindRegAllocBackward
  7898. immediately exits on an instruction). [Kit] }
  7899. asml.InsertBefore(hp1, p);
  7900. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7901. for X := 0 to taicpu(hp1).ops - 1 do
  7902. case taicpu(hp1).oper[X]^.typ of
  7903. top_reg:
  7904. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7905. top_ref:
  7906. begin
  7907. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7908. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7909. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7910. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7911. end;
  7912. else
  7913. ;
  7914. end;
  7915. if taicpu(hp1).opcode = A_LEA then
  7916. { The flags will be overwritten by the CMP/TEST instruction }
  7917. ConvertLEA(taicpu(hp1));
  7918. Result := True;
  7919. end;
  7920. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7921. function IsXCHGAcceptable: Boolean; inline;
  7922. begin
  7923. { Always accept if optimising for size }
  7924. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7925. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7926. than 3, so it becomes a saving compared to three MOVs with two of
  7927. them able to execute simultaneously. [Kit] }
  7928. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  7929. end;
  7930. var
  7931. NewRef: TReference;
  7932. hp1, hp2, hp3, hp4: Tai;
  7933. {$ifndef x86_64}
  7934. OperIdx: Integer;
  7935. {$endif x86_64}
  7936. NewInstr : Taicpu;
  7937. NewAligh : Tai_align;
  7938. DestLabel: TAsmLabel;
  7939. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7940. var
  7941. NextInstr: tai;
  7942. begin
  7943. Result := False;
  7944. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7945. if not GetNextInstruction(InputInstr, NextInstr) or
  7946. (
  7947. { The FLAGS register isn't always tracked properly, so do not
  7948. perform this optimisation if a conditional statement follows }
  7949. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7950. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7951. ) then
  7952. begin
  7953. reference_reset(NewRef, 1, []);
  7954. NewRef.base := taicpu(p).oper[0]^.reg;
  7955. NewRef.scalefactor := 1;
  7956. if taicpu(InputInstr).opcode = A_ADD then
  7957. begin
  7958. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7959. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7960. end
  7961. else
  7962. begin
  7963. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7964. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7965. end;
  7966. taicpu(p).opcode := A_LEA;
  7967. taicpu(p).loadref(0, NewRef);
  7968. RemoveInstruction(InputInstr);
  7969. Result := True;
  7970. end;
  7971. end;
  7972. begin
  7973. Result:=false;
  7974. { This optimisation adds an instruction, so only do it for speed }
  7975. if not (cs_opt_size in current_settings.optimizerswitches) and
  7976. MatchOpType(taicpu(p), top_const, top_reg) and
  7977. (taicpu(p).oper[0]^.val = 0) then
  7978. begin
  7979. { To avoid compiler warning }
  7980. DestLabel := nil;
  7981. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7982. InternalError(2021040750);
  7983. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7984. Exit;
  7985. case hp1.typ of
  7986. ait_align,
  7987. ait_label:
  7988. begin
  7989. { Change:
  7990. mov $0,%reg mov $0,%reg
  7991. @Lbl1: @Lbl1:
  7992. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7993. je @Lbl2 jne @Lbl2
  7994. To: To:
  7995. mov $0,%reg mov $0,%reg
  7996. jmp @Lbl2 jmp @Lbl3
  7997. (align) (align)
  7998. @Lbl1: @Lbl1:
  7999. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8000. je @Lbl2 je @Lbl2
  8001. @Lbl3: <-- Only if label exists
  8002. (Not if it's optimised for size)
  8003. }
  8004. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8005. Exit;
  8006. if (hp2.typ = ait_instruction) and
  8007. (
  8008. { Register sizes must exactly match }
  8009. (
  8010. (taicpu(hp2).opcode = A_CMP) and
  8011. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8012. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8013. ) or (
  8014. (taicpu(hp2).opcode = A_TEST) and
  8015. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8016. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8017. )
  8018. ) and GetNextInstruction(hp2, hp3) and
  8019. (hp3.typ = ait_instruction) and
  8020. (taicpu(hp3).opcode = A_JCC) and
  8021. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  8022. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8023. begin
  8024. { Check condition of jump }
  8025. { Always true? }
  8026. if condition_in(C_E, taicpu(hp3).condition) then
  8027. begin
  8028. { Copy label symbol and obtain matching label entry for the
  8029. conditional jump, as this will be our destination}
  8030. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8031. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8032. Result := True;
  8033. end
  8034. { Always false? }
  8035. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8036. begin
  8037. { This is only worth it if there's a jump to take }
  8038. case hp2.typ of
  8039. ait_instruction:
  8040. begin
  8041. if taicpu(hp2).opcode = A_JMP then
  8042. begin
  8043. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8044. { An unconditional jump follows the conditional jump which will always be false,
  8045. so use this jump's destination for the new jump }
  8046. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8047. Result := True;
  8048. end
  8049. else if taicpu(hp2).opcode = A_JCC then
  8050. begin
  8051. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8052. if condition_in(C_E, taicpu(hp2).condition) then
  8053. begin
  8054. { A second conditional jump follows the conditional jump which will always be false,
  8055. while the second jump is always True, so use this jump's destination for the new jump }
  8056. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8057. Result := True;
  8058. end;
  8059. { Don't risk it if the jump isn't always true (Result remains False) }
  8060. end;
  8061. end;
  8062. else
  8063. { If anything else don't optimise };
  8064. end;
  8065. end;
  8066. if Result then
  8067. begin
  8068. { Just so we have something to insert as a paremeter}
  8069. reference_reset(NewRef, 1, []);
  8070. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8071. { Now actually load the correct parameter (this also
  8072. increases the reference count) }
  8073. NewInstr.loadsymbol(0, DestLabel, 0);
  8074. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8075. begin
  8076. { Get instruction before original label (may not be p under -O3) }
  8077. if not GetLastInstruction(hp1, hp2) then
  8078. { Shouldn't fail here }
  8079. InternalError(2021040701);
  8080. { Before the aligns too }
  8081. while (hp2.typ = ait_align) do
  8082. if not GetLastInstruction(hp2, hp2) then
  8083. { Shouldn't fail here }
  8084. InternalError(2021040702);
  8085. end
  8086. else
  8087. hp2 := p;
  8088. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8089. AsmL.InsertAfter(NewInstr, hp2);
  8090. { Add new alignment field }
  8091. (* AsmL.InsertAfter(
  8092. cai_align.create_max(
  8093. current_settings.alignment.jumpalign,
  8094. current_settings.alignment.jumpalignskipmax
  8095. ),
  8096. NewInstr
  8097. ); *)
  8098. end;
  8099. Exit;
  8100. end;
  8101. end;
  8102. else
  8103. ;
  8104. end;
  8105. end;
  8106. if not GetNextInstruction(p, hp1) then
  8107. Exit;
  8108. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8109. and DoMovCmpMemOpt(p, hp1, True) then
  8110. begin
  8111. Result := True;
  8112. Exit;
  8113. end
  8114. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8115. begin
  8116. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8117. further, but we can't just put this jump optimisation in pass 1
  8118. because it tends to perform worse when conditional jumps are
  8119. nearby (e.g. when converting CMOV instructions). [Kit] }
  8120. if OptPass2JMP(hp1) then
  8121. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8122. Result := OptPass1MOV(p)
  8123. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8124. returned True and the instruction is still a MOV, thus checking
  8125. the optimisations below }
  8126. { If OptPass2JMP returned False, no optimisations were done to
  8127. the jump and there are no further optimisations that can be done
  8128. to the MOV instruction on this pass }
  8129. end
  8130. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8131. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8132. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8133. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8134. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8135. begin
  8136. { Change:
  8137. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8138. addl/q $x,%reg2 subl/q $x,%reg2
  8139. To:
  8140. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8141. }
  8142. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8143. { be lazy, checking separately for sub would be slightly better }
  8144. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8145. begin
  8146. TransferUsedRegs(TmpUsedRegs);
  8147. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8148. if TryMovArith2Lea(hp1) then
  8149. begin
  8150. Result := True;
  8151. Exit;
  8152. end
  8153. end
  8154. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8155. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8156. { Same as above, but also adds or subtracts to %reg2 in between.
  8157. It's still valid as long as the flags aren't in use }
  8158. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8159. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8160. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8161. { be lazy, checking separately for sub would be slightly better }
  8162. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8163. begin
  8164. TransferUsedRegs(TmpUsedRegs);
  8165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8166. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8167. if TryMovArith2Lea(hp2) then
  8168. begin
  8169. Result := True;
  8170. Exit;
  8171. end;
  8172. end;
  8173. end
  8174. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8175. {$ifdef x86_64}
  8176. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8177. {$else x86_64}
  8178. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8179. {$endif x86_64}
  8180. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8181. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8182. { mov reg1, reg2 mov reg1, reg2
  8183. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8184. begin
  8185. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8186. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8187. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8188. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8189. TransferUsedRegs(TmpUsedRegs);
  8190. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8191. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8192. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8193. then
  8194. begin
  8195. RemoveCurrentP(p, hp1);
  8196. Result:=true;
  8197. end;
  8198. exit;
  8199. end
  8200. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8201. IsXCHGAcceptable and
  8202. { XCHG doesn't support 8-byte registers }
  8203. (taicpu(p).opsize <> S_B) and
  8204. MatchInstruction(hp1, A_MOV, []) and
  8205. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8206. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8207. GetNextInstruction(hp1, hp2) and
  8208. MatchInstruction(hp2, A_MOV, []) and
  8209. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8210. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8211. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8212. begin
  8213. { mov %reg1,%reg2
  8214. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8215. mov %reg2,%reg3
  8216. (%reg2 not used afterwards)
  8217. Note that xchg takes 3 cycles to execute, and generally mov's take
  8218. only one cycle apiece, but the first two mov's can be executed in
  8219. parallel, only taking 2 cycles overall. Older processors should
  8220. therefore only optimise for size. [Kit]
  8221. }
  8222. TransferUsedRegs(TmpUsedRegs);
  8223. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8224. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8225. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8226. begin
  8227. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8228. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8229. taicpu(hp1).opcode := A_XCHG;
  8230. RemoveCurrentP(p, hp1);
  8231. RemoveInstruction(hp2);
  8232. Result := True;
  8233. Exit;
  8234. end;
  8235. end
  8236. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8237. MatchInstruction(hp1, A_SAR, []) then
  8238. begin
  8239. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8240. begin
  8241. { the use of %edx also covers the opsize being S_L }
  8242. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8243. begin
  8244. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8245. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8246. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8247. begin
  8248. { Change:
  8249. movl %eax,%edx
  8250. sarl $31,%edx
  8251. To:
  8252. cltd
  8253. }
  8254. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8255. RemoveInstruction(hp1);
  8256. taicpu(p).opcode := A_CDQ;
  8257. taicpu(p).opsize := S_NO;
  8258. taicpu(p).clearop(1);
  8259. taicpu(p).clearop(0);
  8260. taicpu(p).ops:=0;
  8261. Result := True;
  8262. end
  8263. else if (cs_opt_size in current_settings.optimizerswitches) and
  8264. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8265. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8266. begin
  8267. { Change:
  8268. movl %edx,%eax
  8269. sarl $31,%edx
  8270. To:
  8271. movl %edx,%eax
  8272. cltd
  8273. Note that this creates a dependency between the two instructions,
  8274. so only perform if optimising for size.
  8275. }
  8276. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8277. taicpu(hp1).opcode := A_CDQ;
  8278. taicpu(hp1).opsize := S_NO;
  8279. taicpu(hp1).clearop(1);
  8280. taicpu(hp1).clearop(0);
  8281. taicpu(hp1).ops:=0;
  8282. end;
  8283. {$ifndef x86_64}
  8284. end
  8285. { Don't bother if CMOV is supported, because a more optimal
  8286. sequence would have been generated for the Abs() intrinsic }
  8287. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8288. { the use of %eax also covers the opsize being S_L }
  8289. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8290. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8291. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8292. GetNextInstruction(hp1, hp2) and
  8293. MatchInstruction(hp2, A_XOR, [S_L]) and
  8294. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8295. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8296. GetNextInstruction(hp2, hp3) and
  8297. MatchInstruction(hp3, A_SUB, [S_L]) and
  8298. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8299. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8300. begin
  8301. { Change:
  8302. movl %eax,%edx
  8303. sarl $31,%eax
  8304. xorl %eax,%edx
  8305. subl %eax,%edx
  8306. (Instruction that uses %edx)
  8307. (%eax deallocated)
  8308. (%edx deallocated)
  8309. To:
  8310. cltd
  8311. xorl %edx,%eax <-- Note the registers have swapped
  8312. subl %edx,%eax
  8313. (Instruction that uses %eax) <-- %eax rather than %edx
  8314. }
  8315. TransferUsedRegs(TmpUsedRegs);
  8316. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8317. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8318. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8319. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8320. begin
  8321. if GetNextInstruction(hp3, hp4) and
  8322. not RegModifiedByInstruction(NR_EDX, hp4) and
  8323. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8324. begin
  8325. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8326. taicpu(p).opcode := A_CDQ;
  8327. taicpu(p).clearop(1);
  8328. taicpu(p).clearop(0);
  8329. taicpu(p).ops:=0;
  8330. RemoveInstruction(hp1);
  8331. taicpu(hp2).loadreg(0, NR_EDX);
  8332. taicpu(hp2).loadreg(1, NR_EAX);
  8333. taicpu(hp3).loadreg(0, NR_EDX);
  8334. taicpu(hp3).loadreg(1, NR_EAX);
  8335. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8336. { Convert references in the following instruction (hp4) from %edx to %eax }
  8337. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8338. with taicpu(hp4).oper[OperIdx]^ do
  8339. case typ of
  8340. top_reg:
  8341. if getsupreg(reg) = RS_EDX then
  8342. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8343. top_ref:
  8344. begin
  8345. if getsupreg(reg) = RS_EDX then
  8346. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8347. if getsupreg(reg) = RS_EDX then
  8348. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8349. end;
  8350. else
  8351. ;
  8352. end;
  8353. end;
  8354. end;
  8355. {$else x86_64}
  8356. end;
  8357. end
  8358. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8359. { the use of %rdx also covers the opsize being S_Q }
  8360. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8361. begin
  8362. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8363. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8364. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8365. begin
  8366. { Change:
  8367. movq %rax,%rdx
  8368. sarq $63,%rdx
  8369. To:
  8370. cqto
  8371. }
  8372. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8373. RemoveInstruction(hp1);
  8374. taicpu(p).opcode := A_CQO;
  8375. taicpu(p).opsize := S_NO;
  8376. taicpu(p).clearop(1);
  8377. taicpu(p).clearop(0);
  8378. taicpu(p).ops:=0;
  8379. Result := True;
  8380. end
  8381. else if (cs_opt_size in current_settings.optimizerswitches) and
  8382. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8383. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8384. begin
  8385. { Change:
  8386. movq %rdx,%rax
  8387. sarq $63,%rdx
  8388. To:
  8389. movq %rdx,%rax
  8390. cqto
  8391. Note that this creates a dependency between the two instructions,
  8392. so only perform if optimising for size.
  8393. }
  8394. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8395. taicpu(hp1).opcode := A_CQO;
  8396. taicpu(hp1).opsize := S_NO;
  8397. taicpu(hp1).clearop(1);
  8398. taicpu(hp1).clearop(0);
  8399. taicpu(hp1).ops:=0;
  8400. {$endif x86_64}
  8401. end;
  8402. end;
  8403. end
  8404. else if MatchInstruction(hp1, A_MOV, []) and
  8405. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8406. { Though "GetNextInstruction" could be factored out, along with
  8407. the instructions that depend on hp2, it is an expensive call that
  8408. should be delayed for as long as possible, hence we do cheaper
  8409. checks first that are likely to be False. [Kit] }
  8410. begin
  8411. if (
  8412. (
  8413. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8414. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8415. (
  8416. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8417. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8418. )
  8419. ) or
  8420. (
  8421. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8422. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8423. (
  8424. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8425. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8426. )
  8427. )
  8428. ) and
  8429. GetNextInstruction(hp1, hp2) and
  8430. MatchInstruction(hp2, A_SAR, []) and
  8431. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8432. begin
  8433. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8434. begin
  8435. { Change:
  8436. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8437. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8438. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8439. To:
  8440. movl r/m,%eax <- Note the change in register
  8441. cltd
  8442. }
  8443. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8444. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8445. taicpu(p).loadreg(1, NR_EAX);
  8446. taicpu(hp1).opcode := A_CDQ;
  8447. taicpu(hp1).clearop(1);
  8448. taicpu(hp1).clearop(0);
  8449. taicpu(hp1).ops:=0;
  8450. RemoveInstruction(hp2);
  8451. (*
  8452. {$ifdef x86_64}
  8453. end
  8454. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8455. { This code sequence does not get generated - however it might become useful
  8456. if and when 128-bit signed integer types make an appearance, so the code
  8457. is kept here for when it is eventually needed. [Kit] }
  8458. (
  8459. (
  8460. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8461. (
  8462. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8463. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8464. )
  8465. ) or
  8466. (
  8467. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8468. (
  8469. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8470. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8471. )
  8472. )
  8473. ) and
  8474. GetNextInstruction(hp1, hp2) and
  8475. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8476. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8477. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8478. begin
  8479. { Change:
  8480. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8481. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8482. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8483. To:
  8484. movq r/m,%rax <- Note the change in register
  8485. cqto
  8486. }
  8487. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8488. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8489. taicpu(p).loadreg(1, NR_RAX);
  8490. taicpu(hp1).opcode := A_CQO;
  8491. taicpu(hp1).clearop(1);
  8492. taicpu(hp1).clearop(0);
  8493. taicpu(hp1).ops:=0;
  8494. RemoveInstruction(hp2);
  8495. {$endif x86_64}
  8496. *)
  8497. end;
  8498. end;
  8499. {$ifdef x86_64}
  8500. end
  8501. else if (taicpu(p).opsize = S_L) and
  8502. (taicpu(p).oper[1]^.typ = top_reg) and
  8503. (
  8504. MatchInstruction(hp1, A_MOV,[]) and
  8505. (taicpu(hp1).opsize = S_L) and
  8506. (taicpu(hp1).oper[1]^.typ = top_reg)
  8507. ) and (
  8508. GetNextInstruction(hp1, hp2) and
  8509. (tai(hp2).typ=ait_instruction) and
  8510. (taicpu(hp2).opsize = S_Q) and
  8511. (
  8512. (
  8513. MatchInstruction(hp2, A_ADD,[]) and
  8514. (taicpu(hp2).opsize = S_Q) and
  8515. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8516. (
  8517. (
  8518. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8519. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8520. ) or (
  8521. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8522. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8523. )
  8524. )
  8525. ) or (
  8526. MatchInstruction(hp2, A_LEA,[]) and
  8527. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8528. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8529. (
  8530. (
  8531. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8532. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8533. ) or (
  8534. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8535. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8536. )
  8537. ) and (
  8538. (
  8539. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8540. ) or (
  8541. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8542. )
  8543. )
  8544. )
  8545. )
  8546. ) and (
  8547. GetNextInstruction(hp2, hp3) and
  8548. MatchInstruction(hp3, A_SHR,[]) and
  8549. (taicpu(hp3).opsize = S_Q) and
  8550. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8551. (taicpu(hp3).oper[0]^.val = 1) and
  8552. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8553. ) then
  8554. begin
  8555. { Change movl x, reg1d movl x, reg1d
  8556. movl y, reg2d movl y, reg2d
  8557. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8558. shrq $1, reg1q shrq $1, reg1q
  8559. ( reg1d and reg2d can be switched around in the first two instructions )
  8560. To movl x, reg1d
  8561. addl y, reg1d
  8562. rcrl $1, reg1d
  8563. This corresponds to the common expression (x + y) shr 1, where
  8564. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8565. smaller code, but won't account for x + y causing an overflow). [Kit]
  8566. }
  8567. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8568. { Change first MOV command to have the same register as the final output }
  8569. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8570. else
  8571. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8572. { Change second MOV command to an ADD command. This is easier than
  8573. converting the existing command because it means we don't have to
  8574. touch 'y', which might be a complicated reference, and also the
  8575. fact that the third command might either be ADD or LEA. [Kit] }
  8576. taicpu(hp1).opcode := A_ADD;
  8577. { Delete old ADD/LEA instruction }
  8578. RemoveInstruction(hp2);
  8579. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8580. taicpu(hp3).opcode := A_RCR;
  8581. taicpu(hp3).changeopsize(S_L);
  8582. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8583. {$endif x86_64}
  8584. end;
  8585. if FuncMov2Func(p, hp1) then
  8586. begin
  8587. Result := True;
  8588. Exit;
  8589. end;
  8590. end;
  8591. {$push}
  8592. {$q-}{$r-}
  8593. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8594. var
  8595. ThisReg: TRegister;
  8596. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8597. TargetSubReg: TSubRegister;
  8598. hp1, hp2: tai;
  8599. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8600. { Store list of found instructions so we don't have to call
  8601. GetNextInstructionUsingReg multiple times }
  8602. InstrList: array of taicpu;
  8603. InstrMax, Index: Integer;
  8604. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8605. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8606. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8607. WorkingValue: TCgInt;
  8608. PreMessage: string;
  8609. { Data flow analysis }
  8610. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8611. BitwiseOnly, OrXorUsed,
  8612. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8613. function CheckOverflowConditions: Boolean;
  8614. begin
  8615. Result := True;
  8616. if (TestValSignedMax > SignedUpperLimit) then
  8617. UpperSignedOverflow := True;
  8618. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8619. LowerSignedOverflow := True;
  8620. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8621. LowerUnsignedOverflow := True;
  8622. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8623. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8624. begin
  8625. { Absolute overflow }
  8626. Result := False;
  8627. Exit;
  8628. end;
  8629. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8630. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8631. ShiftDownOverflow := True;
  8632. if (TestValMin < 0) or (TestValMax < 0) then
  8633. begin
  8634. LowerUnsignedOverflow := True;
  8635. UpperUnsignedOverflow := True;
  8636. end;
  8637. end;
  8638. function AdjustInitialLoadAndSize: Boolean;
  8639. begin
  8640. Result := False;
  8641. if not p_removed then
  8642. begin
  8643. if TargetSize = MinSize then
  8644. begin
  8645. { Convert the input MOVZX to a MOV }
  8646. if (taicpu(p).oper[0]^.typ = top_reg) and
  8647. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8648. begin
  8649. { Or remove it completely! }
  8650. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8651. RemoveCurrentP(p);
  8652. p_removed := True;
  8653. end
  8654. else
  8655. begin
  8656. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8657. taicpu(p).opcode := A_MOV;
  8658. taicpu(p).oper[1]^.reg := ThisReg;
  8659. taicpu(p).opsize := TargetSize;
  8660. end;
  8661. Result := True;
  8662. end
  8663. else if TargetSize <> MaxSize then
  8664. begin
  8665. case MaxSize of
  8666. S_L:
  8667. if TargetSize = S_W then
  8668. begin
  8669. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8670. taicpu(p).opsize := S_BW;
  8671. taicpu(p).oper[1]^.reg := ThisReg;
  8672. Result := True;
  8673. end
  8674. else
  8675. InternalError(2020112341);
  8676. S_W:
  8677. if TargetSize = S_L then
  8678. begin
  8679. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8680. taicpu(p).opsize := S_BL;
  8681. taicpu(p).oper[1]^.reg := ThisReg;
  8682. Result := True;
  8683. end
  8684. else
  8685. InternalError(2020112342);
  8686. else
  8687. ;
  8688. end;
  8689. end
  8690. else if not hp1_removed and not RegInUse then
  8691. begin
  8692. { If we have something like:
  8693. movzbl (oper),%regd
  8694. add x, %regd
  8695. movzbl %regb, %regd
  8696. We can reduce the register size to the input of the final
  8697. movzbl instruction. Overflows won't have any effect.
  8698. }
  8699. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8700. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8701. begin
  8702. TargetSize := S_B;
  8703. setsubreg(ThisReg, R_SUBL);
  8704. Result := True;
  8705. end
  8706. else if (taicpu(p).opsize = S_WL) and
  8707. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8708. begin
  8709. TargetSize := S_W;
  8710. setsubreg(ThisReg, R_SUBW);
  8711. Result := True;
  8712. end;
  8713. if Result then
  8714. begin
  8715. { Convert the input MOVZX to a MOV }
  8716. if (taicpu(p).oper[0]^.typ = top_reg) and
  8717. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8718. begin
  8719. { Or remove it completely! }
  8720. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8721. RemoveCurrentP(p);
  8722. p_removed := True;
  8723. end
  8724. else
  8725. begin
  8726. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8727. taicpu(p).opcode := A_MOV;
  8728. taicpu(p).oper[1]^.reg := ThisReg;
  8729. taicpu(p).opsize := TargetSize;
  8730. end;
  8731. end;
  8732. end;
  8733. end;
  8734. end;
  8735. procedure AdjustFinalLoad;
  8736. begin
  8737. if not LowerUnsignedOverflow then
  8738. begin
  8739. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8740. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8741. begin
  8742. { Convert the output MOVZX to a MOV }
  8743. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8744. begin
  8745. { Or remove it completely! }
  8746. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8747. { Be careful; if p = hp1 and p was also removed, p
  8748. will become a dangling pointer }
  8749. if p = hp1 then
  8750. begin
  8751. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8752. p_removed := True;
  8753. end
  8754. else
  8755. RemoveInstruction(hp1);
  8756. hp1_removed := True;
  8757. end
  8758. else
  8759. begin
  8760. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8761. taicpu(hp1).opcode := A_MOV;
  8762. taicpu(hp1).oper[0]^.reg := ThisReg;
  8763. taicpu(hp1).opsize := TargetSize;
  8764. end;
  8765. end
  8766. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8767. begin
  8768. { Need to change the size of the output }
  8769. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8770. taicpu(hp1).oper[0]^.reg := ThisReg;
  8771. taicpu(hp1).opsize := S_BL;
  8772. end;
  8773. end;
  8774. end;
  8775. function CompressInstructions: Boolean;
  8776. var
  8777. LocalIndex: Integer;
  8778. begin
  8779. Result := False;
  8780. { The objective here is to try to find a combination that
  8781. removes one of the MOV/Z instructions. }
  8782. if (
  8783. (taicpu(p).oper[0]^.typ <> top_reg) or
  8784. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8785. ) and
  8786. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8787. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8788. begin
  8789. { Make a preference to remove the second MOVZX instruction }
  8790. case taicpu(hp1).opsize of
  8791. S_BL, S_WL:
  8792. begin
  8793. TargetSize := S_L;
  8794. TargetSubReg := R_SUBD;
  8795. end;
  8796. S_BW:
  8797. begin
  8798. TargetSize := S_W;
  8799. TargetSubReg := R_SUBW;
  8800. end;
  8801. else
  8802. InternalError(2020112302);
  8803. end;
  8804. end
  8805. else
  8806. begin
  8807. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8808. begin
  8809. { Exceeded lower bound but not upper bound }
  8810. TargetSize := MaxSize;
  8811. end
  8812. else if not LowerUnsignedOverflow then
  8813. begin
  8814. { Size didn't exceed lower bound }
  8815. TargetSize := MinSize;
  8816. end
  8817. else
  8818. Exit;
  8819. end;
  8820. case TargetSize of
  8821. S_B:
  8822. TargetSubReg := R_SUBL;
  8823. S_W:
  8824. TargetSubReg := R_SUBW;
  8825. S_L:
  8826. TargetSubReg := R_SUBD;
  8827. else
  8828. InternalError(2020112350);
  8829. end;
  8830. { Update the register to its new size }
  8831. setsubreg(ThisReg, TargetSubReg);
  8832. RegInUse := False;
  8833. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8834. begin
  8835. { Check to see if the active register is used afterwards;
  8836. if not, we can change it and make a saving. }
  8837. TransferUsedRegs(TmpUsedRegs);
  8838. { The target register may be marked as in use to cross
  8839. a jump to a distant label, so exclude it }
  8840. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8841. hp2 := p;
  8842. repeat
  8843. { Explicitly check for the excluded register (don't include the first
  8844. instruction as it may be reading from here }
  8845. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8846. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8847. begin
  8848. RegInUse := True;
  8849. Break;
  8850. end;
  8851. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8852. if not GetNextInstruction(hp2, hp2) then
  8853. InternalError(2020112340);
  8854. until (hp2 = hp1);
  8855. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8856. { We might still be able to get away with this }
  8857. RegInUse := not
  8858. (
  8859. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8860. (hp2.typ = ait_instruction) and
  8861. (
  8862. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8863. instruction that doesn't actually contain ThisReg }
  8864. (cs_opt_level3 in current_settings.optimizerswitches) or
  8865. RegInInstruction(ThisReg, hp2)
  8866. ) and
  8867. RegLoadedWithNewValue(ThisReg, hp2)
  8868. );
  8869. if not RegInUse then
  8870. begin
  8871. { Force the register size to the same as this instruction so it can be removed}
  8872. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8873. begin
  8874. TargetSize := S_L;
  8875. TargetSubReg := R_SUBD;
  8876. end
  8877. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8878. begin
  8879. TargetSize := S_W;
  8880. TargetSubReg := R_SUBW;
  8881. end;
  8882. ThisReg := taicpu(hp1).oper[1]^.reg;
  8883. setsubreg(ThisReg, TargetSubReg);
  8884. RegChanged := True;
  8885. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8886. TransferUsedRegs(TmpUsedRegs);
  8887. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8888. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8889. if p = hp1 then
  8890. begin
  8891. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8892. p_removed := True;
  8893. end
  8894. else
  8895. RemoveInstruction(hp1);
  8896. hp1_removed := True;
  8897. { Instruction will become "mov %reg,%reg" }
  8898. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8899. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8900. begin
  8901. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8902. RemoveCurrentP(p);
  8903. p_removed := True;
  8904. end
  8905. else
  8906. taicpu(p).oper[1]^.reg := ThisReg;
  8907. Result := True;
  8908. end
  8909. else
  8910. begin
  8911. if TargetSize <> MaxSize then
  8912. begin
  8913. { Since the register is in use, we have to force it to
  8914. MaxSize otherwise part of it may become undefined later on }
  8915. TargetSize := MaxSize;
  8916. case TargetSize of
  8917. S_B:
  8918. TargetSubReg := R_SUBL;
  8919. S_W:
  8920. TargetSubReg := R_SUBW;
  8921. S_L:
  8922. TargetSubReg := R_SUBD;
  8923. else
  8924. InternalError(2020112351);
  8925. end;
  8926. setsubreg(ThisReg, TargetSubReg);
  8927. end;
  8928. AdjustFinalLoad;
  8929. end;
  8930. end
  8931. else
  8932. AdjustFinalLoad;
  8933. Result := AdjustInitialLoadAndSize or Result;
  8934. { Now go through every instruction we found and change the
  8935. size. If TargetSize = MaxSize, then almost no changes are
  8936. needed and Result can remain False if it hasn't been set
  8937. yet.
  8938. If RegChanged is True, then the register requires changing
  8939. and so the point about TargetSize = MaxSize doesn't apply. }
  8940. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8941. begin
  8942. for LocalIndex := 0 to InstrMax do
  8943. begin
  8944. { If p_removed is true, then the original MOV/Z was removed
  8945. and removing the AND instruction may not be safe if it
  8946. appears first }
  8947. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8948. InternalError(2020112310);
  8949. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8950. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8951. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8952. InstrList[LocalIndex].opsize := TargetSize;
  8953. end;
  8954. Result := True;
  8955. end;
  8956. end;
  8957. begin
  8958. Result := False;
  8959. p_removed := False;
  8960. hp1_removed := False;
  8961. ThisReg := taicpu(p).oper[1]^.reg;
  8962. { Check for:
  8963. movs/z ###,%ecx (or %cx or %rcx)
  8964. ...
  8965. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8966. (dealloc %ecx)
  8967. Change to:
  8968. mov ###,%cl (if ### = %cl, then remove completely)
  8969. ...
  8970. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8971. }
  8972. if (getsupreg(ThisReg) = RS_ECX) and
  8973. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8974. (hp1.typ = ait_instruction) and
  8975. (
  8976. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8977. instruction that doesn't actually contain ECX }
  8978. (cs_opt_level3 in current_settings.optimizerswitches) or
  8979. RegInInstruction(NR_ECX, hp1) or
  8980. (
  8981. { It's common for the shift/rotate's read/write register to be
  8982. initialised in between, so under -O2 and under, search ahead
  8983. one more instruction
  8984. }
  8985. GetNextInstruction(hp1, hp1) and
  8986. (hp1.typ = ait_instruction) and
  8987. RegInInstruction(NR_ECX, hp1)
  8988. )
  8989. ) and
  8990. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8991. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8992. begin
  8993. TransferUsedRegs(TmpUsedRegs);
  8994. hp2 := p;
  8995. repeat
  8996. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8997. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8998. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8999. begin
  9000. case taicpu(p).opsize of
  9001. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9002. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9003. begin
  9004. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9005. RemoveCurrentP(p);
  9006. end
  9007. else
  9008. begin
  9009. taicpu(p).opcode := A_MOV;
  9010. taicpu(p).opsize := S_B;
  9011. taicpu(p).oper[1]^.reg := NR_CL;
  9012. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9013. end;
  9014. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9015. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9016. begin
  9017. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9018. RemoveCurrentP(p);
  9019. end
  9020. else
  9021. begin
  9022. taicpu(p).opcode := A_MOV;
  9023. taicpu(p).opsize := S_W;
  9024. taicpu(p).oper[1]^.reg := NR_CX;
  9025. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9026. end;
  9027. {$ifdef x86_64}
  9028. S_LQ:
  9029. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9030. begin
  9031. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9032. RemoveCurrentP(p);
  9033. end
  9034. else
  9035. begin
  9036. taicpu(p).opcode := A_MOV;
  9037. taicpu(p).opsize := S_L;
  9038. taicpu(p).oper[1]^.reg := NR_ECX;
  9039. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9040. end;
  9041. {$endif x86_64}
  9042. else
  9043. InternalError(2021120401);
  9044. end;
  9045. Result := True;
  9046. Exit;
  9047. end;
  9048. end;
  9049. { This is anything but quick! }
  9050. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9051. Exit;
  9052. SetLength(InstrList, 0);
  9053. InstrMax := -1;
  9054. case taicpu(p).opsize of
  9055. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9056. begin
  9057. {$if defined(i386) or defined(i8086)}
  9058. { If the target size is 8-bit, make sure we can actually encode it }
  9059. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9060. Exit;
  9061. {$endif i386 or i8086}
  9062. LowerLimit := $FF;
  9063. SignedLowerLimit := $7F;
  9064. SignedLowerLimitBottom := -128;
  9065. MinSize := S_B;
  9066. if taicpu(p).opsize = S_BW then
  9067. begin
  9068. MaxSize := S_W;
  9069. UpperLimit := $FFFF;
  9070. SignedUpperLimit := $7FFF;
  9071. SignedUpperLimitBottom := -32768;
  9072. end
  9073. else
  9074. begin
  9075. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9076. MaxSize := S_L;
  9077. UpperLimit := $FFFFFFFF;
  9078. SignedUpperLimit := $7FFFFFFF;
  9079. SignedUpperLimitBottom := -2147483648;
  9080. end;
  9081. end;
  9082. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9083. begin
  9084. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9085. LowerLimit := $FFFF;
  9086. SignedLowerLimit := $7FFF;
  9087. SignedLowerLimitBottom := -32768;
  9088. UpperLimit := $FFFFFFFF;
  9089. SignedUpperLimit := $7FFFFFFF;
  9090. SignedUpperLimitBottom := -2147483648;
  9091. MinSize := S_W;
  9092. MaxSize := S_L;
  9093. end;
  9094. {$ifdef x86_64}
  9095. S_LQ:
  9096. begin
  9097. { Both the lower and upper limits are set to 32-bit. If a limit
  9098. is breached, then optimisation is impossible }
  9099. LowerLimit := $FFFFFFFF;
  9100. SignedLowerLimit := $7FFFFFFF;
  9101. SignedLowerLimitBottom := -2147483648;
  9102. UpperLimit := $FFFFFFFF;
  9103. SignedUpperLimit := $7FFFFFFF;
  9104. SignedUpperLimitBottom := -2147483648;
  9105. MinSize := S_L;
  9106. MaxSize := S_L;
  9107. end;
  9108. {$endif x86_64}
  9109. else
  9110. InternalError(2020112301);
  9111. end;
  9112. TestValMin := 0;
  9113. TestValMax := LowerLimit;
  9114. TestValSignedMax := SignedLowerLimit;
  9115. TryShiftDownLimit := LowerLimit;
  9116. TryShiftDown := S_NO;
  9117. ShiftDownOverflow := False;
  9118. RegChanged := False;
  9119. BitwiseOnly := True;
  9120. OrXorUsed := False;
  9121. UpperSignedOverflow := False;
  9122. LowerSignedOverflow := False;
  9123. UpperUnsignedOverflow := False;
  9124. LowerUnsignedOverflow := False;
  9125. hp1 := p;
  9126. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9127. (hp1.typ = ait_instruction) and
  9128. (
  9129. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9130. instruction that doesn't actually contain ThisReg }
  9131. (cs_opt_level3 in current_settings.optimizerswitches) or
  9132. { This allows this Movx optimisation to work through the SETcc instructions
  9133. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9134. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9135. skip over these SETcc instructions). }
  9136. (taicpu(hp1).opcode = A_SETcc) or
  9137. RegInInstruction(ThisReg, hp1)
  9138. ) do
  9139. begin
  9140. case taicpu(hp1).opcode of
  9141. A_INC,A_DEC:
  9142. begin
  9143. { Has to be an exact match on the register }
  9144. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9145. Break;
  9146. if taicpu(hp1).opcode = A_INC then
  9147. begin
  9148. Inc(TestValMin);
  9149. Inc(TestValMax);
  9150. Inc(TestValSignedMax);
  9151. end
  9152. else
  9153. begin
  9154. Dec(TestValMin);
  9155. Dec(TestValMax);
  9156. Dec(TestValSignedMax);
  9157. end;
  9158. end;
  9159. A_TEST, A_CMP:
  9160. begin
  9161. if (
  9162. { Too high a risk of non-linear behaviour that breaks DFA
  9163. here, unless it's cmp $0,%reg, which is equivalent to
  9164. test %reg,%reg }
  9165. OrXorUsed and
  9166. (taicpu(hp1).opcode = A_CMP) and
  9167. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9168. ) or
  9169. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9170. { Has to be an exact match on the register }
  9171. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9172. (
  9173. { Permit "test %reg,%reg" }
  9174. (taicpu(hp1).opcode = A_TEST) and
  9175. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9176. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9177. ) or
  9178. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9179. { Make sure the comparison value is not smaller than the
  9180. smallest allowed signed value for the minimum size (e.g.
  9181. -128 for 8-bit) }
  9182. not (
  9183. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9184. { Is it in the negative range? }
  9185. (
  9186. (taicpu(hp1).oper[0]^.val < 0) and
  9187. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9188. )
  9189. ) then
  9190. Break;
  9191. { Check to see if the active register is used afterwards }
  9192. TransferUsedRegs(TmpUsedRegs);
  9193. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9194. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9195. begin
  9196. { Make sure the comparison or any previous instructions
  9197. hasn't pushed the test values outside of the range of
  9198. MinSize }
  9199. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9200. begin
  9201. { Exceeded lower bound but not upper bound }
  9202. Exit;
  9203. end
  9204. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9205. begin
  9206. { Size didn't exceed lower bound }
  9207. TargetSize := MinSize;
  9208. end
  9209. else
  9210. Break;
  9211. case TargetSize of
  9212. S_B:
  9213. TargetSubReg := R_SUBL;
  9214. S_W:
  9215. TargetSubReg := R_SUBW;
  9216. S_L:
  9217. TargetSubReg := R_SUBD;
  9218. else
  9219. InternalError(2021051002);
  9220. end;
  9221. if TargetSize <> MaxSize then
  9222. begin
  9223. { Update the register to its new size }
  9224. setsubreg(ThisReg, TargetSubReg);
  9225. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9226. taicpu(hp1).oper[1]^.reg := ThisReg;
  9227. taicpu(hp1).opsize := TargetSize;
  9228. { Convert the input MOVZX to a MOV if necessary }
  9229. AdjustInitialLoadAndSize;
  9230. if (InstrMax >= 0) then
  9231. begin
  9232. for Index := 0 to InstrMax do
  9233. begin
  9234. { If p_removed is true, then the original MOV/Z was removed
  9235. and removing the AND instruction may not be safe if it
  9236. appears first }
  9237. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9238. InternalError(2020112311);
  9239. if InstrList[Index].oper[0]^.typ = top_reg then
  9240. InstrList[Index].oper[0]^.reg := ThisReg;
  9241. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9242. InstrList[Index].opsize := MinSize;
  9243. end;
  9244. end;
  9245. Result := True;
  9246. end;
  9247. Exit;
  9248. end;
  9249. end;
  9250. A_SETcc:
  9251. begin
  9252. { This allows this Movx optimisation to work through the SETcc instructions
  9253. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9254. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9255. skip over these SETcc instructions). }
  9256. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9257. { Of course, break out if the current register is used }
  9258. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9259. Break
  9260. else
  9261. { We must use Continue so the instruction doesn't get added
  9262. to InstrList }
  9263. Continue;
  9264. end;
  9265. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9266. begin
  9267. if
  9268. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9269. { Has to be an exact match on the register }
  9270. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9271. (
  9272. (
  9273. (taicpu(hp1).oper[0]^.typ = top_const) and
  9274. (
  9275. (
  9276. (taicpu(hp1).opcode = A_SHL) and
  9277. (
  9278. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9279. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9280. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9281. )
  9282. ) or (
  9283. (taicpu(hp1).opcode <> A_SHL) and
  9284. (
  9285. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9286. { Is it in the negative range? }
  9287. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9288. )
  9289. )
  9290. )
  9291. ) or (
  9292. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9293. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9294. )
  9295. ) then
  9296. Break;
  9297. { Only process OR and XOR if there are only bitwise operations,
  9298. since otherwise they can too easily fool the data flow
  9299. analysis (they can cause non-linear behaviour) }
  9300. case taicpu(hp1).opcode of
  9301. A_ADD:
  9302. begin
  9303. if OrXorUsed then
  9304. { Too high a risk of non-linear behaviour that breaks DFA here }
  9305. Break
  9306. else
  9307. BitwiseOnly := False;
  9308. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9309. begin
  9310. TestValMin := TestValMin * 2;
  9311. TestValMax := TestValMax * 2;
  9312. TestValSignedMax := TestValSignedMax * 2;
  9313. end
  9314. else
  9315. begin
  9316. WorkingValue := taicpu(hp1).oper[0]^.val;
  9317. TestValMin := TestValMin + WorkingValue;
  9318. TestValMax := TestValMax + WorkingValue;
  9319. TestValSignedMax := TestValSignedMax + WorkingValue;
  9320. end;
  9321. end;
  9322. A_SUB:
  9323. begin
  9324. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9325. begin
  9326. TestValMin := 0;
  9327. TestValMax := 0;
  9328. TestValSignedMax := 0;
  9329. end
  9330. else
  9331. begin
  9332. if OrXorUsed then
  9333. { Too high a risk of non-linear behaviour that breaks DFA here }
  9334. Break
  9335. else
  9336. BitwiseOnly := False;
  9337. WorkingValue := taicpu(hp1).oper[0]^.val;
  9338. TestValMin := TestValMin - WorkingValue;
  9339. TestValMax := TestValMax - WorkingValue;
  9340. TestValSignedMax := TestValSignedMax - WorkingValue;
  9341. end;
  9342. end;
  9343. A_AND:
  9344. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9345. begin
  9346. { we might be able to go smaller if AND appears first }
  9347. if InstrMax = -1 then
  9348. case MinSize of
  9349. S_B:
  9350. ;
  9351. S_W:
  9352. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9353. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9354. begin
  9355. TryShiftDown := S_B;
  9356. TryShiftDownLimit := $FF;
  9357. end;
  9358. S_L:
  9359. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9360. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9361. begin
  9362. TryShiftDown := S_B;
  9363. TryShiftDownLimit := $FF;
  9364. end
  9365. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9366. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9367. begin
  9368. TryShiftDown := S_W;
  9369. TryShiftDownLimit := $FFFF;
  9370. end;
  9371. else
  9372. InternalError(2020112320);
  9373. end;
  9374. WorkingValue := taicpu(hp1).oper[0]^.val;
  9375. TestValMin := TestValMin and WorkingValue;
  9376. TestValMax := TestValMax and WorkingValue;
  9377. TestValSignedMax := TestValSignedMax and WorkingValue;
  9378. end;
  9379. A_OR:
  9380. begin
  9381. if not BitwiseOnly then
  9382. Break;
  9383. OrXorUsed := True;
  9384. WorkingValue := taicpu(hp1).oper[0]^.val;
  9385. TestValMin := TestValMin or WorkingValue;
  9386. TestValMax := TestValMax or WorkingValue;
  9387. TestValSignedMax := TestValSignedMax or WorkingValue;
  9388. end;
  9389. A_XOR:
  9390. begin
  9391. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9392. begin
  9393. TestValMin := 0;
  9394. TestValMax := 0;
  9395. TestValSignedMax := 0;
  9396. end
  9397. else
  9398. begin
  9399. if not BitwiseOnly then
  9400. Break;
  9401. OrXorUsed := True;
  9402. WorkingValue := taicpu(hp1).oper[0]^.val;
  9403. TestValMin := TestValMin xor WorkingValue;
  9404. TestValMax := TestValMax xor WorkingValue;
  9405. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9406. end;
  9407. end;
  9408. A_SHL:
  9409. begin
  9410. BitwiseOnly := False;
  9411. WorkingValue := taicpu(hp1).oper[0]^.val;
  9412. TestValMin := TestValMin shl WorkingValue;
  9413. TestValMax := TestValMax shl WorkingValue;
  9414. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9415. end;
  9416. A_SHR,
  9417. { The first instruction was MOVZX, so the value won't be negative }
  9418. A_SAR:
  9419. begin
  9420. if InstrMax <> -1 then
  9421. BitwiseOnly := False
  9422. else
  9423. { we might be able to go smaller if SHR appears first }
  9424. case MinSize of
  9425. S_B:
  9426. ;
  9427. S_W:
  9428. if (taicpu(hp1).oper[0]^.val >= 8) then
  9429. begin
  9430. TryShiftDown := S_B;
  9431. TryShiftDownLimit := $FF;
  9432. TryShiftDownSignedLimit := $7F;
  9433. TryShiftDownSignedLimitLower := -128;
  9434. end;
  9435. S_L:
  9436. if (taicpu(hp1).oper[0]^.val >= 24) then
  9437. begin
  9438. TryShiftDown := S_B;
  9439. TryShiftDownLimit := $FF;
  9440. TryShiftDownSignedLimit := $7F;
  9441. TryShiftDownSignedLimitLower := -128;
  9442. end
  9443. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9444. begin
  9445. TryShiftDown := S_W;
  9446. TryShiftDownLimit := $FFFF;
  9447. TryShiftDownSignedLimit := $7FFF;
  9448. TryShiftDownSignedLimitLower := -32768;
  9449. end;
  9450. else
  9451. InternalError(2020112321);
  9452. end;
  9453. WorkingValue := taicpu(hp1).oper[0]^.val;
  9454. if taicpu(hp1).opcode = A_SAR then
  9455. begin
  9456. TestValMin := SarInt64(TestValMin, WorkingValue);
  9457. TestValMax := SarInt64(TestValMax, WorkingValue);
  9458. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9459. end
  9460. else
  9461. begin
  9462. TestValMin := TestValMin shr WorkingValue;
  9463. TestValMax := TestValMax shr WorkingValue;
  9464. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9465. end;
  9466. end;
  9467. else
  9468. InternalError(2020112303);
  9469. end;
  9470. end;
  9471. (*
  9472. A_IMUL:
  9473. case taicpu(hp1).ops of
  9474. 2:
  9475. begin
  9476. if not MatchOpType(hp1, top_reg, top_reg) or
  9477. { Has to be an exact match on the register }
  9478. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9479. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9480. Break;
  9481. TestValMin := TestValMin * TestValMin;
  9482. TestValMax := TestValMax * TestValMax;
  9483. TestValSignedMax := TestValSignedMax * TestValMax;
  9484. end;
  9485. 3:
  9486. begin
  9487. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9488. { Has to be an exact match on the register }
  9489. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9490. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9491. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9492. { Is it in the negative range? }
  9493. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9494. Break;
  9495. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9496. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9497. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9498. end;
  9499. else
  9500. Break;
  9501. end;
  9502. A_IDIV:
  9503. case taicpu(hp1).ops of
  9504. 3:
  9505. begin
  9506. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9507. { Has to be an exact match on the register }
  9508. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9509. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9510. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9511. { Is it in the negative range? }
  9512. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9513. Break;
  9514. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9515. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9516. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9517. end;
  9518. else
  9519. Break;
  9520. end;
  9521. *)
  9522. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9523. begin
  9524. { If there are no instructions in between, then we might be able to make a saving }
  9525. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9526. Break;
  9527. { We have something like:
  9528. movzbw %dl,%dx
  9529. ...
  9530. movswl %dx,%edx
  9531. Change the latter to a zero-extension then enter the
  9532. A_MOVZX case branch.
  9533. }
  9534. {$ifdef x86_64}
  9535. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9536. begin
  9537. { this becomes a zero extension from 32-bit to 64-bit, but
  9538. the upper 32 bits are already zero, so just delete the
  9539. instruction }
  9540. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9541. RemoveInstruction(hp1);
  9542. Result := True;
  9543. Exit;
  9544. end
  9545. else
  9546. {$endif x86_64}
  9547. begin
  9548. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9549. taicpu(hp1).opcode := A_MOVZX;
  9550. {$ifdef x86_64}
  9551. case taicpu(hp1).opsize of
  9552. S_BQ:
  9553. begin
  9554. taicpu(hp1).opsize := S_BL;
  9555. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9556. end;
  9557. S_WQ:
  9558. begin
  9559. taicpu(hp1).opsize := S_WL;
  9560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9561. end;
  9562. S_LQ:
  9563. begin
  9564. taicpu(hp1).opcode := A_MOV;
  9565. taicpu(hp1).opsize := S_L;
  9566. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9567. { In this instance, we need to break out because the
  9568. instruction is no longer MOVZX or MOVSXD }
  9569. Result := True;
  9570. Exit;
  9571. end;
  9572. else
  9573. ;
  9574. end;
  9575. {$endif x86_64}
  9576. Result := CompressInstructions;
  9577. Exit;
  9578. end;
  9579. end;
  9580. A_MOVZX:
  9581. begin
  9582. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9583. Break;
  9584. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9585. begin
  9586. if (InstrMax = -1) and
  9587. { Will return false if the second parameter isn't ThisReg
  9588. (can happen on -O2 and under) }
  9589. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9590. begin
  9591. { The two MOVZX instructions are adjacent, so remove the first one }
  9592. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9593. RemoveCurrentP(p);
  9594. Result := True;
  9595. Exit;
  9596. end;
  9597. Break;
  9598. end;
  9599. Result := CompressInstructions;
  9600. Exit;
  9601. end;
  9602. else
  9603. { This includes ADC, SBB and IDIV }
  9604. Break;
  9605. end;
  9606. if not CheckOverflowConditions then
  9607. Break;
  9608. { Contains highest index (so instruction count - 1) }
  9609. Inc(InstrMax);
  9610. if InstrMax > High(InstrList) then
  9611. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9612. InstrList[InstrMax] := taicpu(hp1);
  9613. end;
  9614. end;
  9615. {$pop}
  9616. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9617. var
  9618. hp1 : tai;
  9619. begin
  9620. Result:=false;
  9621. if (taicpu(p).ops >= 2) and
  9622. ((taicpu(p).oper[0]^.typ = top_const) or
  9623. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9624. (taicpu(p).oper[1]^.typ = top_reg) and
  9625. ((taicpu(p).ops = 2) or
  9626. ((taicpu(p).oper[2]^.typ = top_reg) and
  9627. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9628. GetLastInstruction(p,hp1) and
  9629. MatchInstruction(hp1,A_MOV,[]) and
  9630. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9631. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9632. begin
  9633. TransferUsedRegs(TmpUsedRegs);
  9634. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9635. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9636. { change
  9637. mov reg1,reg2
  9638. imul y,reg2 to imul y,reg1,reg2 }
  9639. begin
  9640. taicpu(p).ops := 3;
  9641. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9642. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9643. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9644. RemoveInstruction(hp1);
  9645. result:=true;
  9646. end;
  9647. end;
  9648. end;
  9649. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9650. var
  9651. ThisLabel: TAsmLabel;
  9652. begin
  9653. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9654. ThisLabel.decrefs;
  9655. taicpu(p).condition := C_None;
  9656. taicpu(p).opcode := A_RET;
  9657. taicpu(p).is_jmp := false;
  9658. taicpu(p).ops := taicpu(ret_p).ops;
  9659. case taicpu(ret_p).ops of
  9660. 0:
  9661. taicpu(p).clearop(0);
  9662. 1:
  9663. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9664. else
  9665. internalerror(2016041301);
  9666. end;
  9667. { If the original label is now dead, it might turn out that the label
  9668. immediately follows p. As a result, everything beyond it, which will
  9669. be just some final register configuration and a RET instruction, is
  9670. now dead code. [Kit] }
  9671. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9672. running RemoveDeadCodeAfterJump for each RET instruction, because
  9673. this optimisation rarely happens and most RETs appear at the end of
  9674. routines where there is nothing that can be stripped. [Kit] }
  9675. if not ThisLabel.is_used then
  9676. RemoveDeadCodeAfterJump(p);
  9677. end;
  9678. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9679. var
  9680. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9681. Unconditional, PotentialModified: Boolean;
  9682. OperPtr: POper;
  9683. NewRef: TReference;
  9684. InstrList: array of taicpu;
  9685. InstrMax, Index: Integer;
  9686. const
  9687. {$ifdef DEBUG_AOPTCPU}
  9688. SNoFlags: shortstring = ' so the flags aren''t modified';
  9689. {$else DEBUG_AOPTCPU}
  9690. SNoFlags = '';
  9691. {$endif DEBUG_AOPTCPU}
  9692. begin
  9693. Result:=false;
  9694. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9695. begin
  9696. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9697. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9698. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9699. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9700. GetNextInstruction(hp1, hp2) and
  9701. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9702. { Change from: To:
  9703. set(C) %reg j(~C) label
  9704. test %reg,%reg/cmp $0,%reg
  9705. je label
  9706. set(C) %reg j(C) label
  9707. test %reg,%reg/cmp $0,%reg
  9708. jne label
  9709. (Also do something similar with sete/setne instead of je/jne)
  9710. }
  9711. begin
  9712. { Before we do anything else, we need to check the instructions
  9713. in between SETcc and TEST to make sure they don't modify the
  9714. FLAGS register - if -O2 or under, there won't be any
  9715. instructions between SET and TEST }
  9716. TransferUsedRegs(TmpUsedRegs);
  9717. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9718. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9719. begin
  9720. next := p;
  9721. SetLength(InstrList, 0);
  9722. InstrMax := -1;
  9723. PotentialModified := False;
  9724. { Make a note of every instruction that modifies the FLAGS
  9725. register }
  9726. while GetNextInstruction(next, next) and (next <> hp1) do
  9727. begin
  9728. if next.typ <> ait_instruction then
  9729. { GetNextInstructionUsingReg should have returned False }
  9730. InternalError(2021051701);
  9731. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9732. begin
  9733. case taicpu(next).opcode of
  9734. A_SETcc,
  9735. A_CMOVcc,
  9736. A_Jcc:
  9737. begin
  9738. if PotentialModified then
  9739. { Not safe because the flags were modified earlier }
  9740. Exit
  9741. else
  9742. { Condition is the same as the initial SETcc, so this is safe
  9743. (don't add to instruction list though) }
  9744. Continue;
  9745. end;
  9746. A_ADD:
  9747. begin
  9748. if (taicpu(next).opsize = S_B) or
  9749. { LEA doesn't support 8-bit operands }
  9750. (taicpu(next).oper[1]^.typ <> top_reg) or
  9751. { Must write to a register }
  9752. (taicpu(next).oper[0]^.typ = top_ref) then
  9753. { Require a constant or a register }
  9754. Exit;
  9755. PotentialModified := True;
  9756. end;
  9757. A_SUB:
  9758. begin
  9759. if (taicpu(next).opsize = S_B) or
  9760. { LEA doesn't support 8-bit operands }
  9761. (taicpu(next).oper[1]^.typ <> top_reg) or
  9762. { Must write to a register }
  9763. (taicpu(next).oper[0]^.typ <> top_const) or
  9764. (taicpu(next).oper[0]^.val = $80000000) then
  9765. { Can't subtract a register with LEA - also
  9766. check that the value isn't -2^31, as this
  9767. can't be negated }
  9768. Exit;
  9769. PotentialModified := True;
  9770. end;
  9771. A_SAL,
  9772. A_SHL:
  9773. begin
  9774. if (taicpu(next).opsize = S_B) or
  9775. { LEA doesn't support 8-bit operands }
  9776. (taicpu(next).oper[1]^.typ <> top_reg) or
  9777. { Must write to a register }
  9778. (taicpu(next).oper[0]^.typ <> top_const) or
  9779. (taicpu(next).oper[0]^.val < 0) or
  9780. (taicpu(next).oper[0]^.val > 3) then
  9781. Exit;
  9782. PotentialModified := True;
  9783. end;
  9784. A_IMUL:
  9785. begin
  9786. if (taicpu(next).ops <> 3) or
  9787. (taicpu(next).oper[1]^.typ <> top_reg) or
  9788. { Must write to a register }
  9789. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9790. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9791. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9792. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9793. Exit
  9794. else
  9795. PotentialModified := True;
  9796. end;
  9797. else
  9798. { Don't know how to change this, so abort }
  9799. Exit;
  9800. end;
  9801. { Contains highest index (so instruction count - 1) }
  9802. Inc(InstrMax);
  9803. if InstrMax > High(InstrList) then
  9804. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9805. InstrList[InstrMax] := taicpu(next);
  9806. end;
  9807. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9808. end;
  9809. if not Assigned(next) or (next <> hp1) then
  9810. { It should be equal to hp1 }
  9811. InternalError(2021051702);
  9812. { Cycle through each instruction and check to see if we can
  9813. change them to versions that don't modify the flags }
  9814. if (InstrMax >= 0) then
  9815. begin
  9816. for Index := 0 to InstrMax do
  9817. case InstrList[Index].opcode of
  9818. A_ADD:
  9819. begin
  9820. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9821. InstrList[Index].opcode := A_LEA;
  9822. reference_reset(NewRef, 1, []);
  9823. NewRef.base := InstrList[Index].oper[1]^.reg;
  9824. if InstrList[Index].oper[0]^.typ = top_reg then
  9825. begin
  9826. NewRef.index := InstrList[Index].oper[0]^.reg;
  9827. NewRef.scalefactor := 1;
  9828. end
  9829. else
  9830. NewRef.offset := InstrList[Index].oper[0]^.val;
  9831. InstrList[Index].loadref(0, NewRef);
  9832. end;
  9833. A_SUB:
  9834. begin
  9835. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9836. InstrList[Index].opcode := A_LEA;
  9837. reference_reset(NewRef, 1, []);
  9838. NewRef.base := InstrList[Index].oper[1]^.reg;
  9839. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9840. InstrList[Index].loadref(0, NewRef);
  9841. end;
  9842. A_SHL,
  9843. A_SAL:
  9844. begin
  9845. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9846. InstrList[Index].opcode := A_LEA;
  9847. reference_reset(NewRef, 1, []);
  9848. NewRef.index := InstrList[Index].oper[1]^.reg;
  9849. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9850. InstrList[Index].loadref(0, NewRef);
  9851. end;
  9852. A_IMUL:
  9853. begin
  9854. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9855. InstrList[Index].opcode := A_LEA;
  9856. reference_reset(NewRef, 1, []);
  9857. NewRef.index := InstrList[Index].oper[1]^.reg;
  9858. case InstrList[Index].oper[0]^.val of
  9859. 2, 4, 8:
  9860. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9861. else {3, 5 and 9}
  9862. begin
  9863. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9864. NewRef.base := InstrList[Index].oper[1]^.reg;
  9865. end;
  9866. end;
  9867. InstrList[Index].loadref(0, NewRef);
  9868. end;
  9869. else
  9870. InternalError(2021051710);
  9871. end;
  9872. end;
  9873. { Mark the FLAGS register as used across this whole block }
  9874. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9875. end;
  9876. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9877. JumpC := taicpu(hp2).condition;
  9878. Unconditional := False;
  9879. if conditions_equal(JumpC, C_E) then
  9880. SetC := inverse_cond(taicpu(p).condition)
  9881. else if conditions_equal(JumpC, C_NE) then
  9882. SetC := taicpu(p).condition
  9883. else
  9884. { We've got something weird here (and inefficent) }
  9885. begin
  9886. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9887. SetC := C_NONE;
  9888. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9889. if condition_in(C_AE, JumpC) then
  9890. Unconditional := True
  9891. else
  9892. { Not sure what to do with this jump - drop out }
  9893. Exit;
  9894. end;
  9895. RemoveInstruction(hp1);
  9896. if Unconditional then
  9897. MakeUnconditional(taicpu(hp2))
  9898. else
  9899. begin
  9900. if SetC = C_NONE then
  9901. InternalError(2018061402);
  9902. taicpu(hp2).SetCondition(SetC);
  9903. end;
  9904. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9905. TmpUsedRegs }
  9906. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9907. begin
  9908. RemoveCurrentp(p, hp2);
  9909. if taicpu(hp2).opcode = A_SETcc then
  9910. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9911. else
  9912. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9913. end
  9914. else
  9915. if taicpu(hp2).opcode = A_SETcc then
  9916. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9917. else
  9918. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9919. Result := True;
  9920. end
  9921. else if
  9922. { Make sure the instructions are adjacent }
  9923. (
  9924. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9925. GetNextInstruction(p, hp1)
  9926. ) and
  9927. MatchInstruction(hp1, A_MOV, [S_B]) and
  9928. { Writing to memory is allowed }
  9929. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9930. begin
  9931. {
  9932. Watch out for sequences such as:
  9933. set(c)b %regb
  9934. movb %regb,(ref)
  9935. movb $0,1(ref)
  9936. movb $0,2(ref)
  9937. movb $0,3(ref)
  9938. Much more efficient to turn it into:
  9939. movl $0,%regl
  9940. set(c)b %regb
  9941. movl %regl,(ref)
  9942. Or:
  9943. set(c)b %regb
  9944. movzbl %regb,%regl
  9945. movl %regl,(ref)
  9946. }
  9947. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9948. GetNextInstruction(hp1, hp2) and
  9949. MatchInstruction(hp2, A_MOV, [S_B]) and
  9950. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9951. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9952. begin
  9953. { Don't do anything else except set Result to True }
  9954. end
  9955. else
  9956. begin
  9957. if taicpu(p).oper[0]^.typ = top_reg then
  9958. begin
  9959. TransferUsedRegs(TmpUsedRegs);
  9960. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9961. end;
  9962. { If it's not a register, it's a memory address }
  9963. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9964. begin
  9965. { Even if the register is still in use, we can minimise the
  9966. pipeline stall by changing the MOV into another SETcc. }
  9967. taicpu(hp1).opcode := A_SETcc;
  9968. taicpu(hp1).condition := taicpu(p).condition;
  9969. if taicpu(hp1).oper[1]^.typ = top_ref then
  9970. begin
  9971. { Swapping the operand pointers like this is probably a
  9972. bit naughty, but it is far faster than using loadoper
  9973. to transfer the reference from oper[1] to oper[0] if
  9974. you take into account the extra procedure calls and
  9975. the memory allocation and deallocation required }
  9976. OperPtr := taicpu(hp1).oper[1];
  9977. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9978. taicpu(hp1).oper[0] := OperPtr;
  9979. end
  9980. else
  9981. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9982. taicpu(hp1).clearop(1);
  9983. taicpu(hp1).ops := 1;
  9984. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9985. end
  9986. else
  9987. begin
  9988. if taicpu(hp1).oper[1]^.typ = top_reg then
  9989. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9990. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9991. RemoveInstruction(hp1);
  9992. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9993. end
  9994. end;
  9995. Result := True;
  9996. end;
  9997. end;
  9998. end;
  9999. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10000. var
  10001. hp1: tai;
  10002. Count: Integer;
  10003. OrigLabel: TAsmLabel;
  10004. begin
  10005. result := False;
  10006. { Sometimes, the optimisations below can permit this }
  10007. RemoveDeadCodeAfterJump(p);
  10008. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  10009. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10010. begin
  10011. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10012. { Also a side-effect of optimisations }
  10013. if CollapseZeroDistJump(p, OrigLabel) then
  10014. begin
  10015. Result := True;
  10016. Exit;
  10017. end;
  10018. hp1 := GetLabelWithSym(OrigLabel);
  10019. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10020. begin
  10021. if taicpu(hp1).opcode = A_RET then
  10022. begin
  10023. {
  10024. change
  10025. jmp .L1
  10026. ...
  10027. .L1:
  10028. ret
  10029. into
  10030. ret
  10031. }
  10032. begin
  10033. ConvertJumpToRET(p, hp1);
  10034. result:=true;
  10035. end;
  10036. end
  10037. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10038. not (cs_opt_size in current_settings.optimizerswitches) and
  10039. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10040. begin
  10041. Result := True;
  10042. Exit;
  10043. end;
  10044. end;
  10045. end;
  10046. end;
  10047. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  10048. begin
  10049. CanBeCMOV:=assigned(p) and
  10050. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10051. { we can't use cmov ref,reg because
  10052. ref could be nil and cmov still throws an exception
  10053. if ref=nil but the mov isn't done (FK)
  10054. or ((taicpu(p).oper[0]^.typ = top_ref) and
  10055. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  10056. }
  10057. (taicpu(p).oper[1]^.typ = top_reg) and
  10058. (
  10059. (taicpu(p).oper[0]^.typ = top_reg) or
  10060. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10061. it is not expected that this can cause a seg. violation }
  10062. (
  10063. (taicpu(p).oper[0]^.typ = top_ref) and
  10064. IsRefSafe(taicpu(p).oper[0]^.ref)
  10065. )
  10066. );
  10067. end;
  10068. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10069. var
  10070. hp1,hp2: tai;
  10071. {$ifndef i8086}
  10072. hp3,hp4,hpmov2, hp5: tai;
  10073. l : Longint;
  10074. condition : TAsmCond;
  10075. {$endif i8086}
  10076. carryadd_opcode : TAsmOp;
  10077. symbol: TAsmSymbol;
  10078. increg, tmpreg: TRegister;
  10079. begin
  10080. result:=false;
  10081. if GetNextInstruction(p,hp1) then
  10082. begin
  10083. if (hp1.typ=ait_label) then
  10084. begin
  10085. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10086. Exit;
  10087. end
  10088. else if (hp1.typ<>ait_instruction) then
  10089. Exit;
  10090. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10091. if (
  10092. (
  10093. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10094. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10095. (Taicpu(hp1).oper[0]^.val=1)
  10096. ) or
  10097. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10098. ) and
  10099. GetNextInstruction(hp1,hp2) and
  10100. SkipAligns(hp2, hp2) and
  10101. (hp2.typ = ait_label) and
  10102. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10103. { jb @@1 cmc
  10104. inc/dec operand --> adc/sbb operand,0
  10105. @@1:
  10106. ... and ...
  10107. jnb @@1
  10108. inc/dec operand --> adc/sbb operand,0
  10109. @@1: }
  10110. begin
  10111. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10112. begin
  10113. case taicpu(hp1).opcode of
  10114. A_INC,
  10115. A_ADD:
  10116. carryadd_opcode:=A_ADC;
  10117. A_DEC,
  10118. A_SUB:
  10119. carryadd_opcode:=A_SBB;
  10120. else
  10121. InternalError(2021011001);
  10122. end;
  10123. Taicpu(p).clearop(0);
  10124. Taicpu(p).ops:=0;
  10125. Taicpu(p).is_jmp:=false;
  10126. Taicpu(p).opcode:=A_CMC;
  10127. Taicpu(p).condition:=C_NONE;
  10128. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10129. Taicpu(hp1).ops:=2;
  10130. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10131. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10132. else
  10133. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10134. Taicpu(hp1).loadconst(0,0);
  10135. Taicpu(hp1).opcode:=carryadd_opcode;
  10136. result:=true;
  10137. exit;
  10138. end
  10139. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10140. begin
  10141. case taicpu(hp1).opcode of
  10142. A_INC,
  10143. A_ADD:
  10144. carryadd_opcode:=A_ADC;
  10145. A_DEC,
  10146. A_SUB:
  10147. carryadd_opcode:=A_SBB;
  10148. else
  10149. InternalError(2021011002);
  10150. end;
  10151. Taicpu(hp1).ops:=2;
  10152. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10153. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10154. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10155. else
  10156. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10157. Taicpu(hp1).loadconst(0,0);
  10158. Taicpu(hp1).opcode:=carryadd_opcode;
  10159. RemoveCurrentP(p, hp1);
  10160. result:=true;
  10161. exit;
  10162. end
  10163. {
  10164. jcc @@1 setcc tmpreg
  10165. inc/dec/add/sub operand -> (movzx tmpreg)
  10166. @@1: add/sub tmpreg,operand
  10167. While this increases code size slightly, it makes the code much faster if the
  10168. jump is unpredictable
  10169. }
  10170. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10171. begin
  10172. { search for an available register which is volatile }
  10173. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10174. if increg <> NR_NO then
  10175. begin
  10176. { We don't need to check if tmpreg is in hp1 or not, because
  10177. it will be marked as in use at p (if not, this is
  10178. indictive of a compiler bug). }
  10179. TAsmLabel(symbol).decrefs;
  10180. Taicpu(p).clearop(0);
  10181. Taicpu(p).ops:=1;
  10182. Taicpu(p).is_jmp:=false;
  10183. Taicpu(p).opcode:=A_SETcc;
  10184. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10185. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10186. Taicpu(p).loadreg(0,increg);
  10187. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10188. begin
  10189. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10190. R_SUBW:
  10191. begin
  10192. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10193. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10194. end;
  10195. R_SUBD:
  10196. begin
  10197. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10198. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10199. end;
  10200. {$ifdef x86_64}
  10201. R_SUBQ:
  10202. begin
  10203. { MOVZX doesn't have a 64-bit variant, because
  10204. the 32-bit version implicitly zeroes the
  10205. upper 32-bits of the destination register }
  10206. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10207. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10208. setsubreg(tmpreg, R_SUBQ);
  10209. end;
  10210. {$endif x86_64}
  10211. else
  10212. Internalerror(2020030601);
  10213. end;
  10214. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10215. asml.InsertAfter(hp2,p);
  10216. end
  10217. else
  10218. tmpreg := increg;
  10219. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10220. begin
  10221. Taicpu(hp1).ops:=2;
  10222. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10223. end;
  10224. Taicpu(hp1).loadreg(0,tmpreg);
  10225. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10226. Result := True;
  10227. { p is no longer a Jcc instruction, so exit }
  10228. Exit;
  10229. end;
  10230. end;
  10231. end;
  10232. { Detect the following:
  10233. jmp<cond> @Lbl1
  10234. jmp @Lbl2
  10235. ...
  10236. @Lbl1:
  10237. ret
  10238. Change to:
  10239. jmp<inv_cond> @Lbl2
  10240. ret
  10241. }
  10242. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10243. begin
  10244. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10245. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10246. MatchInstruction(hp2,A_RET,[S_NO]) then
  10247. begin
  10248. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10249. { Change label address to that of the unconditional jump }
  10250. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10251. TAsmLabel(symbol).DecRefs;
  10252. taicpu(hp1).opcode := A_RET;
  10253. taicpu(hp1).is_jmp := false;
  10254. taicpu(hp1).ops := taicpu(hp2).ops;
  10255. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10256. case taicpu(hp2).ops of
  10257. 0:
  10258. taicpu(hp1).clearop(0);
  10259. 1:
  10260. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10261. else
  10262. internalerror(2016041302);
  10263. end;
  10264. end;
  10265. {$ifndef i8086}
  10266. end
  10267. {
  10268. convert
  10269. j<c> .L1
  10270. mov 1,reg
  10271. jmp .L2
  10272. .L1
  10273. mov 0,reg
  10274. .L2
  10275. into
  10276. mov 0,reg
  10277. set<not(c)> reg
  10278. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10279. would destroy the flag contents
  10280. }
  10281. else if MatchInstruction(hp1,A_MOV,[]) and
  10282. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10283. {$ifdef i386}
  10284. (
  10285. { Under i386, ESI, EDI, EBP and ESP
  10286. don't have an 8-bit representation }
  10287. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10288. ) and
  10289. {$endif i386}
  10290. (taicpu(hp1).oper[0]^.val=1) and
  10291. GetNextInstruction(hp1,hp2) and
  10292. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10293. GetNextInstruction(hp2,hp3) and
  10294. { skip align }
  10295. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10296. (hp3.typ=ait_label) and
  10297. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10298. (tai_label(hp3).labsym.getrefs=1) and
  10299. GetNextInstruction(hp3,hp4) and
  10300. MatchInstruction(hp4,A_MOV,[]) and
  10301. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10302. (taicpu(hp4).oper[0]^.val=0) and
  10303. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10304. GetNextInstruction(hp4,hp5) and
  10305. (hp5.typ=ait_label) and
  10306. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10307. (tai_label(hp5).labsym.getrefs=1) then
  10308. begin
  10309. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10310. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10311. { remove last label }
  10312. RemoveInstruction(hp5);
  10313. { remove second label }
  10314. RemoveInstruction(hp3);
  10315. { if align is present remove it }
  10316. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10317. RemoveInstruction(hp3);
  10318. { remove jmp }
  10319. RemoveInstruction(hp2);
  10320. if taicpu(hp1).opsize=S_B then
  10321. RemoveInstruction(hp1)
  10322. else
  10323. taicpu(hp1).loadconst(0,0);
  10324. taicpu(hp4).opcode:=A_SETcc;
  10325. taicpu(hp4).opsize:=S_B;
  10326. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10327. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10328. taicpu(hp4).opercnt:=1;
  10329. taicpu(hp4).ops:=1;
  10330. taicpu(hp4).freeop(1);
  10331. RemoveCurrentP(p);
  10332. Result:=true;
  10333. exit;
  10334. end
  10335. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10336. begin
  10337. { check for
  10338. jCC xxx
  10339. <several movs>
  10340. xxx:
  10341. Also spot:
  10342. Jcc xxx
  10343. <several movs>
  10344. jmp xxx
  10345. Change to:
  10346. <several cmovs with inverted condition>
  10347. jmp xxx
  10348. }
  10349. l:=0;
  10350. while assigned(hp1) and
  10351. CanBeCMOV(hp1) and
  10352. { stop on labels }
  10353. not(hp1.typ=ait_label) do
  10354. begin
  10355. inc(l);
  10356. hp5 := hp1;
  10357. GetNextInstruction(hp1,hp1);
  10358. end;
  10359. if assigned(hp1) then
  10360. begin
  10361. TransferUsedRegs(TmpUsedRegs);
  10362. if (
  10363. MatchInstruction(hp1, A_JMP, []) and
  10364. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10365. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10366. ) or
  10367. FindLabel(tasmlabel(symbol),hp1) then
  10368. begin
  10369. if (l<=4) and (l>0) then
  10370. begin
  10371. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10372. condition:=inverse_cond(taicpu(p).condition);
  10373. UpdateUsedRegs(tai(p.next));
  10374. GetNextInstruction(p,hp1);
  10375. repeat
  10376. if not Assigned(hp1) then
  10377. InternalError(2018062900);
  10378. taicpu(hp1).opcode:=A_CMOVcc;
  10379. taicpu(hp1).condition:=condition;
  10380. UpdateUsedRegs(tai(hp1.next));
  10381. GetNextInstruction(hp1,hp1);
  10382. until not(CanBeCMOV(hp1));
  10383. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10384. hp2 := hp1;
  10385. repeat
  10386. if not Assigned(hp2) then
  10387. InternalError(2018062910);
  10388. case hp2.typ of
  10389. ait_label:
  10390. { What we expected - break out of the loop (it won't be a dead label at the top of
  10391. a cluster because that was optimised at an earlier stage) }
  10392. Break;
  10393. ait_align:
  10394. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10395. begin
  10396. hp2 := tai(hp2.Next);
  10397. Continue;
  10398. end;
  10399. ait_instruction:
  10400. begin
  10401. if taicpu(hp2).opcode<>A_JMP then
  10402. InternalError(2018062912);
  10403. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10404. Break;
  10405. end
  10406. else
  10407. begin
  10408. { Might be a comment or temporary allocation entry }
  10409. if not (hp2.typ in SkipInstr) then
  10410. InternalError(2018062911);
  10411. hp2 := tai(hp2.Next);
  10412. Continue;
  10413. end;
  10414. end;
  10415. until False;
  10416. { Now we can safely decrement the reference count }
  10417. tasmlabel(symbol).decrefs;
  10418. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10419. { Remove the original jump }
  10420. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10421. if hp2.typ=ait_instruction then
  10422. begin
  10423. p:=hp2;
  10424. Result:=True;
  10425. end
  10426. else
  10427. begin
  10428. UpdateUsedRegs(tai(hp2.next));
  10429. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10430. { Remove the label if this is its final reference }
  10431. if (tasmlabel(symbol).getrefs=0) then
  10432. StripLabelFast(hp1);
  10433. end;
  10434. exit;
  10435. end;
  10436. end
  10437. else
  10438. begin
  10439. { check further for
  10440. jCC xxx
  10441. <several movs 1>
  10442. jmp yyy
  10443. xxx:
  10444. <several movs 2>
  10445. yyy:
  10446. }
  10447. { hp2 points to jmp yyy }
  10448. hp2:=hp1;
  10449. { skip hp1 to xxx (or an align right before it) }
  10450. GetNextInstruction(hp1, hp1);
  10451. if assigned(hp2) and
  10452. assigned(hp1) and
  10453. (l<=3) and
  10454. (hp2.typ=ait_instruction) and
  10455. (taicpu(hp2).is_jmp) and
  10456. (taicpu(hp2).condition=C_None) and
  10457. { real label and jump, no further references to the
  10458. label are allowed }
  10459. (tasmlabel(symbol).getrefs=1) and
  10460. FindLabel(tasmlabel(symbol),hp1) then
  10461. begin
  10462. l:=0;
  10463. { skip hp1 to <several moves 2> }
  10464. if (hp1.typ = ait_align) then
  10465. GetNextInstruction(hp1, hp1);
  10466. GetNextInstruction(hp1, hpmov2);
  10467. hp1 := hpmov2;
  10468. while assigned(hp1) and
  10469. CanBeCMOV(hp1) do
  10470. begin
  10471. inc(l);
  10472. hp5 := hp1;
  10473. GetNextInstruction(hp1, hp1);
  10474. end;
  10475. { hp1 points to yyy (or an align right before it) }
  10476. hp3 := hp1;
  10477. if assigned(hp1) and
  10478. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10479. begin
  10480. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10481. condition:=inverse_cond(taicpu(p).condition);
  10482. UpdateUsedRegs(tai(p.next));
  10483. GetNextInstruction(p,hp1);
  10484. repeat
  10485. taicpu(hp1).opcode:=A_CMOVcc;
  10486. taicpu(hp1).condition:=condition;
  10487. UpdateUsedRegs(tai(hp1.next));
  10488. GetNextInstruction(hp1,hp1);
  10489. until not(assigned(hp1)) or
  10490. not(CanBeCMOV(hp1));
  10491. condition:=inverse_cond(condition);
  10492. if GetLastInstruction(hpmov2,hp1) then
  10493. UpdateUsedRegs(tai(hp1.next));
  10494. hp1 := hpmov2;
  10495. { hp1 is now at <several movs 2> }
  10496. while Assigned(hp1) and CanBeCMOV(hp1) do
  10497. begin
  10498. taicpu(hp1).opcode:=A_CMOVcc;
  10499. taicpu(hp1).condition:=condition;
  10500. UpdateUsedRegs(tai(hp1.next));
  10501. GetNextInstruction(hp1,hp1);
  10502. end;
  10503. hp1 := p;
  10504. { Get first instruction after label }
  10505. UpdateUsedRegs(tai(hp3.next));
  10506. GetNextInstruction(hp3, p);
  10507. if assigned(p) and (hp3.typ = ait_align) then
  10508. GetNextInstruction(p, p);
  10509. { Don't dereference yet, as doing so will cause
  10510. GetNextInstruction to skip the label and
  10511. optional align marker. [Kit] }
  10512. GetNextInstruction(hp2, hp4);
  10513. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10514. { remove jCC }
  10515. RemoveInstruction(hp1);
  10516. { Now we can safely decrement it }
  10517. tasmlabel(symbol).decrefs;
  10518. { Remove label xxx (it will have a ref of zero due to the initial check }
  10519. StripLabelFast(hp4);
  10520. { remove jmp }
  10521. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10522. RemoveInstruction(hp2);
  10523. { As before, now we can safely decrement it }
  10524. tasmlabel(symbol).decrefs;
  10525. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10526. if tasmlabel(symbol).getrefs = 0 then
  10527. StripLabelFast(hp3);
  10528. if Assigned(p) then
  10529. result:=true;
  10530. exit;
  10531. end;
  10532. end;
  10533. end;
  10534. end;
  10535. {$endif i8086}
  10536. end;
  10537. end;
  10538. end;
  10539. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10540. var
  10541. hp1,hp2,hp3: tai;
  10542. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10543. NewSize: TOpSize;
  10544. NewRegSize: TSubRegister;
  10545. Limit: TCgInt;
  10546. SwapOper: POper;
  10547. begin
  10548. result:=false;
  10549. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10550. GetNextInstruction(p,hp1) and
  10551. (hp1.typ = ait_instruction);
  10552. if reg_and_hp1_is_instr and
  10553. (
  10554. (taicpu(hp1).opcode <> A_LEA) or
  10555. { If the LEA instruction can be converted into an arithmetic instruction,
  10556. it may be possible to then fold it. }
  10557. (
  10558. { If the flags register is in use, don't change the instruction
  10559. to an ADD otherwise this will scramble the flags. [Kit] }
  10560. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10561. ConvertLEA(taicpu(hp1))
  10562. )
  10563. ) and
  10564. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10565. GetNextInstruction(hp1,hp2) and
  10566. MatchInstruction(hp2,A_MOV,[]) and
  10567. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10568. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10569. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10570. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10571. {$ifdef i386}
  10572. { not all registers have byte size sub registers on i386 }
  10573. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10574. {$endif i386}
  10575. (((taicpu(hp1).ops=2) and
  10576. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10577. ((taicpu(hp1).ops=1) and
  10578. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10579. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10580. begin
  10581. { change movsX/movzX reg/ref, reg2
  10582. add/sub/or/... reg3/$const, reg2
  10583. mov reg2 reg/ref
  10584. to add/sub/or/... reg3/$const, reg/ref }
  10585. { by example:
  10586. movswl %si,%eax movswl %si,%eax p
  10587. decl %eax addl %edx,%eax hp1
  10588. movw %ax,%si movw %ax,%si hp2
  10589. ->
  10590. movswl %si,%eax movswl %si,%eax p
  10591. decw %eax addw %edx,%eax hp1
  10592. movw %ax,%si movw %ax,%si hp2
  10593. }
  10594. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10595. {
  10596. ->
  10597. movswl %si,%eax movswl %si,%eax p
  10598. decw %si addw %dx,%si hp1
  10599. movw %ax,%si movw %ax,%si hp2
  10600. }
  10601. case taicpu(hp1).ops of
  10602. 1:
  10603. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10604. 2:
  10605. begin
  10606. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10607. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10608. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10609. end;
  10610. else
  10611. internalerror(2008042702);
  10612. end;
  10613. {
  10614. ->
  10615. decw %si addw %dx,%si p
  10616. }
  10617. DebugMsg(SPeepholeOptimization + 'var3',p);
  10618. RemoveCurrentP(p, hp1);
  10619. RemoveInstruction(hp2);
  10620. Result := True;
  10621. Exit;
  10622. end;
  10623. if reg_and_hp1_is_instr and
  10624. (taicpu(hp1).opcode = A_MOV) and
  10625. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10626. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10627. {$ifdef x86_64}
  10628. { check for implicit extension to 64 bit }
  10629. or
  10630. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10631. (taicpu(hp1).opsize=S_Q) and
  10632. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10633. )
  10634. {$endif x86_64}
  10635. )
  10636. then
  10637. begin
  10638. { change
  10639. movx %reg1,%reg2
  10640. mov %reg2,%reg3
  10641. dealloc %reg2
  10642. into
  10643. movx %reg,%reg3
  10644. }
  10645. TransferUsedRegs(TmpUsedRegs);
  10646. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10647. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10648. begin
  10649. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10650. {$ifdef x86_64}
  10651. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10652. (taicpu(hp1).opsize=S_Q) then
  10653. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10654. else
  10655. {$endif x86_64}
  10656. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10657. RemoveInstruction(hp1);
  10658. Result := True;
  10659. Exit;
  10660. end;
  10661. end;
  10662. if reg_and_hp1_is_instr and
  10663. ((taicpu(hp1).opcode=A_MOV) or
  10664. (taicpu(hp1).opcode=A_ADD) or
  10665. (taicpu(hp1).opcode=A_SUB) or
  10666. (taicpu(hp1).opcode=A_CMP) or
  10667. (taicpu(hp1).opcode=A_OR) or
  10668. (taicpu(hp1).opcode=A_XOR) or
  10669. (taicpu(hp1).opcode=A_AND)
  10670. ) and
  10671. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10672. begin
  10673. AndTest := (taicpu(hp1).opcode=A_AND) and
  10674. GetNextInstruction(hp1, hp2) and
  10675. (hp2.typ = ait_instruction) and
  10676. (
  10677. (
  10678. (taicpu(hp2).opcode=A_TEST) and
  10679. (
  10680. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10681. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10682. (
  10683. { If the AND and TEST instructions share a constant, this is also valid }
  10684. (taicpu(hp1).oper[0]^.typ = top_const) and
  10685. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10686. )
  10687. ) and
  10688. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10689. ) or
  10690. (
  10691. (taicpu(hp2).opcode=A_CMP) and
  10692. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10693. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10694. )
  10695. );
  10696. { change
  10697. movx (oper),%reg2
  10698. and $x,%reg2
  10699. test %reg2,%reg2
  10700. dealloc %reg2
  10701. into
  10702. op %reg1,%reg3
  10703. if the second op accesses only the bits stored in reg1
  10704. }
  10705. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10706. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10707. (taicpu(hp1).oper[0]^.typ = top_const) and
  10708. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10709. AndTest then
  10710. begin
  10711. { Check if the AND constant is in range }
  10712. case taicpu(p).opsize of
  10713. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10714. begin
  10715. NewSize := S_B;
  10716. Limit := $FF;
  10717. end;
  10718. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10719. begin
  10720. NewSize := S_W;
  10721. Limit := $FFFF;
  10722. end;
  10723. {$ifdef x86_64}
  10724. S_LQ:
  10725. begin
  10726. NewSize := S_L;
  10727. Limit := $FFFFFFFF;
  10728. end;
  10729. {$endif x86_64}
  10730. else
  10731. InternalError(2021120303);
  10732. end;
  10733. if (
  10734. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10735. { Check for negative operands }
  10736. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10737. ) and
  10738. GetNextInstruction(hp2,hp3) and
  10739. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10740. (taicpu(hp3).condition in [C_E,C_NE]) then
  10741. begin
  10742. TransferUsedRegs(TmpUsedRegs);
  10743. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10744. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10745. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10746. begin
  10747. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10748. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10749. taicpu(hp1).opcode := A_TEST;
  10750. taicpu(hp1).opsize := NewSize;
  10751. RemoveInstruction(hp2);
  10752. RemoveCurrentP(p, hp1);
  10753. Result:=true;
  10754. exit;
  10755. end;
  10756. end;
  10757. end;
  10758. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10759. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10760. (taicpu(hp1).opsize=S_B)) or
  10761. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10762. (taicpu(hp1).opsize=S_W))
  10763. {$ifdef x86_64}
  10764. or ((taicpu(p).opsize=S_LQ) and
  10765. (taicpu(hp1).opsize=S_L))
  10766. {$endif x86_64}
  10767. ) and
  10768. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10769. begin
  10770. { change
  10771. movx %reg1,%reg2
  10772. op %reg2,%reg3
  10773. dealloc %reg2
  10774. into
  10775. op %reg1,%reg3
  10776. if the second op accesses only the bits stored in reg1
  10777. }
  10778. TransferUsedRegs(TmpUsedRegs);
  10779. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10780. if AndTest then
  10781. begin
  10782. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10783. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10784. end
  10785. else
  10786. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10787. if not RegUsed then
  10788. begin
  10789. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10790. if taicpu(p).oper[0]^.typ=top_reg then
  10791. begin
  10792. case taicpu(hp1).opsize of
  10793. S_B:
  10794. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10795. S_W:
  10796. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10797. S_L:
  10798. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10799. else
  10800. Internalerror(2020102301);
  10801. end;
  10802. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10803. end
  10804. else
  10805. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10806. RemoveCurrentP(p);
  10807. if AndTest then
  10808. RemoveInstruction(hp2);
  10809. result:=true;
  10810. exit;
  10811. end;
  10812. end
  10813. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10814. (
  10815. { Bitwise operations only }
  10816. (taicpu(hp1).opcode=A_AND) or
  10817. (taicpu(hp1).opcode=A_TEST) or
  10818. (
  10819. (taicpu(hp1).oper[0]^.typ = top_const) and
  10820. (
  10821. (taicpu(hp1).opcode=A_OR) or
  10822. (taicpu(hp1).opcode=A_XOR)
  10823. )
  10824. )
  10825. ) and
  10826. (
  10827. (taicpu(hp1).oper[0]^.typ = top_const) or
  10828. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10829. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10830. ) then
  10831. begin
  10832. { change
  10833. movx %reg2,%reg2
  10834. op const,%reg2
  10835. into
  10836. op const,%reg2 (smaller version)
  10837. movx %reg2,%reg2
  10838. also change
  10839. movx %reg1,%reg2
  10840. and/test (oper),%reg2
  10841. dealloc %reg2
  10842. into
  10843. and/test (oper),%reg1
  10844. }
  10845. case taicpu(p).opsize of
  10846. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10847. begin
  10848. NewSize := S_B;
  10849. NewRegSize := R_SUBL;
  10850. Limit := $FF;
  10851. end;
  10852. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10853. begin
  10854. NewSize := S_W;
  10855. NewRegSize := R_SUBW;
  10856. Limit := $FFFF;
  10857. end;
  10858. {$ifdef x86_64}
  10859. S_LQ:
  10860. begin
  10861. NewSize := S_L;
  10862. NewRegSize := R_SUBD;
  10863. Limit := $FFFFFFFF;
  10864. end;
  10865. {$endif x86_64}
  10866. else
  10867. Internalerror(2021120302);
  10868. end;
  10869. TransferUsedRegs(TmpUsedRegs);
  10870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10871. if AndTest then
  10872. begin
  10873. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10874. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10875. end
  10876. else
  10877. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10878. if
  10879. (
  10880. (taicpu(p).opcode = A_MOVZX) and
  10881. (
  10882. (taicpu(hp1).opcode=A_AND) or
  10883. (taicpu(hp1).opcode=A_TEST)
  10884. ) and
  10885. not (
  10886. { If both are references, then the final instruction will have
  10887. both operands as references, which is not allowed }
  10888. (taicpu(p).oper[0]^.typ = top_ref) and
  10889. (taicpu(hp1).oper[0]^.typ = top_ref)
  10890. ) and
  10891. not RegUsed
  10892. ) or
  10893. (
  10894. (
  10895. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10896. not RegUsed
  10897. ) and
  10898. (taicpu(p).oper[0]^.typ = top_reg) and
  10899. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10900. (taicpu(hp1).oper[0]^.typ = top_const) and
  10901. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10902. ) then
  10903. begin
  10904. {$if defined(i386) or defined(i8086)}
  10905. { If the target size is 8-bit, make sure we can actually encode it }
  10906. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10907. Exit;
  10908. {$endif i386 or i8086}
  10909. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10910. taicpu(hp1).opsize := NewSize;
  10911. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10912. if AndTest then
  10913. begin
  10914. RemoveInstruction(hp2);
  10915. if not RegUsed then
  10916. begin
  10917. taicpu(hp1).opcode := A_TEST;
  10918. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10919. begin
  10920. { Make sure the reference is the second operand }
  10921. SwapOper := taicpu(hp1).oper[0];
  10922. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10923. taicpu(hp1).oper[1] := SwapOper;
  10924. end;
  10925. end;
  10926. end;
  10927. case taicpu(hp1).oper[0]^.typ of
  10928. top_reg:
  10929. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10930. top_const:
  10931. { For the AND/TEST case }
  10932. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10933. else
  10934. ;
  10935. end;
  10936. if RegUsed then
  10937. begin
  10938. AsmL.Remove(p);
  10939. AsmL.InsertAfter(p, hp1);
  10940. p := hp1;
  10941. end
  10942. else
  10943. RemoveCurrentP(p, hp1);
  10944. result:=true;
  10945. exit;
  10946. end;
  10947. end;
  10948. end;
  10949. if reg_and_hp1_is_instr and
  10950. (taicpu(p).oper[0]^.typ = top_reg) and
  10951. (
  10952. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10953. ) and
  10954. (taicpu(hp1).oper[0]^.typ = top_const) and
  10955. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10956. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10957. { Minimum shift value allowed is the bit difference between the sizes }
  10958. (taicpu(hp1).oper[0]^.val >=
  10959. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10960. 8 * (
  10961. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10962. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10963. )
  10964. ) then
  10965. begin
  10966. { For:
  10967. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10968. shl/sal ##, %reg1
  10969. Remove the movsx/movzx instruction if the shift overwrites the
  10970. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10971. }
  10972. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10973. RemoveCurrentP(p, hp1);
  10974. Result := True;
  10975. Exit;
  10976. end
  10977. else if reg_and_hp1_is_instr and
  10978. (taicpu(p).oper[0]^.typ = top_reg) and
  10979. (
  10980. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10981. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10982. ) and
  10983. (taicpu(hp1).oper[0]^.typ = top_const) and
  10984. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10985. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10986. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10987. (taicpu(hp1).oper[0]^.val <
  10988. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10989. 8 * (
  10990. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10991. )
  10992. ) then
  10993. begin
  10994. { For:
  10995. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10996. sar ##, %reg1 shr ##, %reg1
  10997. Move the shift to before the movx instruction if the shift value
  10998. is not too large.
  10999. }
  11000. asml.Remove(hp1);
  11001. asml.InsertBefore(hp1, p);
  11002. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11003. case taicpu(p).opsize of
  11004. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11005. taicpu(hp1).opsize := S_B;
  11006. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11007. taicpu(hp1).opsize := S_W;
  11008. {$ifdef x86_64}
  11009. S_LQ:
  11010. taicpu(hp1).opsize := S_L;
  11011. {$endif}
  11012. else
  11013. InternalError(2020112401);
  11014. end;
  11015. if (taicpu(hp1).opcode = A_SHR) then
  11016. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11017. else
  11018. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11019. Result := True;
  11020. end;
  11021. if reg_and_hp1_is_instr and
  11022. (taicpu(p).oper[0]^.typ = top_reg) and
  11023. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11024. (
  11025. (taicpu(hp1).opcode = taicpu(p).opcode)
  11026. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11027. {$ifdef x86_64}
  11028. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11029. {$endif x86_64}
  11030. ) then
  11031. begin
  11032. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11033. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11034. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11035. begin
  11036. {
  11037. For example:
  11038. movzbw %al,%ax
  11039. movzwl %ax,%eax
  11040. Compress into:
  11041. movzbl %al,%eax
  11042. }
  11043. RegUsed := False;
  11044. case taicpu(p).opsize of
  11045. S_BW:
  11046. case taicpu(hp1).opsize of
  11047. S_WL:
  11048. begin
  11049. taicpu(p).opsize := S_BL;
  11050. RegUsed := True;
  11051. end;
  11052. {$ifdef x86_64}
  11053. S_WQ:
  11054. begin
  11055. if taicpu(p).opcode = A_MOVZX then
  11056. begin
  11057. taicpu(p).opsize := S_BL;
  11058. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11059. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11060. end
  11061. else
  11062. taicpu(p).opsize := S_BQ;
  11063. RegUsed := True;
  11064. end;
  11065. {$endif x86_64}
  11066. else
  11067. ;
  11068. end;
  11069. {$ifdef x86_64}
  11070. S_BL:
  11071. case taicpu(hp1).opsize of
  11072. S_LQ:
  11073. begin
  11074. if taicpu(p).opcode = A_MOVZX then
  11075. begin
  11076. taicpu(p).opsize := S_BL;
  11077. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11078. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11079. end
  11080. else
  11081. taicpu(p).opsize := S_BQ;
  11082. RegUsed := True;
  11083. end;
  11084. else
  11085. ;
  11086. end;
  11087. S_WL:
  11088. case taicpu(hp1).opsize of
  11089. S_LQ:
  11090. begin
  11091. if taicpu(p).opcode = A_MOVZX then
  11092. begin
  11093. taicpu(p).opsize := S_WL;
  11094. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11095. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11096. end
  11097. else
  11098. taicpu(p).opsize := S_WQ;
  11099. RegUsed := True;
  11100. end;
  11101. else
  11102. ;
  11103. end;
  11104. {$endif x86_64}
  11105. else
  11106. ;
  11107. end;
  11108. if RegUsed then
  11109. begin
  11110. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11111. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11112. RemoveInstruction(hp1);
  11113. Result := True;
  11114. Exit;
  11115. end;
  11116. end;
  11117. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11118. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11119. GetNextInstruction(hp1, hp2) and
  11120. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11121. (
  11122. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11123. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11124. {$ifdef x86_64}
  11125. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11126. {$endif x86_64}
  11127. ) and
  11128. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11129. (
  11130. (
  11131. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11132. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11133. ) or
  11134. (
  11135. { Only allow the operands in reverse order for TEST instructions }
  11136. (taicpu(hp2).opcode = A_TEST) and
  11137. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11138. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11139. )
  11140. ) then
  11141. begin
  11142. {
  11143. For example:
  11144. movzbl %al,%eax
  11145. movzbl (ref),%edx
  11146. andl %edx,%eax
  11147. (%edx deallocated)
  11148. Change to:
  11149. andb (ref),%al
  11150. movzbl %al,%eax
  11151. Rules are:
  11152. - First two instructions have the same opcode and opsize
  11153. - First instruction's operands are the same super-register
  11154. - Second instruction operates on a different register
  11155. - Third instruction is AND, OR, XOR or TEST
  11156. - Third instruction's operands are the destination registers of the first two instructions
  11157. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11158. - Second instruction's destination register is deallocated afterwards
  11159. }
  11160. TransferUsedRegs(TmpUsedRegs);
  11161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11162. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11163. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11164. begin
  11165. case taicpu(p).opsize of
  11166. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11167. NewSize := S_B;
  11168. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11169. NewSize := S_W;
  11170. {$ifdef x86_64}
  11171. S_LQ:
  11172. NewSize := S_L;
  11173. {$endif x86_64}
  11174. else
  11175. InternalError(2021120301);
  11176. end;
  11177. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11178. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11179. taicpu(hp2).opsize := NewSize;
  11180. RemoveInstruction(hp1);
  11181. { With TEST, it's best to keep the MOVX instruction at the top }
  11182. if (taicpu(hp2).opcode <> A_TEST) then
  11183. begin
  11184. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11185. asml.Remove(p);
  11186. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11187. asml.InsertAfter(p, hp2);
  11188. p := hp2;
  11189. end
  11190. else
  11191. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11192. Result := True;
  11193. Exit;
  11194. end;
  11195. end;
  11196. end;
  11197. if taicpu(p).opcode=A_MOVZX then
  11198. begin
  11199. { removes superfluous And's after movzx's }
  11200. if reg_and_hp1_is_instr and
  11201. (taicpu(hp1).opcode = A_AND) and
  11202. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11203. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11204. {$ifdef x86_64}
  11205. { check for implicit extension to 64 bit }
  11206. or
  11207. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11208. (taicpu(hp1).opsize=S_Q) and
  11209. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11210. )
  11211. {$endif x86_64}
  11212. )
  11213. then
  11214. begin
  11215. case taicpu(p).opsize Of
  11216. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11217. if (taicpu(hp1).oper[0]^.val = $ff) then
  11218. begin
  11219. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11220. RemoveInstruction(hp1);
  11221. Result:=true;
  11222. exit;
  11223. end;
  11224. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11225. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11226. begin
  11227. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11228. RemoveInstruction(hp1);
  11229. Result:=true;
  11230. exit;
  11231. end;
  11232. {$ifdef x86_64}
  11233. S_LQ:
  11234. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11235. begin
  11236. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11237. RemoveInstruction(hp1);
  11238. Result:=true;
  11239. exit;
  11240. end;
  11241. {$endif x86_64}
  11242. else
  11243. ;
  11244. end;
  11245. { we cannot get rid of the and, but can we get rid of the movz ?}
  11246. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11247. begin
  11248. case taicpu(p).opsize Of
  11249. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11250. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11251. begin
  11252. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11253. RemoveCurrentP(p,hp1);
  11254. Result:=true;
  11255. exit;
  11256. end;
  11257. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11258. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11259. begin
  11260. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11261. RemoveCurrentP(p,hp1);
  11262. Result:=true;
  11263. exit;
  11264. end;
  11265. {$ifdef x86_64}
  11266. S_LQ:
  11267. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11268. begin
  11269. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11270. RemoveCurrentP(p,hp1);
  11271. Result:=true;
  11272. exit;
  11273. end;
  11274. {$endif x86_64}
  11275. else
  11276. ;
  11277. end;
  11278. end;
  11279. end;
  11280. { changes some movzx constructs to faster synonyms (all examples
  11281. are given with eax/ax, but are also valid for other registers)}
  11282. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11283. begin
  11284. case taicpu(p).opsize of
  11285. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11286. (the machine code is equivalent to movzbl %al,%eax), but the
  11287. code generator still generates that assembler instruction and
  11288. it is silently converted. This should probably be checked.
  11289. [Kit] }
  11290. S_BW:
  11291. begin
  11292. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11293. (
  11294. not IsMOVZXAcceptable
  11295. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11296. or (
  11297. (cs_opt_size in current_settings.optimizerswitches) and
  11298. (taicpu(p).oper[1]^.reg = NR_AX)
  11299. )
  11300. ) then
  11301. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11302. begin
  11303. DebugMsg(SPeepholeOptimization + 'var7',p);
  11304. taicpu(p).opcode := A_AND;
  11305. taicpu(p).changeopsize(S_W);
  11306. taicpu(p).loadConst(0,$ff);
  11307. Result := True;
  11308. end
  11309. else if not IsMOVZXAcceptable and
  11310. GetNextInstruction(p, hp1) and
  11311. (tai(hp1).typ = ait_instruction) and
  11312. (taicpu(hp1).opcode = A_AND) and
  11313. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11314. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11315. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11316. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11317. begin
  11318. DebugMsg(SPeepholeOptimization + 'var8',p);
  11319. taicpu(p).opcode := A_MOV;
  11320. taicpu(p).changeopsize(S_W);
  11321. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11322. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11323. Result := True;
  11324. end;
  11325. end;
  11326. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11327. S_BL:
  11328. if not IsMOVZXAcceptable then
  11329. begin
  11330. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11331. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11332. begin
  11333. DebugMsg(SPeepholeOptimization + 'var9',p);
  11334. taicpu(p).opcode := A_AND;
  11335. taicpu(p).changeopsize(S_L);
  11336. taicpu(p).loadConst(0,$ff);
  11337. Result := True;
  11338. end
  11339. else if GetNextInstruction(p, hp1) and
  11340. (tai(hp1).typ = ait_instruction) and
  11341. (taicpu(hp1).opcode = A_AND) and
  11342. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11343. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11344. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11345. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11346. begin
  11347. DebugMsg(SPeepholeOptimization + 'var10',p);
  11348. taicpu(p).opcode := A_MOV;
  11349. taicpu(p).changeopsize(S_L);
  11350. { do not use R_SUBWHOLE
  11351. as movl %rdx,%eax
  11352. is invalid in assembler PM }
  11353. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11354. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11355. Result := True;
  11356. end;
  11357. end;
  11358. {$endif i8086}
  11359. S_WL:
  11360. if not IsMOVZXAcceptable then
  11361. begin
  11362. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11363. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11364. begin
  11365. DebugMsg(SPeepholeOptimization + 'var11',p);
  11366. taicpu(p).opcode := A_AND;
  11367. taicpu(p).changeopsize(S_L);
  11368. taicpu(p).loadConst(0,$ffff);
  11369. Result := True;
  11370. end
  11371. else if GetNextInstruction(p, hp1) and
  11372. (tai(hp1).typ = ait_instruction) and
  11373. (taicpu(hp1).opcode = A_AND) and
  11374. (taicpu(hp1).oper[0]^.typ = top_const) and
  11375. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11376. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11377. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11378. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11379. begin
  11380. DebugMsg(SPeepholeOptimization + 'var12',p);
  11381. taicpu(p).opcode := A_MOV;
  11382. taicpu(p).changeopsize(S_L);
  11383. { do not use R_SUBWHOLE
  11384. as movl %rdx,%eax
  11385. is invalid in assembler PM }
  11386. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11387. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11388. Result := True;
  11389. end;
  11390. end;
  11391. else
  11392. InternalError(2017050705);
  11393. end;
  11394. end
  11395. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11396. begin
  11397. if GetNextInstruction(p, hp1) and
  11398. (tai(hp1).typ = ait_instruction) and
  11399. (taicpu(hp1).opcode = A_AND) and
  11400. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11401. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11402. begin
  11403. //taicpu(p).opcode := A_MOV;
  11404. case taicpu(p).opsize Of
  11405. S_BL:
  11406. begin
  11407. DebugMsg(SPeepholeOptimization + 'var13',p);
  11408. taicpu(hp1).changeopsize(S_L);
  11409. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11410. end;
  11411. S_WL:
  11412. begin
  11413. DebugMsg(SPeepholeOptimization + 'var14',p);
  11414. taicpu(hp1).changeopsize(S_L);
  11415. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11416. end;
  11417. S_BW:
  11418. begin
  11419. DebugMsg(SPeepholeOptimization + 'var15',p);
  11420. taicpu(hp1).changeopsize(S_W);
  11421. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11422. end;
  11423. else
  11424. Internalerror(2017050704)
  11425. end;
  11426. Result := True;
  11427. end;
  11428. end;
  11429. end;
  11430. end;
  11431. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11432. var
  11433. hp1, hp2 : tai;
  11434. MaskLength : Cardinal;
  11435. MaskedBits : TCgInt;
  11436. ActiveReg : TRegister;
  11437. begin
  11438. Result:=false;
  11439. { There are no optimisations for reference targets }
  11440. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11441. Exit;
  11442. while GetNextInstruction(p, hp1) and
  11443. (hp1.typ = ait_instruction) do
  11444. begin
  11445. if (taicpu(p).oper[0]^.typ = top_const) then
  11446. begin
  11447. case taicpu(hp1).opcode of
  11448. A_AND:
  11449. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11450. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11451. { the second register must contain the first one, so compare their subreg types }
  11452. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11453. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11454. { change
  11455. and const1, reg
  11456. and const2, reg
  11457. to
  11458. and (const1 and const2), reg
  11459. }
  11460. begin
  11461. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11462. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11463. RemoveCurrentP(p, hp1);
  11464. Result:=true;
  11465. exit;
  11466. end;
  11467. A_CMP:
  11468. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11469. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11470. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11471. { Just check that the condition on the next instruction is compatible }
  11472. GetNextInstruction(hp1, hp2) and
  11473. (hp2.typ = ait_instruction) and
  11474. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11475. then
  11476. { change
  11477. and 2^n, reg
  11478. cmp 2^n, reg
  11479. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11480. to
  11481. and 2^n, reg
  11482. test reg, reg
  11483. j(~c) / set(~c) / cmov(~c)
  11484. }
  11485. begin
  11486. { Keep TEST instruction in, rather than remove it, because
  11487. it may trigger other optimisations such as MovAndTest2Test }
  11488. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11489. taicpu(hp1).opcode := A_TEST;
  11490. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11491. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11492. Result := True;
  11493. Exit;
  11494. end;
  11495. A_MOVZX:
  11496. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11497. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11498. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11499. (
  11500. (
  11501. (taicpu(p).opsize=S_W) and
  11502. (taicpu(hp1).opsize=S_BW)
  11503. ) or
  11504. (
  11505. (taicpu(p).opsize=S_L) and
  11506. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11507. )
  11508. {$ifdef x86_64}
  11509. or
  11510. (
  11511. (taicpu(p).opsize=S_Q) and
  11512. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11513. )
  11514. {$endif x86_64}
  11515. ) then
  11516. begin
  11517. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11518. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11519. ) or
  11520. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11521. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11522. then
  11523. begin
  11524. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11525. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11526. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11527. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11528. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11529. }
  11530. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11531. RemoveInstruction(hp1);
  11532. { See if there are other optimisations possible }
  11533. Continue;
  11534. end;
  11535. end;
  11536. A_SHL:
  11537. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11538. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11539. begin
  11540. {$ifopt R+}
  11541. {$define RANGE_WAS_ON}
  11542. {$R-}
  11543. {$endif}
  11544. { get length of potential and mask }
  11545. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11546. { really a mask? }
  11547. {$ifdef RANGE_WAS_ON}
  11548. {$R+}
  11549. {$endif}
  11550. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11551. { unmasked part shifted out? }
  11552. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11553. begin
  11554. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11555. RemoveCurrentP(p, hp1);
  11556. Result:=true;
  11557. exit;
  11558. end;
  11559. end;
  11560. A_SHR:
  11561. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11562. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11563. (taicpu(hp1).oper[0]^.val <= 63) then
  11564. begin
  11565. { Does SHR combined with the AND cover all the bits?
  11566. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11567. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11568. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11569. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11570. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11571. begin
  11572. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11573. RemoveCurrentP(p, hp1);
  11574. Result := True;
  11575. Exit;
  11576. end;
  11577. end;
  11578. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11579. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11580. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11581. begin
  11582. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11583. (
  11584. (
  11585. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11586. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11587. ) or (
  11588. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11589. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11590. {$ifdef x86_64}
  11591. ) or (
  11592. (taicpu(hp1).opsize = S_LQ) and
  11593. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11594. {$endif x86_64}
  11595. )
  11596. ) then
  11597. begin
  11598. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11599. begin
  11600. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11601. RemoveInstruction(hp1);
  11602. { See if there are other optimisations possible }
  11603. Continue;
  11604. end;
  11605. { The super-registers are the same though.
  11606. Note that this change by itself doesn't improve
  11607. code speed, but it opens up other optimisations. }
  11608. {$ifdef x86_64}
  11609. { Convert 64-bit register to 32-bit }
  11610. case taicpu(hp1).opsize of
  11611. S_BQ:
  11612. begin
  11613. taicpu(hp1).opsize := S_BL;
  11614. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11615. end;
  11616. S_WQ:
  11617. begin
  11618. taicpu(hp1).opsize := S_WL;
  11619. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11620. end
  11621. else
  11622. ;
  11623. end;
  11624. {$endif x86_64}
  11625. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11626. taicpu(hp1).opcode := A_MOVZX;
  11627. { See if there are other optimisations possible }
  11628. Continue;
  11629. end;
  11630. end;
  11631. else
  11632. ;
  11633. end;
  11634. end
  11635. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11636. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11637. begin
  11638. {$ifdef x86_64}
  11639. if (taicpu(p).opsize = S_Q) then
  11640. begin
  11641. { Never necessary }
  11642. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11643. RemoveCurrentP(p, hp1);
  11644. Result := True;
  11645. Exit;
  11646. end;
  11647. {$endif x86_64}
  11648. { Forward check to determine necessity of and %reg,%reg }
  11649. TransferUsedRegs(TmpUsedRegs);
  11650. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11651. { Saves on a bunch of dereferences }
  11652. ActiveReg := taicpu(p).oper[1]^.reg;
  11653. case taicpu(hp1).opcode of
  11654. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11655. if (
  11656. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11657. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11658. ) and
  11659. (
  11660. (taicpu(hp1).opcode <> A_MOV) or
  11661. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11662. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11663. ) and
  11664. not (
  11665. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11666. (taicpu(hp1).opcode = A_MOV) and
  11667. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11668. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11669. ) and
  11670. (
  11671. (
  11672. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11673. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11674. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11675. ) or
  11676. (
  11677. {$ifdef x86_64}
  11678. (
  11679. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11680. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11681. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11682. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11683. ) and
  11684. {$endif x86_64}
  11685. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11686. )
  11687. ) then
  11688. begin
  11689. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11690. RemoveCurrentP(p, hp1);
  11691. Result := True;
  11692. Exit;
  11693. end;
  11694. A_ADD,
  11695. A_AND,
  11696. A_BSF,
  11697. A_BSR,
  11698. A_BTC,
  11699. A_BTR,
  11700. A_BTS,
  11701. A_OR,
  11702. A_SUB,
  11703. A_XOR:
  11704. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11705. if (
  11706. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11707. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11708. ) and
  11709. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11710. begin
  11711. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11712. RemoveCurrentP(p, hp1);
  11713. Result := True;
  11714. Exit;
  11715. end;
  11716. A_CMP,
  11717. A_TEST:
  11718. if (
  11719. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11720. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11721. ) and
  11722. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11723. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11724. begin
  11725. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11726. RemoveCurrentP(p, hp1);
  11727. Result := True;
  11728. Exit;
  11729. end;
  11730. A_BSWAP,
  11731. A_NEG,
  11732. A_NOT:
  11733. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11734. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11735. begin
  11736. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11737. RemoveCurrentP(p, hp1);
  11738. Result := True;
  11739. Exit;
  11740. end;
  11741. else
  11742. ;
  11743. end;
  11744. end;
  11745. if (taicpu(hp1).is_jmp) and
  11746. (taicpu(hp1).opcode<>A_JMP) and
  11747. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11748. begin
  11749. { change
  11750. and x, reg
  11751. jxx
  11752. to
  11753. test x, reg
  11754. jxx
  11755. if reg is deallocated before the
  11756. jump, but only if it's a conditional jump (PFV)
  11757. }
  11758. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  11759. taicpu(p).opcode := A_TEST;
  11760. Exit;
  11761. end;
  11762. Break;
  11763. end;
  11764. { Lone AND tests }
  11765. if (taicpu(p).oper[0]^.typ = top_const) then
  11766. begin
  11767. {
  11768. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11769. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11770. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11771. }
  11772. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11773. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11774. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11775. begin
  11776. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11777. if taicpu(p).opsize = S_L then
  11778. begin
  11779. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11780. Result := True;
  11781. end;
  11782. end;
  11783. end;
  11784. { Backward check to determine necessity of and %reg,%reg }
  11785. if (taicpu(p).oper[0]^.typ = top_reg) and
  11786. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11787. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11788. GetLastInstruction(p, hp2) and
  11789. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11790. { Check size of adjacent instruction to determine if the AND is
  11791. effectively a null operation }
  11792. (
  11793. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11794. { Note: Don't include S_Q }
  11795. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11796. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11797. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11798. ) then
  11799. begin
  11800. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11801. { If GetNextInstruction returned False, hp1 will be nil }
  11802. RemoveCurrentP(p, hp1);
  11803. Result := True;
  11804. Exit;
  11805. end;
  11806. end;
  11807. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11808. var
  11809. hp1, hp2: tai;
  11810. NewRef: TReference;
  11811. Distance: Cardinal;
  11812. TempTracking: TAllUsedRegs;
  11813. { This entire nested function is used in an if-statement below, but we
  11814. want to avoid all the used reg transfers and GetNextInstruction calls
  11815. until we really have to check }
  11816. function MemRegisterNotUsedLater: Boolean; inline;
  11817. var
  11818. hp2: tai;
  11819. begin
  11820. TransferUsedRegs(TmpUsedRegs);
  11821. hp2 := p;
  11822. repeat
  11823. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11824. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11825. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11826. end;
  11827. begin
  11828. Result := False;
  11829. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11830. (taicpu(p).oper[1]^.typ = top_reg) then
  11831. begin
  11832. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11833. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11834. (hp1.typ <> ait_instruction) or
  11835. not
  11836. (
  11837. (cs_opt_level3 in current_settings.optimizerswitches) or
  11838. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11839. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11840. ) then
  11841. Exit;
  11842. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11843. addq $x, %rax
  11844. movq %rax, %rdx
  11845. sarq $63, %rdx
  11846. (%rax still in use)
  11847. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11848. leaq $x(%rax),%rdx
  11849. addq $x, %rax
  11850. sarq $63, %rdx
  11851. ...which is okay since it breaks the dependency chain between
  11852. addq and movq, but if OptPass2MOV is called first:
  11853. addq $x, %rax
  11854. cqto
  11855. ...which is better in all ways, taking only 2 cycles to execute
  11856. and much smaller in code size.
  11857. }
  11858. { The extra register tracking is quite strenuous }
  11859. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11860. MatchInstruction(hp1, A_MOV, []) then
  11861. begin
  11862. { Update the register tracking to the MOV instruction }
  11863. CopyUsedRegs(TempTracking);
  11864. hp2 := p;
  11865. repeat
  11866. UpdateUsedRegs(tai(hp2.Next));
  11867. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11868. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11869. OptPass2ADD get called again }
  11870. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11871. begin
  11872. { Reset the tracking to the current instruction }
  11873. RestoreUsedRegs(TempTracking);
  11874. ReleaseUsedRegs(TempTracking);
  11875. Result := True;
  11876. Exit;
  11877. end;
  11878. { Reset the tracking to the current instruction }
  11879. RestoreUsedRegs(TempTracking);
  11880. ReleaseUsedRegs(TempTracking);
  11881. { If OptPass2MOV returned True, we don't need to set Result to
  11882. True if hp1 didn't change because the ADD instruction didn't
  11883. get modified and we'll be evaluating hp1 again when the
  11884. peephole optimizer reaches it }
  11885. end;
  11886. { Change:
  11887. add %reg2,%reg1
  11888. (%reg2 not modified in between)
  11889. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11890. To:
  11891. mov/s/z #(%reg1,%reg2),%reg1
  11892. }
  11893. if (taicpu(p).oper[0]^.typ = top_reg) and
  11894. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11895. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11896. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11897. (
  11898. (
  11899. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11900. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11901. { r/esp cannot be an index }
  11902. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11903. ) or (
  11904. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11905. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11906. )
  11907. ) and (
  11908. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11909. (
  11910. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11911. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11912. MemRegisterNotUsedLater
  11913. )
  11914. ) then
  11915. begin
  11916. if (
  11917. { Instructions are guaranteed to be adjacent on -O2 and under }
  11918. (cs_opt_level3 in current_settings.optimizerswitches) and
  11919. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  11920. ) then
  11921. begin
  11922. { If the other register is used in between, move the MOV
  11923. instruction to right after the ADD instruction so a
  11924. saving can still be made }
  11925. Asml.Remove(hp1);
  11926. Asml.InsertAfter(hp1, p);
  11927. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11928. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11929. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  11930. RemoveCurrentp(p, hp1);
  11931. end
  11932. else
  11933. begin
  11934. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11935. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11936. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11937. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11938. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11939. { hp1 may not be the immediate next instruction under -O3 }
  11940. RemoveCurrentp(p)
  11941. else
  11942. RemoveCurrentp(p, hp1);
  11943. end;
  11944. Result := True;
  11945. Exit;
  11946. end;
  11947. { Change:
  11948. addl/q $x,%reg1
  11949. movl/q %reg1,%reg2
  11950. To:
  11951. leal/q $x(%reg1),%reg2
  11952. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11953. Breaks the dependency chain.
  11954. }
  11955. if (taicpu(p).oper[0]^.typ = top_const) and
  11956. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11957. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11958. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11959. (
  11960. { Instructions are guaranteed to be adjacent on -O2 and under }
  11961. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11962. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11963. ) then
  11964. begin
  11965. TransferUsedRegs(TmpUsedRegs);
  11966. hp2 := p;
  11967. repeat
  11968. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11969. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11970. if (
  11971. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11972. not (cs_opt_size in current_settings.optimizerswitches) or
  11973. (
  11974. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11975. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11976. )
  11977. ) then
  11978. begin
  11979. { Change the MOV instruction to a LEA instruction, and update the
  11980. first operand }
  11981. reference_reset(NewRef, 1, []);
  11982. NewRef.base := taicpu(p).oper[1]^.reg;
  11983. NewRef.scalefactor := 1;
  11984. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11985. taicpu(hp1).opcode := A_LEA;
  11986. taicpu(hp1).loadref(0, NewRef);
  11987. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11988. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11989. begin
  11990. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11991. { Move what is now the LEA instruction to before the ADD instruction }
  11992. Asml.Remove(hp1);
  11993. Asml.InsertBefore(hp1, p);
  11994. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11995. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11996. p := hp1;
  11997. end
  11998. else
  11999. begin
  12000. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12001. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12002. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12003. { hp1 may not be the immediate next instruction under -O3 }
  12004. RemoveCurrentp(p)
  12005. else
  12006. RemoveCurrentp(p, hp1);
  12007. end;
  12008. Result := True;
  12009. end;
  12010. end;
  12011. end;
  12012. end;
  12013. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12014. var
  12015. SubReg: TSubRegister;
  12016. begin
  12017. Result:=false;
  12018. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12019. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12020. with taicpu(p).oper[0]^.ref^ do
  12021. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12022. begin
  12023. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12024. begin
  12025. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12026. taicpu(p).opcode := A_ADD;
  12027. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12028. Result := True;
  12029. end
  12030. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12031. begin
  12032. if (base <> NR_NO) then
  12033. begin
  12034. if (scalefactor <= 1) then
  12035. begin
  12036. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12037. taicpu(p).opcode := A_ADD;
  12038. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12039. Result := True;
  12040. end;
  12041. end
  12042. else
  12043. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12044. if (scalefactor in [2, 4, 8]) then
  12045. begin
  12046. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12047. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12048. taicpu(p).opcode := A_SHL;
  12049. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12050. Result := True;
  12051. end;
  12052. end;
  12053. end;
  12054. end;
  12055. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12056. var
  12057. hp1, hp2: tai;
  12058. NewRef: TReference;
  12059. Distance: Cardinal;
  12060. TempTracking: TAllUsedRegs;
  12061. begin
  12062. Result := False;
  12063. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12064. MatchOpType(taicpu(p),top_const,top_reg) then
  12065. begin
  12066. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12067. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12068. (hp1.typ <> ait_instruction) or
  12069. not
  12070. (
  12071. (cs_opt_level3 in current_settings.optimizerswitches) or
  12072. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12073. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12074. ) then
  12075. Exit;
  12076. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12077. subq $x, %rax
  12078. movq %rax, %rdx
  12079. sarq $63, %rdx
  12080. (%rax still in use)
  12081. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12082. leaq $-x(%rax),%rdx
  12083. movq $x, %rax
  12084. sarq $63, %rdx
  12085. ...which is okay since it breaks the dependency chain between
  12086. subq and movq, but if OptPass2MOV is called first:
  12087. subq $x, %rax
  12088. cqto
  12089. ...which is better in all ways, taking only 2 cycles to execute
  12090. and much smaller in code size.
  12091. }
  12092. { The extra register tracking is quite strenuous }
  12093. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12094. MatchInstruction(hp1, A_MOV, []) then
  12095. begin
  12096. { Update the register tracking to the MOV instruction }
  12097. CopyUsedRegs(TempTracking);
  12098. hp2 := p;
  12099. repeat
  12100. UpdateUsedRegs(tai(hp2.Next));
  12101. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12102. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12103. OptPass2SUB get called again }
  12104. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12105. begin
  12106. { Reset the tracking to the current instruction }
  12107. RestoreUsedRegs(TempTracking);
  12108. ReleaseUsedRegs(TempTracking);
  12109. Result := True;
  12110. Exit;
  12111. end;
  12112. { Reset the tracking to the current instruction }
  12113. RestoreUsedRegs(TempTracking);
  12114. ReleaseUsedRegs(TempTracking);
  12115. { If OptPass2MOV returned True, we don't need to set Result to
  12116. True if hp1 didn't change because the SUB instruction didn't
  12117. get modified and we'll be evaluating hp1 again when the
  12118. peephole optimizer reaches it }
  12119. end;
  12120. { Change:
  12121. subl/q $x,%reg1
  12122. movl/q %reg1,%reg2
  12123. To:
  12124. leal/q $-x(%reg1),%reg2
  12125. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12126. Breaks the dependency chain and potentially permits the removal of
  12127. a CMP instruction if one follows.
  12128. }
  12129. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12130. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12131. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12132. (
  12133. { Instructions are guaranteed to be adjacent on -O2 and under }
  12134. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12135. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12136. ) then
  12137. begin
  12138. TransferUsedRegs(TmpUsedRegs);
  12139. hp2 := p;
  12140. repeat
  12141. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12142. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12143. if (
  12144. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12145. not (cs_opt_size in current_settings.optimizerswitches) or
  12146. (
  12147. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12148. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12149. )
  12150. ) then
  12151. begin
  12152. { Change the MOV instruction to a LEA instruction, and update the
  12153. first operand }
  12154. reference_reset(NewRef, 1, []);
  12155. NewRef.base := taicpu(p).oper[1]^.reg;
  12156. NewRef.scalefactor := 1;
  12157. NewRef.offset := -taicpu(p).oper[0]^.val;
  12158. taicpu(hp1).opcode := A_LEA;
  12159. taicpu(hp1).loadref(0, NewRef);
  12160. TransferUsedRegs(TmpUsedRegs);
  12161. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12162. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12163. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12164. begin
  12165. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12166. { Move what is now the LEA instruction to before the SUB instruction }
  12167. Asml.Remove(hp1);
  12168. Asml.InsertBefore(hp1, p);
  12169. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12170. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12171. p := hp1;
  12172. end
  12173. else
  12174. begin
  12175. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12176. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12177. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12178. { hp1 may not be the immediate next instruction under -O3 }
  12179. RemoveCurrentp(p)
  12180. else
  12181. RemoveCurrentp(p, hp1);
  12182. end;
  12183. Result := True;
  12184. end;
  12185. end;
  12186. end;
  12187. end;
  12188. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12189. begin
  12190. { we can skip all instructions not messing with the stack pointer }
  12191. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12192. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12193. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12194. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12195. ({(taicpu(hp1).ops=0) or }
  12196. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12197. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12198. ) and }
  12199. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12200. )
  12201. ) do
  12202. GetNextInstruction(hp1,hp1);
  12203. Result:=assigned(hp1);
  12204. end;
  12205. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12206. var
  12207. hp1, hp2, hp3, hp4, hp5: tai;
  12208. begin
  12209. Result:=false;
  12210. hp5:=nil;
  12211. { replace
  12212. leal(q) x(<stackpointer>),<stackpointer>
  12213. call procname
  12214. leal(q) -x(<stackpointer>),<stackpointer>
  12215. ret
  12216. by
  12217. jmp procname
  12218. but do it only on level 4 because it destroys stack back traces
  12219. }
  12220. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12221. MatchOpType(taicpu(p),top_ref,top_reg) and
  12222. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12223. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12224. { the -8 or -24 are not required, but bail out early if possible,
  12225. higher values are unlikely }
  12226. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12227. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12228. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12229. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12230. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12231. GetNextInstruction(p, hp1) and
  12232. { Take a copy of hp1 }
  12233. SetAndTest(hp1, hp4) and
  12234. { trick to skip label }
  12235. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12236. SkipSimpleInstructions(hp1) and
  12237. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12238. GetNextInstruction(hp1, hp2) and
  12239. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12240. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12241. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12242. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12243. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12244. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12245. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12246. { Segment register will be NR_NO }
  12247. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12248. GetNextInstruction(hp2, hp3) and
  12249. { trick to skip label }
  12250. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12251. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12252. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12253. SetAndTest(hp3,hp5) and
  12254. GetNextInstruction(hp3,hp3) and
  12255. MatchInstruction(hp3,A_RET,[S_NO])
  12256. )
  12257. ) and
  12258. (taicpu(hp3).ops=0) then
  12259. begin
  12260. taicpu(hp1).opcode := A_JMP;
  12261. taicpu(hp1).is_jmp := true;
  12262. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12263. RemoveCurrentP(p, hp4);
  12264. RemoveInstruction(hp2);
  12265. RemoveInstruction(hp3);
  12266. if Assigned(hp5) then
  12267. begin
  12268. AsmL.Remove(hp5);
  12269. ASmL.InsertBefore(hp5,hp1)
  12270. end;
  12271. Result:=true;
  12272. end;
  12273. end;
  12274. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12275. {$ifdef x86_64}
  12276. var
  12277. hp1, hp2, hp3, hp4, hp5: tai;
  12278. {$endif x86_64}
  12279. begin
  12280. Result:=false;
  12281. {$ifdef x86_64}
  12282. hp5:=nil;
  12283. { replace
  12284. push %rax
  12285. call procname
  12286. pop %rcx
  12287. ret
  12288. by
  12289. jmp procname
  12290. but do it only on level 4 because it destroys stack back traces
  12291. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12292. for all supported calling conventions
  12293. }
  12294. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12295. MatchOpType(taicpu(p),top_reg) and
  12296. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12297. GetNextInstruction(p, hp1) and
  12298. { Take a copy of hp1 }
  12299. SetAndTest(hp1, hp4) and
  12300. { trick to skip label }
  12301. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12302. SkipSimpleInstructions(hp1) and
  12303. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12304. GetNextInstruction(hp1, hp2) and
  12305. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12306. MatchOpType(taicpu(hp2),top_reg) and
  12307. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12308. GetNextInstruction(hp2, hp3) and
  12309. { trick to skip label }
  12310. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12311. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12312. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12313. SetAndTest(hp3,hp5) and
  12314. GetNextInstruction(hp3,hp3) and
  12315. MatchInstruction(hp3,A_RET,[S_NO])
  12316. )
  12317. ) and
  12318. (taicpu(hp3).ops=0) then
  12319. begin
  12320. taicpu(hp1).opcode := A_JMP;
  12321. taicpu(hp1).is_jmp := true;
  12322. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12323. RemoveCurrentP(p, hp4);
  12324. RemoveInstruction(hp2);
  12325. RemoveInstruction(hp3);
  12326. if Assigned(hp5) then
  12327. begin
  12328. AsmL.Remove(hp5);
  12329. ASmL.InsertBefore(hp5,hp1)
  12330. end;
  12331. Result:=true;
  12332. end;
  12333. {$endif x86_64}
  12334. end;
  12335. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12336. var
  12337. Value, RegName: string;
  12338. begin
  12339. Result:=false;
  12340. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12341. begin
  12342. case taicpu(p).oper[0]^.val of
  12343. 0:
  12344. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12345. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12346. begin
  12347. { change "mov $0,%reg" into "xor %reg,%reg" }
  12348. taicpu(p).opcode := A_XOR;
  12349. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12350. Result := True;
  12351. {$ifdef x86_64}
  12352. end
  12353. else if (taicpu(p).opsize = S_Q) then
  12354. begin
  12355. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12356. { The actual optimization }
  12357. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12358. taicpu(p).changeopsize(S_L);
  12359. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12360. Result := True;
  12361. end;
  12362. $1..$FFFFFFFF:
  12363. begin
  12364. { Code size reduction by J. Gareth "Kit" Moreton }
  12365. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12366. case taicpu(p).opsize of
  12367. S_Q:
  12368. begin
  12369. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12370. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12371. { The actual optimization }
  12372. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12373. taicpu(p).changeopsize(S_L);
  12374. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12375. Result := True;
  12376. end;
  12377. else
  12378. { Do nothing };
  12379. end;
  12380. {$endif x86_64}
  12381. end;
  12382. -1:
  12383. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12384. if (cs_opt_size in current_settings.optimizerswitches) and
  12385. (taicpu(p).opsize <> S_B) and
  12386. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12387. begin
  12388. { change "mov $-1,%reg" into "or $-1,%reg" }
  12389. { NOTES:
  12390. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12391. - This operation creates a false dependency on the register, so only do it when optimising for size
  12392. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  12393. }
  12394. taicpu(p).opcode := A_OR;
  12395. Result := True;
  12396. end;
  12397. else
  12398. { Do nothing };
  12399. end;
  12400. end;
  12401. end;
  12402. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  12403. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  12404. begin
  12405. Result := False;
  12406. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  12407. Exit;
  12408. { For sizes less than S_L, the byte size is equal or larger with BTx,
  12409. so don't bother optimising }
  12410. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12411. Exit;
  12412. if (taicpu(p).oper[0]^.typ <> top_const) or
  12413. { If the value can fit into an 8-bit signed integer, a smaller
  12414. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  12415. falls within this range }
  12416. (
  12417. (taicpu(p).oper[0]^.val > -128) and
  12418. (taicpu(p).oper[0]^.val <= 127)
  12419. ) then
  12420. Exit;
  12421. { If we're optimising for size, this is acceptable }
  12422. if (cs_opt_size in current_settings.optimizerswitches) then
  12423. Exit(True);
  12424. if (taicpu(p).oper[1]^.typ = top_reg) and
  12425. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12426. Exit(True);
  12427. if (taicpu(p).oper[1]^.typ <> top_reg) and
  12428. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12429. Exit(True);
  12430. end;
  12431. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12432. var
  12433. hp1: tai;
  12434. Value: TCGInt;
  12435. begin
  12436. Result := False;
  12437. if MatchOpType(taicpu(p), top_const, top_reg) then
  12438. begin
  12439. { Detect:
  12440. andw x, %ax (0 <= x < $8000)
  12441. ...
  12442. movzwl %ax,%eax
  12443. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12444. }
  12445. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12446. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12447. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12448. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12449. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12450. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12451. begin
  12452. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12453. taicpu(hp1).opcode := A_CWDE;
  12454. taicpu(hp1).clearop(0);
  12455. taicpu(hp1).clearop(1);
  12456. taicpu(hp1).ops := 0;
  12457. { A change was made, but not with p, so move forward 1 }
  12458. p := tai(p.Next);
  12459. Result := True;
  12460. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  12461. end;
  12462. end;
  12463. { If "not x" is a power of 2 (popcnt = 1), change:
  12464. and $x, %reg/ref
  12465. To:
  12466. btr lb(x), %reg/ref
  12467. }
  12468. if IsBTXAcceptable(p) and
  12469. (
  12470. { Make sure a TEST doesn't follow that plays with the register }
  12471. not GetNextInstruction(p, hp1) or
  12472. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  12473. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  12474. ) then
  12475. begin
  12476. {$push}{$R-}{$Q-}
  12477. { Value is a sign-extended 32-bit integer - just correct it
  12478. if it's represented as an unsigned value. Also, IsBTXAcceptable
  12479. checks to see if this operand is an immediate. }
  12480. Value := not taicpu(p).oper[0]^.val;
  12481. {$pop}
  12482. {$ifdef x86_64}
  12483. if taicpu(p).opsize = S_L then
  12484. {$endif x86_64}
  12485. Value := Value and $FFFFFFFF;
  12486. if (PopCnt(QWord(Value)) = 1) then
  12487. begin
  12488. DebugMsg(SPeepholeOptimization + 'Changed AND (not $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ') to BTR ' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  12489. taicpu(p).opcode := A_BTR;
  12490. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  12491. Result := True;
  12492. Exit;
  12493. end;
  12494. end;
  12495. end;
  12496. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12497. begin
  12498. Result := False;
  12499. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12500. Exit;
  12501. { Convert:
  12502. movswl %ax,%eax -> cwtl
  12503. movslq %eax,%rax -> cdqe
  12504. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12505. refer to the same opcode and depends only on the assembler's
  12506. current operand-size attribute. [Kit]
  12507. }
  12508. with taicpu(p) do
  12509. case opsize of
  12510. S_WL:
  12511. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12512. begin
  12513. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12514. opcode := A_CWDE;
  12515. clearop(0);
  12516. clearop(1);
  12517. ops := 0;
  12518. Result := True;
  12519. end;
  12520. {$ifdef x86_64}
  12521. S_LQ:
  12522. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12523. begin
  12524. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12525. opcode := A_CDQE;
  12526. clearop(0);
  12527. clearop(1);
  12528. ops := 0;
  12529. Result := True;
  12530. end;
  12531. {$endif x86_64}
  12532. else
  12533. ;
  12534. end;
  12535. end;
  12536. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12537. var
  12538. hp1, hp2: tai;
  12539. IdentityMask, Shift: TCGInt;
  12540. LimitSize: Topsize;
  12541. DoNotMerge: Boolean;
  12542. begin
  12543. Result := False;
  12544. { All these optimisations work on "shr const,%reg" }
  12545. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12546. Exit;
  12547. DoNotMerge := False;
  12548. Shift := taicpu(p).oper[0]^.val;
  12549. LimitSize := taicpu(p).opsize;
  12550. hp1 := p;
  12551. repeat
  12552. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12553. Break;
  12554. { Detect:
  12555. shr x, %reg
  12556. and y, %reg
  12557. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12558. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12559. }
  12560. case taicpu(hp1).opcode of
  12561. A_AND:
  12562. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12563. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12564. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12565. begin
  12566. { Make sure the FLAGS register isn't in use }
  12567. TransferUsedRegs(TmpUsedRegs);
  12568. hp2 := p;
  12569. repeat
  12570. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12571. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12572. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12573. begin
  12574. { Generate the identity mask }
  12575. case taicpu(p).opsize of
  12576. S_B:
  12577. IdentityMask := $FF shr Shift;
  12578. S_W:
  12579. IdentityMask := $FFFF shr Shift;
  12580. S_L:
  12581. IdentityMask := $FFFFFFFF shr Shift;
  12582. {$ifdef x86_64}
  12583. S_Q:
  12584. { We need to force the operands to be unsigned 64-bit
  12585. integers otherwise the wrong value is generated }
  12586. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12587. {$endif x86_64}
  12588. else
  12589. InternalError(2022081501);
  12590. end;
  12591. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12592. begin
  12593. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12594. { All the possible 1 bits are covered, so we can remove the AND }
  12595. hp2 := tai(hp1.Previous);
  12596. RemoveInstruction(hp1);
  12597. { p wasn't actually changed, so don't set Result to True,
  12598. but a change was nonetheless made elsewhere }
  12599. Include(OptsToCheck, aoc_ForceNewIteration);
  12600. { Do another pass in case other AND or MOVZX instructions
  12601. follow }
  12602. hp1 := hp2;
  12603. Continue;
  12604. end;
  12605. end;
  12606. end;
  12607. A_TEST, A_CMP, A_Jcc:
  12608. { Skip over conditional jumps and relevant comparisons }
  12609. Continue;
  12610. A_MOVZX:
  12611. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12612. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12613. begin
  12614. { Since the original register is being read as is, subsequent
  12615. SHRs must not be merged at this point }
  12616. DoNotMerge := True;
  12617. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12618. begin
  12619. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12620. begin
  12621. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12622. { All the possible 1 bits are covered, so we can remove the AND }
  12623. hp2 := tai(hp1.Previous);
  12624. RemoveInstruction(hp1);
  12625. hp1 := hp2;
  12626. end
  12627. else { Different register target }
  12628. begin
  12629. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12630. taicpu(hp1).opcode := A_MOV;
  12631. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12632. case taicpu(hp1).opsize of
  12633. S_BW:
  12634. taicpu(hp1).opsize := S_W;
  12635. S_BL, S_WL:
  12636. taicpu(hp1).opsize := S_L;
  12637. else
  12638. InternalError(2022081503);
  12639. end;
  12640. end;
  12641. end
  12642. else if (Shift > 0) and
  12643. (taicpu(p).opsize = S_W) and
  12644. (taicpu(hp1).opsize = S_WL) and
  12645. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12646. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12647. begin
  12648. { Detect:
  12649. shr x, %ax (x > 0)
  12650. ...
  12651. movzwl %ax,%eax
  12652. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12653. }
  12654. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12655. taicpu(hp1).opcode := A_CWDE;
  12656. taicpu(hp1).clearop(0);
  12657. taicpu(hp1).clearop(1);
  12658. taicpu(hp1).ops := 0;
  12659. end;
  12660. { Move onto the next instruction }
  12661. Continue;
  12662. end;
  12663. A_SHL, A_SAL, A_SHR:
  12664. if (taicpu(hp1).opsize <= LimitSize) and
  12665. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12666. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12667. begin
  12668. { Make sure the sizes don't exceed the register size limit
  12669. (measured by the shift value falling below the limit) }
  12670. if taicpu(hp1).opsize < LimitSize then
  12671. LimitSize := taicpu(hp1).opsize;
  12672. if taicpu(hp1).opcode = A_SHR then
  12673. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12674. else
  12675. begin
  12676. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12677. DoNotMerge := True;
  12678. end;
  12679. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12680. Break;
  12681. { Since we've established that the combined shift is within
  12682. limits, we can actually combine the adjacent SHR
  12683. instructions even if they're different sizes }
  12684. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12685. begin
  12686. hp2 := tai(hp1.Previous);
  12687. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12688. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12689. RemoveInstruction(hp1);
  12690. hp1 := hp2;
  12691. end;
  12692. { Move onto the next instruction }
  12693. Continue;
  12694. end;
  12695. else
  12696. ;
  12697. end;
  12698. Break;
  12699. until False;
  12700. { Detect the following (looking backwards):
  12701. shr %cl,%reg
  12702. shr x, %reg
  12703. Swap the two SHR instructions to minimise a pipeline stall.
  12704. }
  12705. if GetLastInstruction(p, hp1) and
  12706. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12707. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12708. { First operand will be %cl }
  12709. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12710. { Just to be sure }
  12711. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12712. begin
  12713. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12714. { Moving the entries this way ensures the register tracking remains correct }
  12715. Asml.Remove(p);
  12716. Asml.InsertBefore(p, hp1);
  12717. p := hp1;
  12718. { Don't set Result to True because the current instruction is now
  12719. "shr %cl,%reg" and there's nothing more we can do with it }
  12720. end;
  12721. end;
  12722. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12723. var
  12724. hp1, hp2: tai;
  12725. Opposite, SecondOpposite: TAsmOp;
  12726. NewCond: TAsmCond;
  12727. begin
  12728. Result := False;
  12729. { Change:
  12730. add/sub 128,(dest)
  12731. To:
  12732. sub/add -128,(dest)
  12733. This generaally takes fewer bytes to encode because -128 can be stored
  12734. in a signed byte, whereas +128 cannot.
  12735. }
  12736. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12737. begin
  12738. if taicpu(p).opcode = A_ADD then
  12739. Opposite := A_SUB
  12740. else
  12741. Opposite := A_ADD;
  12742. { Be careful if the flags are in use, because the CF flag inverts
  12743. when changing from ADD to SUB and vice versa }
  12744. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12745. GetNextInstruction(p, hp1) then
  12746. begin
  12747. TransferUsedRegs(TmpUsedRegs);
  12748. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12749. hp2 := hp1;
  12750. { Scan ahead to check if everything's safe }
  12751. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12752. begin
  12753. if (hp1.typ <> ait_instruction) then
  12754. { Probably unsafe since the flags are still in use }
  12755. Exit;
  12756. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12757. { Stop searching at an unconditional jump }
  12758. Break;
  12759. if not
  12760. (
  12761. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12762. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12763. ) and
  12764. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12765. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12766. Exit;
  12767. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12768. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12769. { Move to the next instruction }
  12770. GetNextInstruction(hp1, hp1);
  12771. end;
  12772. while Assigned(hp2) and (hp2 <> hp1) do
  12773. begin
  12774. NewCond := C_None;
  12775. case taicpu(hp2).condition of
  12776. C_A, C_NBE:
  12777. NewCond := C_BE;
  12778. C_B, C_C, C_NAE:
  12779. NewCond := C_AE;
  12780. C_AE, C_NB, C_NC:
  12781. NewCond := C_B;
  12782. C_BE, C_NA:
  12783. NewCond := C_A;
  12784. else
  12785. { No change needed };
  12786. end;
  12787. if NewCond <> C_None then
  12788. begin
  12789. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12790. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12791. taicpu(hp2).condition := NewCond;
  12792. end
  12793. else
  12794. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12795. begin
  12796. { Because of the flipping of the carry bit, to ensure
  12797. the operation remains equivalent, ADC becomes SBB
  12798. and vice versa, and the constant is not-inverted.
  12799. If multiple ADCs or SBBs appear in a row, each one
  12800. changed causes the carry bit to invert, so they all
  12801. need to be flipped }
  12802. if taicpu(hp2).opcode = A_ADC then
  12803. SecondOpposite := A_SBB
  12804. else
  12805. SecondOpposite := A_ADC;
  12806. if taicpu(hp2).oper[0]^.typ <> top_const then
  12807. { Should have broken out of this optimisation already }
  12808. InternalError(2021112901);
  12809. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  12810. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  12811. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12812. taicpu(hp2).opcode := SecondOpposite;
  12813. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12814. end;
  12815. { Move to the next instruction }
  12816. GetNextInstruction(hp2, hp2);
  12817. end;
  12818. if (hp2 <> hp1) then
  12819. InternalError(2021111501);
  12820. end;
  12821. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12822. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12823. taicpu(p).opcode := Opposite;
  12824. taicpu(p).oper[0]^.val := -128;
  12825. { No further optimisations can be made on this instruction, so move
  12826. onto the next one to save time }
  12827. p := tai(p.Next);
  12828. UpdateUsedRegs(p);
  12829. Result := True;
  12830. Exit;
  12831. end;
  12832. { Detect:
  12833. add/sub %reg2,(dest)
  12834. add/sub x, (dest)
  12835. (dest can be a register or a reference)
  12836. Swap the instructions to minimise a pipeline stall. This reverses the
  12837. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12838. optimisations could be made.
  12839. }
  12840. if (taicpu(p).oper[0]^.typ = top_reg) and
  12841. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12842. (
  12843. (
  12844. (taicpu(p).oper[1]^.typ = top_reg) and
  12845. { We can try searching further ahead if we're writing to a register }
  12846. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12847. ) or
  12848. (
  12849. (taicpu(p).oper[1]^.typ = top_ref) and
  12850. GetNextInstruction(p, hp1)
  12851. )
  12852. ) and
  12853. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12854. (taicpu(hp1).oper[0]^.typ = top_const) and
  12855. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12856. begin
  12857. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12858. TransferUsedRegs(TmpUsedRegs);
  12859. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12860. hp2 := p;
  12861. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12862. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12863. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12864. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12865. begin
  12866. asml.remove(hp1);
  12867. asml.InsertBefore(hp1, p);
  12868. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12869. Result := True;
  12870. end;
  12871. end;
  12872. end;
  12873. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12874. begin
  12875. Result:=false;
  12876. { change "cmp $0, %reg" to "test %reg, %reg" }
  12877. if MatchOpType(taicpu(p),top_const,top_reg) and
  12878. (taicpu(p).oper[0]^.val = 0) then
  12879. begin
  12880. taicpu(p).opcode := A_TEST;
  12881. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12882. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  12883. Result:=true;
  12884. end;
  12885. end;
  12886. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12887. var
  12888. IsTestConstX, IsValid : Boolean;
  12889. hp1,hp2 : tai;
  12890. begin
  12891. Result:=false;
  12892. { If x is a power of 2 (popcnt = 1), change:
  12893. or $x, %reg/ref
  12894. To:
  12895. bts lb(x), %reg/ref
  12896. }
  12897. if (taicpu(p).opcode = A_OR) and
  12898. IsBTXAcceptable(p) and
  12899. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  12900. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12901. (
  12902. { Don't optimise if a test instruction follows }
  12903. not GetNextInstruction(p, hp1) or
  12904. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  12905. ) then
  12906. begin
  12907. DebugMsg(SPeepholeOptimization + 'Changed OR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTS ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  12908. taicpu(p).opcode := A_BTS;
  12909. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12910. Result := True;
  12911. Exit;
  12912. end;
  12913. { If x is a power of 2 (popcnt = 1), change:
  12914. test $x, %reg/ref
  12915. je / sete / cmove (or jne / setne)
  12916. To:
  12917. bt lb(x), %reg/ref
  12918. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  12919. }
  12920. if (taicpu(p).opcode = A_TEST) and
  12921. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  12922. (taicpu(p).oper[0]^.typ = top_const) and
  12923. (
  12924. (cs_opt_size in current_settings.optimizerswitches) or
  12925. (
  12926. (taicpu(p).oper[1]^.typ = top_reg) and
  12927. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  12928. ) or
  12929. (
  12930. (taicpu(p).oper[1]^.typ <> top_reg) and
  12931. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  12932. )
  12933. ) and
  12934. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12935. { For sizes less than S_L, the byte size is equal or larger with BT,
  12936. so don't bother optimising }
  12937. (taicpu(p).opsize >= S_L) then
  12938. begin
  12939. IsValid := True;
  12940. { Check the next set of instructions, watching the FLAGS register
  12941. and the conditions used }
  12942. TransferUsedRegs(TmpUsedRegs);
  12943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12944. hp1 := p;
  12945. hp2 := nil;
  12946. while GetNextInstruction(hp1, hp1) do
  12947. begin
  12948. if not Assigned(hp2) then
  12949. { The first instruction after TEST }
  12950. hp2 := hp1;
  12951. if (hp1.typ <> ait_instruction) then
  12952. begin
  12953. { If the flags are no longer in use, everything is fine }
  12954. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12955. IsValid := False;
  12956. Break;
  12957. end;
  12958. case taicpu(hp1).condition of
  12959. C_None:
  12960. begin
  12961. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12962. { Something is not quite normal, so play safe and don't change }
  12963. IsValid := False;
  12964. Break;
  12965. end;
  12966. C_E, C_Z, C_NE, C_NZ:
  12967. { This is fine };
  12968. else
  12969. begin
  12970. { Unsupported condition }
  12971. IsValid := False;
  12972. Break;
  12973. end;
  12974. end;
  12975. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12976. end;
  12977. if IsValid then
  12978. begin
  12979. while hp2 <> hp1 do
  12980. begin
  12981. case taicpu(hp2).condition of
  12982. C_Z, C_E:
  12983. taicpu(hp2).condition := C_NC;
  12984. C_NZ, C_NE:
  12985. taicpu(hp2).condition := C_C;
  12986. else
  12987. { Should not get this by this point }
  12988. InternalError(2022110701);
  12989. end;
  12990. GetNextInstruction(hp2, hp2);
  12991. end;
  12992. DebugMsg(SPeepholeOptimization + 'Changed TEST $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BT ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  12993. taicpu(p).opcode := A_BT;
  12994. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12995. Result := True;
  12996. Exit;
  12997. end;
  12998. end;
  12999. { removes the line marked with (x) from the sequence
  13000. and/or/xor/add/sub/... $x, %y
  13001. test/or %y, %y | test $-1, %y (x)
  13002. j(n)z _Label
  13003. as the first instruction already adjusts the ZF
  13004. %y operand may also be a reference }
  13005. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13006. MatchOperand(taicpu(p).oper[0]^,-1);
  13007. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13008. GetLastInstruction(p, hp1) and
  13009. (tai(hp1).typ = ait_instruction) and
  13010. GetNextInstruction(p,hp2) and
  13011. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13012. case taicpu(hp1).opcode Of
  13013. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13014. { These two instructions set the zero flag if the result is zero }
  13015. A_POPCNT, A_LZCNT:
  13016. begin
  13017. if (
  13018. { With POPCNT, an input of zero will set the zero flag
  13019. because the population count of zero is zero }
  13020. (taicpu(hp1).opcode = A_POPCNT) and
  13021. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13022. (
  13023. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13024. { Faster than going through the second half of the 'or'
  13025. condition below }
  13026. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13027. )
  13028. ) or (
  13029. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13030. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13031. { and in case of carry for A(E)/B(E)/C/NC }
  13032. (
  13033. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13034. (
  13035. (taicpu(hp1).opcode <> A_ADD) and
  13036. (taicpu(hp1).opcode <> A_SUB) and
  13037. (taicpu(hp1).opcode <> A_LZCNT)
  13038. )
  13039. )
  13040. ) then
  13041. begin
  13042. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13043. RemoveCurrentP(p, hp2);
  13044. Result:=true;
  13045. Exit;
  13046. end;
  13047. end;
  13048. A_SHL, A_SAL, A_SHR, A_SAR:
  13049. begin
  13050. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13051. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13052. { therefore, it's only safe to do this optimization for }
  13053. { shifts by a (nonzero) constant }
  13054. (taicpu(hp1).oper[0]^.typ = top_const) and
  13055. (taicpu(hp1).oper[0]^.val <> 0) and
  13056. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13057. { and in case of carry for A(E)/B(E)/C/NC }
  13058. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13059. begin
  13060. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13061. RemoveCurrentP(p, hp2);
  13062. Result:=true;
  13063. Exit;
  13064. end;
  13065. end;
  13066. A_DEC, A_INC, A_NEG:
  13067. begin
  13068. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13069. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13070. { and in case of carry for A(E)/B(E)/C/NC }
  13071. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13072. begin
  13073. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13074. RemoveCurrentP(p, hp2);
  13075. Result:=true;
  13076. Exit;
  13077. end;
  13078. end;
  13079. A_ANDN, A_BZHI:
  13080. begin
  13081. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13082. { Only the zero and sign flags are consistent with what the result is }
  13083. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13084. begin
  13085. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13086. RemoveCurrentP(p, hp2);
  13087. Result:=true;
  13088. Exit;
  13089. end;
  13090. end;
  13091. A_BEXTR:
  13092. begin
  13093. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13094. { Only the zero flag is set }
  13095. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13096. begin
  13097. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13098. RemoveCurrentP(p, hp2);
  13099. Result:=true;
  13100. Exit;
  13101. end;
  13102. end;
  13103. else
  13104. ;
  13105. end; { case }
  13106. { change "test $-1,%reg" into "test %reg,%reg" }
  13107. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13108. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13109. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13110. if MatchInstruction(p, A_OR, []) and
  13111. { Can only match if they're both registers }
  13112. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13113. begin
  13114. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13115. taicpu(p).opcode := A_TEST;
  13116. { No need to set Result to True, as we've done all the optimisations we can }
  13117. end;
  13118. end;
  13119. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13120. var
  13121. hp1,hp3 : tai;
  13122. {$ifndef x86_64}
  13123. hp2 : taicpu;
  13124. {$endif x86_64}
  13125. begin
  13126. Result:=false;
  13127. hp3:=nil;
  13128. {$ifndef x86_64}
  13129. { don't do this on modern CPUs, this really hurts them due to
  13130. broken call/ret pairing }
  13131. if (current_settings.optimizecputype < cpu_Pentium2) and
  13132. not(cs_create_pic in current_settings.moduleswitches) and
  13133. GetNextInstruction(p, hp1) and
  13134. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13135. MatchOpType(taicpu(hp1),top_ref) and
  13136. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13137. begin
  13138. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13139. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13140. InsertLLItem(p.previous, p, hp2);
  13141. taicpu(p).opcode := A_JMP;
  13142. taicpu(p).is_jmp := true;
  13143. RemoveInstruction(hp1);
  13144. Result:=true;
  13145. end
  13146. else
  13147. {$endif x86_64}
  13148. { replace
  13149. call procname
  13150. ret
  13151. by
  13152. jmp procname
  13153. but do it only on level 4 because it destroys stack back traces
  13154. else if the subroutine is marked as no return, remove the ret
  13155. }
  13156. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13157. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13158. GetNextInstruction(p, hp1) and
  13159. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13160. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13161. SetAndTest(hp1,hp3) and
  13162. GetNextInstruction(hp1,hp1) and
  13163. MatchInstruction(hp1,A_RET,[S_NO])
  13164. )
  13165. ) and
  13166. (taicpu(hp1).ops=0) then
  13167. begin
  13168. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13169. { we might destroy stack alignment here if we do not do a call }
  13170. (target_info.stackalign<=sizeof(SizeUInt)) then
  13171. begin
  13172. taicpu(p).opcode := A_JMP;
  13173. taicpu(p).is_jmp := true;
  13174. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13175. end
  13176. else
  13177. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13178. RemoveInstruction(hp1);
  13179. if Assigned(hp3) then
  13180. begin
  13181. AsmL.Remove(hp3);
  13182. AsmL.InsertBefore(hp3,p)
  13183. end;
  13184. Result:=true;
  13185. end;
  13186. end;
  13187. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13188. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13189. begin
  13190. case OpSize of
  13191. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13192. Result := (Val <= $FF) and (Val >= -128);
  13193. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13194. Result := (Val <= $FFFF) and (Val >= -32768);
  13195. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13196. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13197. else
  13198. Result := True;
  13199. end;
  13200. end;
  13201. var
  13202. hp1, hp2 : tai;
  13203. SizeChange: Boolean;
  13204. PreMessage: string;
  13205. begin
  13206. Result := False;
  13207. if (taicpu(p).oper[0]^.typ = top_reg) and
  13208. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13209. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  13210. begin
  13211. { Change (using movzbl %al,%eax as an example):
  13212. movzbl %al, %eax movzbl %al, %eax
  13213. cmpl x, %eax testl %eax,%eax
  13214. To:
  13215. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  13216. movzbl %al, %eax movzbl %al, %eax
  13217. Smaller instruction and minimises pipeline stall as the CPU
  13218. doesn't have to wait for the register to get zero-extended. [Kit]
  13219. Also allow if the smaller of the two registers is being checked,
  13220. as this still removes the false dependency.
  13221. }
  13222. if
  13223. (
  13224. (
  13225. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  13226. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  13227. ) or (
  13228. { If MatchOperand returns True, they must both be registers }
  13229. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  13230. )
  13231. ) and
  13232. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  13233. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  13234. begin
  13235. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  13236. asml.Remove(hp1);
  13237. asml.InsertBefore(hp1, p);
  13238. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  13239. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  13240. begin
  13241. taicpu(hp1).opcode := A_TEST;
  13242. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  13243. end;
  13244. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13245. case taicpu(p).opsize of
  13246. S_BW, S_BL:
  13247. begin
  13248. SizeChange := taicpu(hp1).opsize <> S_B;
  13249. taicpu(hp1).changeopsize(S_B);
  13250. end;
  13251. S_WL:
  13252. begin
  13253. SizeChange := taicpu(hp1).opsize <> S_W;
  13254. taicpu(hp1).changeopsize(S_W);
  13255. end
  13256. else
  13257. InternalError(2020112701);
  13258. end;
  13259. UpdateUsedRegs(tai(p.Next));
  13260. { Check if the register is used aferwards - if not, we can
  13261. remove the movzx instruction completely }
  13262. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  13263. begin
  13264. { Hp1 is a better position than p for debugging purposes }
  13265. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13266. RemoveCurrentp(p, hp1);
  13267. Result := True;
  13268. end;
  13269. if SizeChange then
  13270. DebugMsg(SPeepholeOptimization + PreMessage +
  13271. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  13272. else
  13273. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13274. Exit;
  13275. end;
  13276. { Change (using movzwl %ax,%eax as an example):
  13277. movzwl %ax, %eax
  13278. movb %al, (dest) (Register is smaller than read register in movz)
  13279. To:
  13280. movb %al, (dest) (Move one back to avoid a false dependency)
  13281. movzwl %ax, %eax
  13282. }
  13283. if (taicpu(hp1).opcode = A_MOV) and
  13284. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13285. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13286. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13287. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13288. begin
  13289. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13290. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13291. asml.Remove(hp1);
  13292. asml.InsertBefore(hp1, p);
  13293. if taicpu(hp1).oper[1]^.typ = top_reg then
  13294. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13295. { Check if the register is used aferwards - if not, we can
  13296. remove the movzx instruction completely }
  13297. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13298. begin
  13299. { Hp1 is a better position than p for debugging purposes }
  13300. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13301. RemoveCurrentp(p, hp1);
  13302. Result := True;
  13303. end;
  13304. Exit;
  13305. end;
  13306. end;
  13307. end;
  13308. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13309. var
  13310. hp1: tai;
  13311. {$ifdef x86_64}
  13312. PreMessage, RegName: string;
  13313. {$endif x86_64}
  13314. begin
  13315. Result := False;
  13316. { If x is a power of 2 (popcnt = 1), change:
  13317. xor $x, %reg/ref
  13318. To:
  13319. btc lb(x), %reg/ref
  13320. }
  13321. if IsBTXAcceptable(p) and
  13322. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13323. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13324. (
  13325. { Don't optimise if a test instruction follows }
  13326. not GetNextInstruction(p, hp1) or
  13327. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13328. ) then
  13329. begin
  13330. DebugMsg(SPeepholeOptimization + 'Changed XOR $0x' + hexstr(taicpu(p).oper[0]^.val, 2) + ' to BTC ' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  13331. taicpu(p).opcode := A_BTC;
  13332. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13333. Result := True;
  13334. Exit;
  13335. end;
  13336. {$ifdef x86_64}
  13337. { Code size reduction by J. Gareth "Kit" Moreton }
  13338. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13339. as this removes the REX prefix }
  13340. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13341. Exit;
  13342. if taicpu(p).oper[0]^.typ <> top_reg then
  13343. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13344. InternalError(2018011500);
  13345. case taicpu(p).opsize of
  13346. S_Q:
  13347. begin
  13348. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13349. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13350. { The actual optimization }
  13351. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13352. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13353. taicpu(p).changeopsize(S_L);
  13354. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13355. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13356. end;
  13357. else
  13358. ;
  13359. end;
  13360. {$endif x86_64}
  13361. end;
  13362. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13363. var
  13364. XReg: TRegister;
  13365. begin
  13366. Result := False;
  13367. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  13368. Smaller encoding and slightly faster on some platforms (also works for
  13369. ZMM-sized registers) }
  13370. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  13371. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  13372. begin
  13373. XReg := taicpu(p).oper[0]^.reg;
  13374. if (taicpu(p).oper[1]^.reg = XReg) then
  13375. begin
  13376. taicpu(p).changeopsize(S_XMM);
  13377. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  13378. if (cs_opt_size in current_settings.optimizerswitches) then
  13379. begin
  13380. { Change input registers to %xmm0 to reduce size. Note that
  13381. there's a risk of a false dependency doing this, so only
  13382. optimise for size here }
  13383. XReg := NR_XMM0;
  13384. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  13385. end
  13386. else
  13387. begin
  13388. setsubreg(XReg, R_SUBMMX);
  13389. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  13390. end;
  13391. taicpu(p).oper[0]^.reg := XReg;
  13392. taicpu(p).oper[1]^.reg := XReg;
  13393. Result := True;
  13394. end;
  13395. end;
  13396. end;
  13397. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  13398. var
  13399. OperIdx: Integer;
  13400. begin
  13401. for OperIdx := 0 to p.ops - 1 do
  13402. if p.oper[OperIdx]^.typ = top_ref then
  13403. optimize_ref(p.oper[OperIdx]^.ref^, False);
  13404. end;
  13405. end.