aoptx86.pas 626 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655
  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. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  156. function PostPeepholeOptXor(var p : tai) : Boolean;
  157. {$endif x86_64}
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  171. { Processor-dependent reference optimisation }
  172. class procedure OptimizeRefs(var p: taicpu); static;
  173. end;
  174. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  175. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  178. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  179. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  180. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  181. {$if max_operands>2}
  182. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  183. {$endif max_operands>2}
  184. function RefsEqual(const r1, r2: treference): boolean;
  185. { Note that Result is set to True if the references COULD overlap but the
  186. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  187. might still overlap because %reg2 could be equal to %reg1-4 }
  188. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  189. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  190. { returns true, if ref is a reference using only the registers passed as base and index
  191. and having an offset }
  192. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  193. implementation
  194. uses
  195. cutils,verbose,
  196. systems,
  197. globals,
  198. cpuinfo,
  199. procinfo,
  200. paramgr,
  201. aasmbase,
  202. aoptbase,aoptutils,
  203. symconst,symsym,
  204. cgx86,
  205. itcpugas;
  206. {$ifdef DEBUG_AOPTCPU}
  207. const
  208. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  209. {$else DEBUG_AOPTCPU}
  210. { Empty strings help the optimizer to remove string concatenations that won't
  211. ever appear to the user on release builds. [Kit] }
  212. const
  213. SPeepholeOptimization = '';
  214. {$endif DEBUG_AOPTCPU}
  215. LIST_STEP_SIZE = 4;
  216. type
  217. TJumpTrackingItem = class(TLinkedListItem)
  218. private
  219. FSymbol: TAsmSymbol;
  220. FRefs: LongInt;
  221. public
  222. constructor Create(ASymbol: TAsmSymbol);
  223. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  224. property Symbol: TAsmSymbol read FSymbol;
  225. property Refs: LongInt read FRefs;
  226. end;
  227. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  228. begin
  229. inherited Create;
  230. FSymbol := ASymbol;
  231. FRefs := 0;
  232. end;
  233. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  234. begin
  235. Inc(FRefs);
  236. end;
  237. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  238. begin
  239. result :=
  240. (instr.typ = ait_instruction) and
  241. (taicpu(instr).opcode = op) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2)
  250. ) and
  251. ((opsize = []) or (taicpu(instr).opsize in opsize));
  252. end;
  253. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  254. begin
  255. result :=
  256. (instr.typ = ait_instruction) and
  257. ((taicpu(instr).opcode = op1) or
  258. (taicpu(instr).opcode = op2) or
  259. (taicpu(instr).opcode = op3)
  260. ) and
  261. ((opsize = []) or (taicpu(instr).opsize in opsize));
  262. end;
  263. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  264. const opsize : topsizes) : boolean;
  265. var
  266. op : TAsmOp;
  267. begin
  268. result:=false;
  269. if (instr.typ <> ait_instruction) or
  270. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  271. exit;
  272. for op in ops do
  273. begin
  274. if taicpu(instr).opcode = op then
  275. begin
  276. result:=true;
  277. exit;
  278. end;
  279. end;
  280. end;
  281. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  282. begin
  283. result := (oper.typ = top_reg) and (oper.reg = reg);
  284. end;
  285. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  286. begin
  287. result := (oper.typ = top_const) and (oper.val = a);
  288. end;
  289. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  290. begin
  291. result := oper1.typ = oper2.typ;
  292. if result then
  293. case oper1.typ of
  294. top_const:
  295. Result:=oper1.val = oper2.val;
  296. top_reg:
  297. Result:=oper1.reg = oper2.reg;
  298. top_ref:
  299. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  300. else
  301. internalerror(2013102801);
  302. end
  303. end;
  304. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  305. begin
  306. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  307. if result then
  308. case oper1.typ of
  309. top_const:
  310. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  311. top_reg:
  312. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  313. top_ref:
  314. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  315. else
  316. internalerror(2020052401);
  317. end
  318. end;
  319. function RefsEqual(const r1, r2: treference): boolean;
  320. begin
  321. RefsEqual :=
  322. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  323. (r1.relsymbol = r2.relsymbol) and
  324. (r1.segment = r2.segment) and (r1.base = r2.base) and
  325. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  326. (r1.offset = r2.offset) and
  327. (r1.volatility + r2.volatility = []);
  328. end;
  329. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  330. begin
  331. if (r1.symbol<>r2.symbol) then
  332. { If the index registers are different, there's a chance one could
  333. be set so it equals the other symbol }
  334. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  335. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  336. (r1.relsymbol = r2.relsymbol) and
  337. (r1.segment = r2.segment) and (r1.base = r2.base) and
  338. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  339. (r1.volatility + r2.volatility = []) then
  340. { In this case, it all depends on the offsets }
  341. Exit(abs(r1.offset - r2.offset) < Range);
  342. { There's a chance things MIGHT overlap, so take no chances }
  343. Result := True;
  344. end;
  345. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  346. begin
  347. Result:=(ref.offset=0) and
  348. (ref.scalefactor in [0,1]) and
  349. (ref.segment=NR_NO) and
  350. (ref.symbol=nil) and
  351. (ref.relsymbol=nil) and
  352. ((base=NR_INVALID) or
  353. (ref.base=base)) and
  354. ((index=NR_INVALID) or
  355. (ref.index=index)) and
  356. (ref.volatility=[]);
  357. end;
  358. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  359. begin
  360. Result:=(ref.scalefactor in [0,1]) and
  361. (ref.segment=NR_NO) and
  362. (ref.symbol=nil) and
  363. (ref.relsymbol=nil) and
  364. ((base=NR_INVALID) or
  365. (ref.base=base)) and
  366. ((index=NR_INVALID) or
  367. (ref.index=index)) and
  368. (ref.volatility=[]);
  369. end;
  370. function InstrReadsFlags(p: tai): boolean;
  371. begin
  372. InstrReadsFlags := true;
  373. case p.typ of
  374. ait_instruction:
  375. if InsProp[taicpu(p).opcode].Ch*
  376. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  377. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  378. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  379. exit;
  380. ait_label:
  381. exit;
  382. else
  383. ;
  384. end;
  385. InstrReadsFlags := false;
  386. end;
  387. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  388. begin
  389. Next:=Current;
  390. repeat
  391. Result:=GetNextInstruction(Next,Next);
  392. until not (Result) or
  393. not(cs_opt_level3 in current_settings.optimizerswitches) or
  394. (Next.typ<>ait_instruction) or
  395. RegInInstruction(reg,Next) or
  396. is_calljmp(taicpu(Next).opcode);
  397. end;
  398. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  399. var
  400. GetNextResult: Boolean;
  401. begin
  402. Result:=0;
  403. Next:=Current;
  404. repeat
  405. GetNextResult := GetNextInstruction(Next,Next);
  406. if GetNextResult then
  407. Inc(Result)
  408. else
  409. { Must return zero upon hitting the end of the linked list without a match }
  410. Result := 0;
  411. until not (GetNextResult) or
  412. not(cs_opt_level3 in current_settings.optimizerswitches) or
  413. (Next.typ<>ait_instruction) or
  414. RegInInstruction(reg,Next) or
  415. is_calljmp(taicpu(Next).opcode);
  416. end;
  417. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  418. procedure TrackJump(Symbol: TAsmSymbol);
  419. var
  420. Search: TJumpTrackingItem;
  421. begin
  422. { See if an entry already exists in our jump tracking list
  423. (faster to search backwards due to the higher chance of
  424. matching destinations) }
  425. Search := TJumpTrackingItem(JumpTracking.Last);
  426. while Assigned(Search) do
  427. begin
  428. if Search.Symbol = Symbol then
  429. begin
  430. { Found it - remove it so it can be pushed to the front }
  431. JumpTracking.Remove(Search);
  432. Break;
  433. end;
  434. Search := TJumpTrackingItem(Search.Previous);
  435. end;
  436. if not Assigned(Search) then
  437. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  438. JumpTracking.Concat(Search);
  439. Search.IncRefs;
  440. end;
  441. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  442. var
  443. Search: TJumpTrackingItem;
  444. begin
  445. Result := False;
  446. { See if this label appears in the tracking list }
  447. Search := TJumpTrackingItem(JumpTracking.Last);
  448. while Assigned(Search) do
  449. begin
  450. if Search.Symbol = Symbol then
  451. begin
  452. { Found it - let's see what we can discover }
  453. if Search.Symbol.getrefs = Search.Refs then
  454. begin
  455. { Success - all the references are accounted for }
  456. JumpTracking.Remove(Search);
  457. Search.Free;
  458. { It is logically impossible for CrossJump to be false here
  459. because we must have run into a conditional jump for
  460. this label at some point }
  461. if not CrossJump then
  462. InternalError(2022041710);
  463. if JumpTracking.First = nil then
  464. { Tracking list is now empty - no more cross jumps }
  465. CrossJump := False;
  466. Result := True;
  467. Exit;
  468. end;
  469. { If the references don't match, it's possible to enter
  470. this label through other means, so drop out }
  471. Exit;
  472. end;
  473. Search := TJumpTrackingItem(Search.Previous);
  474. end;
  475. end;
  476. var
  477. Next_Label: tai;
  478. begin
  479. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  480. Next := Current;
  481. repeat
  482. Result := GetNextInstruction(Next,Next);
  483. if not Result then
  484. Break;
  485. if Next.typ = ait_align then
  486. Result := SkipAligns(Next, Next);
  487. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  488. if is_calljmpuncondret(taicpu(Next).opcode) then
  489. begin
  490. if (taicpu(Next).opcode = A_JMP) and
  491. { Remove dead code now to save time }
  492. RemoveDeadCodeAfterJump(taicpu(Next)) then
  493. { A jump was removed, but not the current instruction, and
  494. Result doesn't necessarily translate into an optimisation
  495. routine's Result, so use the "Force New Iteration" flag so
  496. mark a new pass }
  497. Include(OptsToCheck, aoc_ForceNewIteration);
  498. if not Assigned(JumpTracking) then
  499. begin
  500. { Cross-label optimisations often causes other optimisations
  501. to perform worse because they're not given the chance to
  502. optimise locally. In this case, don't do the cross-label
  503. optimisations yet, but flag them as a potential possibility
  504. for the next iteration of Pass 1 }
  505. if not NotFirstIteration then
  506. Include(OptsToCheck, aoc_ForceNewIteration);
  507. end
  508. else if IsJumpToLabel(taicpu(Next)) and
  509. GetNextInstruction(Next, Next_Label) and
  510. SkipAligns(Next_Label, Next_Label) then
  511. begin
  512. { If we have JMP .lbl, and the label after it has all of its
  513. references tracked, then this is probably an if-else style of
  514. block and we can keep tracking. If the label for this jump
  515. then appears later and is fully tracked, then it's the end
  516. of the if-else blocks and the code paths converge (thus
  517. marking the end of the cross-jump) }
  518. if (Next_Label.typ = ait_label) then
  519. begin
  520. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  521. begin
  522. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  523. Next := Next_Label;
  524. { CrossJump gets set to false by LabelAccountedFor if the
  525. list is completely emptied (as it indicates that all
  526. code paths have converged). We could avoid this nuance
  527. by moving the TrackJump call to before the
  528. LabelAccountedFor call, but this is slower in situations
  529. where LabelAccountedFor would return False due to the
  530. creation of a new object that is not used and destroyed
  531. soon after. }
  532. CrossJump := True;
  533. Continue;
  534. end;
  535. end
  536. else if (Next_Label.typ <> ait_marker) then
  537. { We just did a RemoveDeadCodeAfterJump, so either we find
  538. a label, the end of the procedure or some kind of marker}
  539. InternalError(2022041720);
  540. end;
  541. Result := False;
  542. Exit;
  543. end
  544. else
  545. begin
  546. if not Assigned(JumpTracking) then
  547. begin
  548. { Cross-label optimisations often causes other optimisations
  549. to perform worse because they're not given the chance to
  550. optimise locally. In this case, don't do the cross-label
  551. optimisations yet, but flag them as a potential possibility
  552. for the next iteration of Pass 1 }
  553. if not NotFirstIteration then
  554. Include(OptsToCheck, aoc_ForceNewIteration);
  555. end
  556. else if IsJumpToLabel(taicpu(Next)) then
  557. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  558. else
  559. { Conditional jumps should always be a jump to label }
  560. InternalError(2022041701);
  561. CrossJump := True;
  562. Continue;
  563. end;
  564. if Next.typ = ait_label then
  565. begin
  566. if not Assigned(JumpTracking) then
  567. begin
  568. { Cross-label optimisations often causes other optimisations
  569. to perform worse because they're not given the chance to
  570. optimise locally. In this case, don't do the cross-label
  571. optimisations yet, but flag them as a potential possibility
  572. for the next iteration of Pass 1 }
  573. if not NotFirstIteration then
  574. Include(OptsToCheck, aoc_ForceNewIteration);
  575. end
  576. else if LabelAccountedFor(tai_label(Next).labsym) then
  577. Continue;
  578. { If we reach here, we're at a label that hasn't been seen before
  579. (or JumpTracking was nil) }
  580. Break;
  581. end;
  582. until not Result or
  583. not (cs_opt_level3 in current_settings.optimizerswitches) or
  584. not (Next.typ in [ait_label, ait_instruction]) or
  585. RegInInstruction(reg,Next);
  586. end;
  587. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  588. begin
  589. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  590. begin
  591. Result:=GetNextInstruction(Current,Next);
  592. exit;
  593. end;
  594. Next:=tai(Current.Next);
  595. Result:=false;
  596. while assigned(Next) do
  597. begin
  598. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  599. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  600. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  601. exit
  602. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  603. begin
  604. Result:=true;
  605. exit;
  606. end;
  607. Next:=tai(Next.Next);
  608. end;
  609. end;
  610. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  611. begin
  612. Result:=RegReadByInstruction(reg,hp);
  613. end;
  614. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  615. var
  616. p: taicpu;
  617. opcount: longint;
  618. begin
  619. RegReadByInstruction := false;
  620. if hp.typ <> ait_instruction then
  621. exit;
  622. p := taicpu(hp);
  623. case p.opcode of
  624. A_CALL:
  625. regreadbyinstruction := true;
  626. A_IMUL:
  627. case p.ops of
  628. 1:
  629. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  630. (
  631. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  632. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  633. );
  634. 2,3:
  635. regReadByInstruction :=
  636. reginop(reg,p.oper[0]^) or
  637. reginop(reg,p.oper[1]^);
  638. else
  639. InternalError(2019112801);
  640. end;
  641. A_MUL:
  642. begin
  643. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  644. (
  645. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  646. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  647. );
  648. end;
  649. A_IDIV,A_DIV:
  650. begin
  651. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  652. (
  653. (getregtype(reg)=R_INTREGISTER) and
  654. (
  655. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  656. )
  657. );
  658. end;
  659. else
  660. begin
  661. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  662. begin
  663. RegReadByInstruction := false;
  664. exit;
  665. end;
  666. for opcount := 0 to p.ops-1 do
  667. if (p.oper[opCount]^.typ = top_ref) and
  668. RegInRef(reg,p.oper[opcount]^.ref^) then
  669. begin
  670. RegReadByInstruction := true;
  671. exit
  672. end;
  673. { special handling for SSE MOVSD }
  674. if (p.opcode=A_MOVSD) and (p.ops>0) then
  675. begin
  676. if p.ops<>2 then
  677. internalerror(2017042702);
  678. regReadByInstruction := reginop(reg,p.oper[0]^) or
  679. (
  680. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  681. );
  682. exit;
  683. end;
  684. with insprop[p.opcode] do
  685. begin
  686. case getregtype(reg) of
  687. R_INTREGISTER:
  688. begin
  689. case getsupreg(reg) of
  690. RS_EAX:
  691. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  692. begin
  693. RegReadByInstruction := true;
  694. exit
  695. end;
  696. RS_ECX:
  697. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  698. begin
  699. RegReadByInstruction := true;
  700. exit
  701. end;
  702. RS_EDX:
  703. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  704. begin
  705. RegReadByInstruction := true;
  706. exit
  707. end;
  708. RS_EBX:
  709. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  710. begin
  711. RegReadByInstruction := true;
  712. exit
  713. end;
  714. RS_ESP:
  715. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  716. begin
  717. RegReadByInstruction := true;
  718. exit
  719. end;
  720. RS_EBP:
  721. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. RS_ESI:
  727. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  728. begin
  729. RegReadByInstruction := true;
  730. exit
  731. end;
  732. RS_EDI:
  733. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  734. begin
  735. RegReadByInstruction := true;
  736. exit
  737. end;
  738. end;
  739. end;
  740. R_MMREGISTER:
  741. begin
  742. case getsupreg(reg) of
  743. RS_XMM0:
  744. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. end;
  750. end;
  751. else
  752. ;
  753. end;
  754. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  755. begin
  756. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  757. begin
  758. case p.condition of
  759. C_A,C_NBE, { CF=0 and ZF=0 }
  760. C_BE,C_NA: { CF=1 or ZF=1 }
  761. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  762. C_AE,C_NB,C_NC, { CF=0 }
  763. C_B,C_NAE,C_C: { CF=1 }
  764. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  765. C_NE,C_NZ, { ZF=0 }
  766. C_E,C_Z: { ZF=1 }
  767. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  768. C_G,C_NLE, { ZF=0 and SF=OF }
  769. C_LE,C_NG: { ZF=1 or SF<>OF }
  770. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  771. C_GE,C_NL, { SF=OF }
  772. C_L,C_NGE: { SF<>OF }
  773. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  774. C_NO, { OF=0 }
  775. C_O: { OF=1 }
  776. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  777. C_NP,C_PO, { PF=0 }
  778. C_P,C_PE: { PF=1 }
  779. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  780. C_NS, { SF=0 }
  781. C_S: { SF=1 }
  782. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  783. else
  784. internalerror(2017042701);
  785. end;
  786. if RegReadByInstruction then
  787. exit;
  788. end;
  789. case getsubreg(reg) of
  790. R_SUBW,R_SUBD,R_SUBQ:
  791. RegReadByInstruction :=
  792. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  793. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  794. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  795. R_SUBFLAGCARRY:
  796. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  797. R_SUBFLAGPARITY:
  798. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  799. R_SUBFLAGAUXILIARY:
  800. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  801. R_SUBFLAGZERO:
  802. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGSIGN:
  804. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGOVERFLOW:
  806. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGINTERRUPT:
  808. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. R_SUBFLAGDIRECTION:
  810. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  811. else
  812. internalerror(2017042601);
  813. end;
  814. exit;
  815. end;
  816. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  817. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  818. (p.oper[0]^.reg=p.oper[1]^.reg) then
  819. exit;
  820. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  821. begin
  822. RegReadByInstruction := true;
  823. exit
  824. end;
  825. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. end;
  841. end;
  842. end;
  843. end;
  844. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  845. begin
  846. result:=false;
  847. if p1.typ<>ait_instruction then
  848. exit;
  849. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  850. exit(true);
  851. if (getregtype(reg)=R_INTREGISTER) and
  852. { change information for xmm movsd are not correct }
  853. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  854. begin
  855. case getsupreg(reg) of
  856. { RS_EAX = RS_RAX on x86-64 }
  857. RS_EAX:
  858. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  859. RS_ECX:
  860. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  861. RS_EDX:
  862. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  863. RS_EBX:
  864. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  865. RS_ESP:
  866. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  867. RS_EBP:
  868. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. RS_ESI:
  870. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. RS_EDI:
  872. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. else
  874. ;
  875. end;
  876. if result then
  877. exit;
  878. end
  879. else if getregtype(reg)=R_MMREGISTER then
  880. begin
  881. case getsupreg(reg) of
  882. RS_XMM0:
  883. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  884. else
  885. ;
  886. end;
  887. if result then
  888. exit;
  889. end
  890. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  891. begin
  892. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  893. exit(true);
  894. case getsubreg(reg) of
  895. R_SUBFLAGCARRY:
  896. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  897. R_SUBFLAGPARITY:
  898. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  899. R_SUBFLAGAUXILIARY:
  900. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  901. R_SUBFLAGZERO:
  902. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  903. R_SUBFLAGSIGN:
  904. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. R_SUBFLAGOVERFLOW:
  906. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. R_SUBFLAGINTERRUPT:
  908. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  909. R_SUBFLAGDIRECTION:
  910. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  911. R_SUBW,R_SUBD,R_SUBQ:
  912. { Everything except the direction bits }
  913. Result:=
  914. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  915. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  916. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  917. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  918. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  919. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  920. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  921. else
  922. ;
  923. end;
  924. if result then
  925. exit;
  926. end
  927. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  928. exit(true);
  929. Result:=inherited RegInInstruction(Reg, p1);
  930. end;
  931. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  932. const
  933. WriteOps: array[0..3] of set of TInsChange =
  934. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  935. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  936. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  937. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  938. var
  939. OperIdx: Integer;
  940. begin
  941. Result := False;
  942. if p1.typ <> ait_instruction then
  943. exit;
  944. with insprop[taicpu(p1).opcode] do
  945. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  946. begin
  947. case getsubreg(reg) of
  948. R_SUBW,R_SUBD,R_SUBQ:
  949. Result :=
  950. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  951. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  952. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  953. R_SUBFLAGCARRY:
  954. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  955. R_SUBFLAGPARITY:
  956. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  957. R_SUBFLAGAUXILIARY:
  958. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  959. R_SUBFLAGZERO:
  960. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  961. R_SUBFLAGSIGN:
  962. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  963. R_SUBFLAGOVERFLOW:
  964. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  965. R_SUBFLAGINTERRUPT:
  966. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  967. R_SUBFLAGDIRECTION:
  968. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  969. else
  970. internalerror(2017042602);
  971. end;
  972. exit;
  973. end;
  974. case taicpu(p1).opcode of
  975. A_CALL:
  976. { We could potentially set Result to False if the register in
  977. question is non-volatile for the subroutine's calling convention,
  978. but this would require detecting the calling convention in use and
  979. also assuming that the routine doesn't contain malformed assembly
  980. language, for example... so it could only be done under -O4 as it
  981. would be considered a side-effect. [Kit] }
  982. Result := True;
  983. A_MOVSD:
  984. { special handling for SSE MOVSD }
  985. if (taicpu(p1).ops>0) then
  986. begin
  987. if taicpu(p1).ops<>2 then
  988. internalerror(2017042703);
  989. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  990. end;
  991. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  992. so fix it here (FK)
  993. }
  994. A_VMOVSS,
  995. A_VMOVSD:
  996. begin
  997. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  998. exit;
  999. end;
  1000. A_IMUL:
  1001. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1002. else
  1003. ;
  1004. end;
  1005. if Result then
  1006. exit;
  1007. with insprop[taicpu(p1).opcode] do
  1008. begin
  1009. if getregtype(reg)=R_INTREGISTER then
  1010. begin
  1011. case getsupreg(reg) of
  1012. RS_EAX:
  1013. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1014. begin
  1015. Result := True;
  1016. exit
  1017. end;
  1018. RS_ECX:
  1019. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1020. begin
  1021. Result := True;
  1022. exit
  1023. end;
  1024. RS_EDX:
  1025. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1026. begin
  1027. Result := True;
  1028. exit
  1029. end;
  1030. RS_EBX:
  1031. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1032. begin
  1033. Result := True;
  1034. exit
  1035. end;
  1036. RS_ESP:
  1037. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1038. begin
  1039. Result := True;
  1040. exit
  1041. end;
  1042. RS_EBP:
  1043. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1044. begin
  1045. Result := True;
  1046. exit
  1047. end;
  1048. RS_ESI:
  1049. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1050. begin
  1051. Result := True;
  1052. exit
  1053. end;
  1054. RS_EDI:
  1055. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1056. begin
  1057. Result := True;
  1058. exit
  1059. end;
  1060. end;
  1061. end;
  1062. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1063. if (WriteOps[OperIdx]*Ch<>[]) and
  1064. { The register doesn't get modified inside a reference }
  1065. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1066. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1067. begin
  1068. Result := true;
  1069. exit
  1070. end;
  1071. end;
  1072. end;
  1073. {$ifdef DEBUG_AOPTCPU}
  1074. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1075. begin
  1076. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1077. end;
  1078. function debug_tostr(i: tcgint): string; inline;
  1079. begin
  1080. Result := tostr(i);
  1081. end;
  1082. function debug_regname(r: TRegister): string; inline;
  1083. begin
  1084. Result := '%' + std_regname(r);
  1085. end;
  1086. { Debug output function - creates a string representation of an operator }
  1087. function debug_operstr(oper: TOper): string;
  1088. begin
  1089. case oper.typ of
  1090. top_const:
  1091. Result := '$' + debug_tostr(oper.val);
  1092. top_reg:
  1093. Result := debug_regname(oper.reg);
  1094. top_ref:
  1095. begin
  1096. if oper.ref^.offset <> 0 then
  1097. Result := debug_tostr(oper.ref^.offset) + '('
  1098. else
  1099. Result := '(';
  1100. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1101. begin
  1102. Result := Result + debug_regname(oper.ref^.base);
  1103. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1104. Result := Result + ',' + debug_regname(oper.ref^.index);
  1105. end
  1106. else
  1107. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1108. Result := Result + debug_regname(oper.ref^.index);
  1109. if (oper.ref^.scalefactor > 1) then
  1110. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1111. else
  1112. Result := Result + ')';
  1113. end;
  1114. else
  1115. Result := '[UNKNOWN]';
  1116. end;
  1117. end;
  1118. function debug_op2str(opcode: tasmop): string; inline;
  1119. begin
  1120. Result := std_op2str[opcode];
  1121. end;
  1122. function debug_opsize2str(opsize: topsize): string; inline;
  1123. begin
  1124. Result := gas_opsize2str[opsize];
  1125. end;
  1126. {$else DEBUG_AOPTCPU}
  1127. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1128. begin
  1129. end;
  1130. function debug_tostr(i: tcgint): string; inline;
  1131. begin
  1132. Result := '';
  1133. end;
  1134. function debug_regname(r: TRegister): string; inline;
  1135. begin
  1136. Result := '';
  1137. end;
  1138. function debug_operstr(oper: TOper): string; inline;
  1139. begin
  1140. Result := '';
  1141. end;
  1142. function debug_op2str(opcode: tasmop): string; inline;
  1143. begin
  1144. Result := '';
  1145. end;
  1146. function debug_opsize2str(opsize: topsize): string; inline;
  1147. begin
  1148. Result := '';
  1149. end;
  1150. {$endif DEBUG_AOPTCPU}
  1151. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1152. begin
  1153. {$ifdef x86_64}
  1154. { Always fine on x86-64 }
  1155. Result := True;
  1156. {$else x86_64}
  1157. Result :=
  1158. {$ifdef i8086}
  1159. (current_settings.cputype >= cpu_386) and
  1160. {$endif i8086}
  1161. (
  1162. { Always accept if optimising for size }
  1163. (cs_opt_size in current_settings.optimizerswitches) or
  1164. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1165. (current_settings.optimizecputype >= cpu_Pentium2)
  1166. );
  1167. {$endif x86_64}
  1168. end;
  1169. { Attempts to allocate a volatile integer register for use between p and hp,
  1170. using AUsedRegs for the current register usage information. Returns NR_NO
  1171. if no free register could be found }
  1172. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1173. var
  1174. RegSet: TCPURegisterSet;
  1175. CurrentSuperReg: Integer;
  1176. CurrentReg: TRegister;
  1177. Currentp: tai;
  1178. Breakout: Boolean;
  1179. begin
  1180. Result := NR_NO;
  1181. RegSet :=
  1182. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1183. current_procinfo.saved_regs_int;
  1184. for CurrentSuperReg in RegSet do
  1185. begin
  1186. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1187. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1188. {$if defined(i386) or defined(i8086)}
  1189. { If the target size is 8-bit, make sure we can actually encode it }
  1190. and (
  1191. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1192. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1193. )
  1194. {$endif i386 or i8086}
  1195. then
  1196. begin
  1197. Currentp := p;
  1198. Breakout := False;
  1199. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1200. begin
  1201. case Currentp.typ of
  1202. ait_instruction:
  1203. begin
  1204. if RegInInstruction(CurrentReg, Currentp) then
  1205. begin
  1206. Breakout := True;
  1207. Break;
  1208. end;
  1209. { Cannot allocate across an unconditional jump }
  1210. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1211. Exit;
  1212. end;
  1213. ait_marker:
  1214. { Don't try anything more if a marker is hit }
  1215. Exit;
  1216. ait_regalloc:
  1217. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1218. begin
  1219. Breakout := True;
  1220. Break;
  1221. end;
  1222. else
  1223. ;
  1224. end;
  1225. end;
  1226. if Breakout then
  1227. { Try the next register }
  1228. Continue;
  1229. { We have a free register available }
  1230. Result := CurrentReg;
  1231. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1232. Exit;
  1233. end;
  1234. end;
  1235. end;
  1236. { Attempts to allocate a volatile MM register for use between p and hp,
  1237. using AUsedRegs for the current register usage information. Returns NR_NO
  1238. if no free register could be found }
  1239. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1240. var
  1241. RegSet: TCPURegisterSet;
  1242. CurrentSuperReg: Integer;
  1243. CurrentReg: TRegister;
  1244. Currentp: tai;
  1245. Breakout: Boolean;
  1246. begin
  1247. Result := NR_NO;
  1248. RegSet :=
  1249. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1250. current_procinfo.saved_regs_mm;
  1251. for CurrentSuperReg in RegSet do
  1252. begin
  1253. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1254. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1255. begin
  1256. Currentp := p;
  1257. Breakout := False;
  1258. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1259. begin
  1260. case Currentp.typ of
  1261. ait_instruction:
  1262. begin
  1263. if RegInInstruction(CurrentReg, Currentp) then
  1264. begin
  1265. Breakout := True;
  1266. Break;
  1267. end;
  1268. { Cannot allocate across an unconditional jump }
  1269. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1270. Exit;
  1271. end;
  1272. ait_marker:
  1273. { Don't try anything more if a marker is hit }
  1274. Exit;
  1275. ait_regalloc:
  1276. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1277. begin
  1278. Breakout := True;
  1279. Break;
  1280. end;
  1281. else
  1282. ;
  1283. end;
  1284. end;
  1285. if Breakout then
  1286. { Try the next register }
  1287. Continue;
  1288. { We have a free register available }
  1289. Result := CurrentReg;
  1290. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1291. Exit;
  1292. end;
  1293. end;
  1294. end;
  1295. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1296. begin
  1297. if not SuperRegistersEqual(reg1,reg2) then
  1298. exit(false);
  1299. if getregtype(reg1)<>R_INTREGISTER then
  1300. exit(true); {because SuperRegisterEqual is true}
  1301. case getsubreg(reg1) of
  1302. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1303. higher, it preserves the high bits, so the new value depends on
  1304. reg2's previous value. In other words, it is equivalent to doing:
  1305. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)=R_SUBL);
  1308. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1309. higher, it actually does a:
  1310. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1311. R_SUBH:
  1312. exit(getsubreg(reg2)=R_SUBH);
  1313. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1314. bits of reg2:
  1315. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1316. R_SUBW:
  1317. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1318. { a write to R_SUBD always overwrites every other subregister,
  1319. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1320. R_SUBD,
  1321. R_SUBQ:
  1322. exit(true);
  1323. else
  1324. internalerror(2017042801);
  1325. end;
  1326. end;
  1327. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1328. begin
  1329. if not SuperRegistersEqual(reg1,reg2) then
  1330. exit(false);
  1331. if getregtype(reg1)<>R_INTREGISTER then
  1332. exit(true); {because SuperRegisterEqual is true}
  1333. case getsubreg(reg1) of
  1334. R_SUBL:
  1335. exit(getsubreg(reg2)<>R_SUBH);
  1336. R_SUBH:
  1337. exit(getsubreg(reg2)<>R_SUBL);
  1338. R_SUBW,
  1339. R_SUBD,
  1340. R_SUBQ:
  1341. exit(true);
  1342. else
  1343. internalerror(2017042802);
  1344. end;
  1345. end;
  1346. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1347. var
  1348. hp1 : tai;
  1349. l : TCGInt;
  1350. begin
  1351. result:=false;
  1352. { changes the code sequence
  1353. shr/sar const1, x
  1354. shl const2, x
  1355. to
  1356. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1357. if GetNextInstruction(p, hp1) and
  1358. MatchInstruction(hp1,A_SHL,[]) and
  1359. (taicpu(p).oper[0]^.typ = top_const) and
  1360. (taicpu(hp1).oper[0]^.typ = top_const) and
  1361. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1362. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1363. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1364. begin
  1365. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1366. not(cs_opt_size in current_settings.optimizerswitches) then
  1367. begin
  1368. { shr/sar const1, %reg
  1369. shl const2, %reg
  1370. with const1 > const2 }
  1371. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1372. taicpu(hp1).opcode := A_AND;
  1373. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1374. case taicpu(p).opsize Of
  1375. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1376. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1377. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1378. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1379. else
  1380. Internalerror(2017050703)
  1381. end;
  1382. end
  1383. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1384. not(cs_opt_size in current_settings.optimizerswitches) then
  1385. begin
  1386. { shr/sar const1, %reg
  1387. shl const2, %reg
  1388. with const1 < const2 }
  1389. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1390. taicpu(p).opcode := A_AND;
  1391. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1392. case taicpu(p).opsize Of
  1393. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1394. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1395. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1396. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1397. else
  1398. Internalerror(2017050702)
  1399. end;
  1400. end
  1401. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1402. begin
  1403. { shr/sar const1, %reg
  1404. shl const2, %reg
  1405. with const1 = const2 }
  1406. taicpu(p).opcode := A_AND;
  1407. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1408. case taicpu(p).opsize Of
  1409. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1410. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1411. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1412. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1413. else
  1414. Internalerror(2017050701)
  1415. end;
  1416. RemoveInstruction(hp1);
  1417. end;
  1418. end;
  1419. end;
  1420. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1421. var
  1422. opsize : topsize;
  1423. hp1, hp2 : tai;
  1424. tmpref : treference;
  1425. ShiftValue : Cardinal;
  1426. BaseValue : TCGInt;
  1427. begin
  1428. result:=false;
  1429. opsize:=taicpu(p).opsize;
  1430. { changes certain "imul const, %reg"'s to lea sequences }
  1431. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1432. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1433. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1434. if (taicpu(p).oper[0]^.val = 1) then
  1435. if (taicpu(p).ops = 2) then
  1436. { remove "imul $1, reg" }
  1437. begin
  1438. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1439. Result := RemoveCurrentP(p);
  1440. end
  1441. else
  1442. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1443. begin
  1444. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1445. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1446. asml.InsertAfter(hp1, p);
  1447. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1448. RemoveCurrentP(p, hp1);
  1449. Result := True;
  1450. end
  1451. else if ((taicpu(p).ops <= 2) or
  1452. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1453. not(cs_opt_size in current_settings.optimizerswitches) and
  1454. (not(GetNextInstruction(p, hp1)) or
  1455. not((tai(hp1).typ = ait_instruction) and
  1456. ((taicpu(hp1).opcode=A_Jcc) and
  1457. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1458. begin
  1459. {
  1460. imul X, reg1, reg2 to
  1461. lea (reg1,reg1,Y), reg2
  1462. shl ZZ,reg2
  1463. imul XX, reg1 to
  1464. lea (reg1,reg1,YY), reg1
  1465. shl ZZ,reg2
  1466. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1467. it does not exist as a separate optimization target in FPC though.
  1468. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1469. at most two zeros
  1470. }
  1471. reference_reset(tmpref,1,[]);
  1472. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1473. begin
  1474. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1475. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1476. TmpRef.base := taicpu(p).oper[1]^.reg;
  1477. TmpRef.index := taicpu(p).oper[1]^.reg;
  1478. if not(BaseValue in [3,5,9]) then
  1479. Internalerror(2018110101);
  1480. TmpRef.ScaleFactor := BaseValue-1;
  1481. if (taicpu(p).ops = 2) then
  1482. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1483. else
  1484. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1485. AsmL.InsertAfter(hp1,p);
  1486. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1487. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1488. RemoveCurrentP(p, hp1);
  1489. if ShiftValue>0 then
  1490. begin
  1491. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1492. AsmL.InsertAfter(hp2,hp1);
  1493. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1494. end;
  1495. Result := True;
  1496. end;
  1497. end;
  1498. end;
  1499. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1500. begin
  1501. Result := False;
  1502. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1503. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1504. begin
  1505. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1506. taicpu(p).opcode := A_MOV;
  1507. Result := True;
  1508. end;
  1509. end;
  1510. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1511. var
  1512. p: taicpu absolute hp; { Implicit typecast }
  1513. i: Integer;
  1514. begin
  1515. Result := False;
  1516. if not assigned(hp) or
  1517. (hp.typ <> ait_instruction) then
  1518. Exit;
  1519. Prefetch(insprop[p.opcode]);
  1520. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1521. with insprop[p.opcode] do
  1522. begin
  1523. case getsubreg(reg) of
  1524. R_SUBW,R_SUBD,R_SUBQ:
  1525. Result:=
  1526. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1527. uncommon flags are checked first }
  1528. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1529. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1531. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1532. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1533. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1534. R_SUBFLAGCARRY:
  1535. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1536. R_SUBFLAGPARITY:
  1537. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1538. R_SUBFLAGAUXILIARY:
  1539. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1540. R_SUBFLAGZERO:
  1541. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1542. R_SUBFLAGSIGN:
  1543. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1544. R_SUBFLAGOVERFLOW:
  1545. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1546. R_SUBFLAGINTERRUPT:
  1547. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1548. R_SUBFLAGDIRECTION:
  1549. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1550. else
  1551. internalerror(2017050501);
  1552. end;
  1553. exit;
  1554. end;
  1555. { Handle special cases first }
  1556. case p.opcode of
  1557. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1558. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1559. begin
  1560. Result :=
  1561. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1562. (p.oper[1]^.typ = top_reg) and
  1563. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1564. (
  1565. (p.oper[0]^.typ = top_const) or
  1566. (
  1567. (p.oper[0]^.typ = top_reg) and
  1568. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1569. ) or (
  1570. (p.oper[0]^.typ = top_ref) and
  1571. not RegInRef(reg,p.oper[0]^.ref^)
  1572. )
  1573. );
  1574. end;
  1575. A_MUL, A_IMUL:
  1576. Result :=
  1577. (
  1578. (p.ops=3) and { IMUL only }
  1579. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1580. (
  1581. (
  1582. (p.oper[1]^.typ=top_reg) and
  1583. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1584. ) or (
  1585. (p.oper[1]^.typ=top_ref) and
  1586. not RegInRef(reg,p.oper[1]^.ref^)
  1587. )
  1588. )
  1589. ) or (
  1590. (
  1591. (p.ops=1) and
  1592. (
  1593. (
  1594. (
  1595. (p.oper[0]^.typ=top_reg) and
  1596. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1597. )
  1598. ) or (
  1599. (p.oper[0]^.typ=top_ref) and
  1600. not RegInRef(reg,p.oper[0]^.ref^)
  1601. )
  1602. ) and (
  1603. (
  1604. (p.opsize=S_B) and
  1605. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1606. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1607. ) or (
  1608. (p.opsize=S_W) and
  1609. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1610. ) or (
  1611. (p.opsize=S_L) and
  1612. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1613. {$ifdef x86_64}
  1614. ) or (
  1615. (p.opsize=S_Q) and
  1616. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1617. {$endif x86_64}
  1618. )
  1619. )
  1620. )
  1621. );
  1622. A_CBW:
  1623. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1624. {$ifndef x86_64}
  1625. A_LDS:
  1626. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1627. A_LES:
  1628. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1629. {$endif not x86_64}
  1630. A_LFS:
  1631. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1632. A_LGS:
  1633. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1634. A_LSS:
  1635. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1636. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1637. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1638. A_LODSB:
  1639. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1640. A_LODSW:
  1641. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1642. {$ifdef x86_64}
  1643. A_LODSQ:
  1644. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1645. {$endif x86_64}
  1646. A_LODSD:
  1647. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1648. A_FSTSW, A_FNSTSW:
  1649. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1650. else
  1651. begin
  1652. with insprop[p.opcode] do
  1653. begin
  1654. if (
  1655. { xor %reg,%reg etc. is classed as a new value }
  1656. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1657. MatchOpType(p, top_reg, top_reg) and
  1658. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1659. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1660. ) then
  1661. begin
  1662. Result := True;
  1663. Exit;
  1664. end;
  1665. { Make sure the entire register is overwritten }
  1666. if (getregtype(reg) = R_INTREGISTER) then
  1667. begin
  1668. if (p.ops > 0) then
  1669. begin
  1670. if RegInOp(reg, p.oper[0]^) then
  1671. begin
  1672. if (p.oper[0]^.typ = top_ref) then
  1673. begin
  1674. if RegInRef(reg, p.oper[0]^.ref^) then
  1675. begin
  1676. Result := False;
  1677. Exit;
  1678. end;
  1679. end
  1680. else if (p.oper[0]^.typ = top_reg) then
  1681. begin
  1682. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1683. begin
  1684. Result := False;
  1685. Exit;
  1686. end
  1687. else if ([Ch_WOp1]*Ch<>[]) then
  1688. begin
  1689. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1690. Result := True
  1691. else
  1692. begin
  1693. Result := False;
  1694. Exit;
  1695. end;
  1696. end;
  1697. end;
  1698. end;
  1699. if (p.ops > 1) then
  1700. begin
  1701. if RegInOp(reg, p.oper[1]^) then
  1702. begin
  1703. if (p.oper[1]^.typ = top_ref) then
  1704. begin
  1705. if RegInRef(reg, p.oper[1]^.ref^) then
  1706. begin
  1707. Result := False;
  1708. Exit;
  1709. end;
  1710. end
  1711. else if (p.oper[1]^.typ = top_reg) then
  1712. begin
  1713. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1714. begin
  1715. Result := False;
  1716. Exit;
  1717. end
  1718. else if ([Ch_WOp2]*Ch<>[]) then
  1719. begin
  1720. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1721. Result := True
  1722. else
  1723. begin
  1724. Result := False;
  1725. Exit;
  1726. end;
  1727. end;
  1728. end;
  1729. end;
  1730. if (p.ops > 2) then
  1731. begin
  1732. if RegInOp(reg, p.oper[2]^) then
  1733. begin
  1734. if (p.oper[2]^.typ = top_ref) then
  1735. begin
  1736. if RegInRef(reg, p.oper[2]^.ref^) then
  1737. begin
  1738. Result := False;
  1739. Exit;
  1740. end;
  1741. end
  1742. else if (p.oper[2]^.typ = top_reg) then
  1743. begin
  1744. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1745. begin
  1746. Result := False;
  1747. Exit;
  1748. end
  1749. else if ([Ch_WOp3]*Ch<>[]) then
  1750. begin
  1751. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1752. Result := True
  1753. else
  1754. begin
  1755. Result := False;
  1756. Exit;
  1757. end;
  1758. end;
  1759. end;
  1760. end;
  1761. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1762. begin
  1763. if (p.oper[3]^.typ = top_ref) then
  1764. begin
  1765. if RegInRef(reg, p.oper[3]^.ref^) then
  1766. begin
  1767. Result := False;
  1768. Exit;
  1769. end;
  1770. end
  1771. else if (p.oper[3]^.typ = top_reg) then
  1772. begin
  1773. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1774. begin
  1775. Result := False;
  1776. Exit;
  1777. end
  1778. else if ([Ch_WOp4]*Ch<>[]) then
  1779. begin
  1780. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1781. Result := True
  1782. else
  1783. begin
  1784. Result := False;
  1785. Exit;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. end;
  1791. end;
  1792. end;
  1793. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1794. case getsupreg(reg) of
  1795. RS_EAX:
  1796. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1797. begin
  1798. Result := True;
  1799. Exit;
  1800. end;
  1801. RS_ECX:
  1802. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1803. begin
  1804. Result := True;
  1805. Exit;
  1806. end;
  1807. RS_EDX:
  1808. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1809. begin
  1810. Result := True;
  1811. Exit;
  1812. end;
  1813. RS_EBX:
  1814. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1815. begin
  1816. Result := True;
  1817. Exit;
  1818. end;
  1819. RS_ESP:
  1820. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1821. begin
  1822. Result := True;
  1823. Exit;
  1824. end;
  1825. RS_EBP:
  1826. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1827. begin
  1828. Result := True;
  1829. Exit;
  1830. end;
  1831. RS_ESI:
  1832. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1833. begin
  1834. Result := True;
  1835. Exit;
  1836. end;
  1837. RS_EDI:
  1838. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1839. begin
  1840. Result := True;
  1841. Exit;
  1842. end;
  1843. else
  1844. ;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. end;
  1851. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1852. var
  1853. hp2,hp3 : tai;
  1854. begin
  1855. { some x86-64 issue a NOP before the real exit code }
  1856. if MatchInstruction(p,A_NOP,[]) then
  1857. GetNextInstruction(p,p);
  1858. result:=assigned(p) and (p.typ=ait_instruction) and
  1859. ((taicpu(p).opcode = A_RET) or
  1860. ((taicpu(p).opcode=A_LEAVE) and
  1861. GetNextInstruction(p,hp2) and
  1862. MatchInstruction(hp2,A_RET,[S_NO])
  1863. ) or
  1864. (((taicpu(p).opcode=A_LEA) and
  1865. MatchOpType(taicpu(p),top_ref,top_reg) and
  1866. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1867. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1868. ) and
  1869. GetNextInstruction(p,hp2) and
  1870. MatchInstruction(hp2,A_RET,[S_NO])
  1871. ) or
  1872. ((((taicpu(p).opcode=A_MOV) and
  1873. MatchOpType(taicpu(p),top_reg,top_reg) and
  1874. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1875. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1876. ((taicpu(p).opcode=A_LEA) and
  1877. MatchOpType(taicpu(p),top_ref,top_reg) and
  1878. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1879. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1880. )
  1881. ) and
  1882. GetNextInstruction(p,hp2) and
  1883. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1884. MatchOpType(taicpu(hp2),top_reg) and
  1885. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1886. GetNextInstruction(hp2,hp3) and
  1887. MatchInstruction(hp3,A_RET,[S_NO])
  1888. )
  1889. );
  1890. end;
  1891. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1892. begin
  1893. isFoldableArithOp := False;
  1894. case hp1.opcode of
  1895. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1896. isFoldableArithOp :=
  1897. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1898. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1899. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1900. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1901. (taicpu(hp1).oper[1]^.reg = reg);
  1902. A_INC,A_DEC,A_NEG,A_NOT:
  1903. isFoldableArithOp :=
  1904. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1905. (taicpu(hp1).oper[0]^.reg = reg);
  1906. else
  1907. ;
  1908. end;
  1909. end;
  1910. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1911. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1912. var
  1913. hp2: tai;
  1914. begin
  1915. hp2 := p;
  1916. repeat
  1917. hp2 := tai(hp2.previous);
  1918. if assigned(hp2) and
  1919. (hp2.typ = ait_regalloc) and
  1920. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1921. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1922. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1923. begin
  1924. RemoveInstruction(hp2);
  1925. break;
  1926. end;
  1927. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1928. end;
  1929. begin
  1930. case current_procinfo.procdef.returndef.typ of
  1931. arraydef,recorddef,pointerdef,
  1932. stringdef,enumdef,procdef,objectdef,errordef,
  1933. filedef,setdef,procvardef,
  1934. classrefdef,forwarddef:
  1935. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1936. orddef:
  1937. if current_procinfo.procdef.returndef.size <> 0 then
  1938. begin
  1939. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1940. { for int64/qword }
  1941. if current_procinfo.procdef.returndef.size = 8 then
  1942. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1943. end;
  1944. else
  1945. ;
  1946. end;
  1947. end;
  1948. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1949. var
  1950. hp1,hp2 : tai;
  1951. begin
  1952. result:=false;
  1953. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1954. begin
  1955. { vmova* reg1,reg1
  1956. =>
  1957. <nop> }
  1958. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1959. begin
  1960. RemoveCurrentP(p);
  1961. result:=true;
  1962. exit;
  1963. end
  1964. else if GetNextInstruction(p,hp1) then
  1965. begin
  1966. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1967. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1968. begin
  1969. { vmova* reg1,reg2
  1970. vmova* reg2,reg3
  1971. dealloc reg2
  1972. =>
  1973. vmova* reg1,reg3 }
  1974. TransferUsedRegs(TmpUsedRegs);
  1975. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1976. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1977. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1978. begin
  1979. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1980. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1981. RemoveInstruction(hp1);
  1982. result:=true;
  1983. exit;
  1984. end
  1985. { special case:
  1986. vmova* reg1,<op>
  1987. vmova* <op>,reg1
  1988. =>
  1989. vmova* reg1,<op> }
  1990. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1991. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1992. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1993. ) then
  1994. begin
  1995. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1996. RemoveInstruction(hp1);
  1997. result:=true;
  1998. exit;
  1999. end
  2000. end
  2001. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2002. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2003. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2004. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2005. ) and
  2006. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2007. begin
  2008. { vmova* reg1,reg2
  2009. vmovs* reg2,<op>
  2010. dealloc reg2
  2011. =>
  2012. vmovs* reg1,reg3 }
  2013. TransferUsedRegs(TmpUsedRegs);
  2014. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2015. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2016. begin
  2017. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2018. taicpu(p).opcode:=taicpu(hp1).opcode;
  2019. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2020. RemoveInstruction(hp1);
  2021. result:=true;
  2022. exit;
  2023. end
  2024. end;
  2025. end;
  2026. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2027. begin
  2028. if MatchInstruction(hp1,[A_VFMADDPD,
  2029. A_VFMADD132PD,
  2030. A_VFMADD132PS,
  2031. A_VFMADD132SD,
  2032. A_VFMADD132SS,
  2033. A_VFMADD213PD,
  2034. A_VFMADD213PS,
  2035. A_VFMADD213SD,
  2036. A_VFMADD213SS,
  2037. A_VFMADD231PD,
  2038. A_VFMADD231PS,
  2039. A_VFMADD231SD,
  2040. A_VFMADD231SS,
  2041. A_VFMADDSUB132PD,
  2042. A_VFMADDSUB132PS,
  2043. A_VFMADDSUB213PD,
  2044. A_VFMADDSUB213PS,
  2045. A_VFMADDSUB231PD,
  2046. A_VFMADDSUB231PS,
  2047. A_VFMSUB132PD,
  2048. A_VFMSUB132PS,
  2049. A_VFMSUB132SD,
  2050. A_VFMSUB132SS,
  2051. A_VFMSUB213PD,
  2052. A_VFMSUB213PS,
  2053. A_VFMSUB213SD,
  2054. A_VFMSUB213SS,
  2055. A_VFMSUB231PD,
  2056. A_VFMSUB231PS,
  2057. A_VFMSUB231SD,
  2058. A_VFMSUB231SS,
  2059. A_VFMSUBADD132PD,
  2060. A_VFMSUBADD132PS,
  2061. A_VFMSUBADD213PD,
  2062. A_VFMSUBADD213PS,
  2063. A_VFMSUBADD231PD,
  2064. A_VFMSUBADD231PS,
  2065. A_VFNMADD132PD,
  2066. A_VFNMADD132PS,
  2067. A_VFNMADD132SD,
  2068. A_VFNMADD132SS,
  2069. A_VFNMADD213PD,
  2070. A_VFNMADD213PS,
  2071. A_VFNMADD213SD,
  2072. A_VFNMADD213SS,
  2073. A_VFNMADD231PD,
  2074. A_VFNMADD231PS,
  2075. A_VFNMADD231SD,
  2076. A_VFNMADD231SS,
  2077. A_VFNMSUB132PD,
  2078. A_VFNMSUB132PS,
  2079. A_VFNMSUB132SD,
  2080. A_VFNMSUB132SS,
  2081. A_VFNMSUB213PD,
  2082. A_VFNMSUB213PS,
  2083. A_VFNMSUB213SD,
  2084. A_VFNMSUB213SS,
  2085. A_VFNMSUB231PD,
  2086. A_VFNMSUB231PS,
  2087. A_VFNMSUB231SD,
  2088. A_VFNMSUB231SS],[S_NO]) and
  2089. { we mix single and double opperations here because we assume that the compiler
  2090. generates vmovapd only after double operations and vmovaps only after single operations }
  2091. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2092. GetNextInstruction(hp1,hp2) and
  2093. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2094. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2095. begin
  2096. TransferUsedRegs(TmpUsedRegs);
  2097. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2098. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2099. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2100. begin
  2101. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2102. RemoveCurrentP(p);
  2103. RemoveInstruction(hp2);
  2104. end;
  2105. end
  2106. else if (hp1.typ = ait_instruction) and
  2107. GetNextInstruction(hp1, hp2) and
  2108. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2109. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2110. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2111. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2112. (((taicpu(p).opcode=A_MOVAPS) and
  2113. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2114. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2115. ((taicpu(p).opcode=A_MOVAPD) and
  2116. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2117. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2118. ) then
  2119. { change
  2120. movapX reg,reg2
  2121. addsX/subsX/... reg3, reg2
  2122. movapX reg2,reg
  2123. to
  2124. addsX/subsX/... reg3,reg
  2125. }
  2126. begin
  2127. TransferUsedRegs(TmpUsedRegs);
  2128. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2129. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2130. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2131. begin
  2132. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2133. debug_op2str(taicpu(p).opcode)+' '+
  2134. debug_op2str(taicpu(hp1).opcode)+' '+
  2135. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2136. { we cannot eliminate the first move if
  2137. the operations uses the same register for source and dest }
  2138. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2139. { Remember that hp1 is not necessarily the immediate
  2140. next instruction }
  2141. RemoveCurrentP(p);
  2142. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2143. RemoveInstruction(hp2);
  2144. result:=true;
  2145. end;
  2146. end
  2147. else if (hp1.typ = ait_instruction) and
  2148. (((taicpu(p).opcode=A_VMOVAPD) and
  2149. (taicpu(hp1).opcode=A_VCOMISD)) or
  2150. ((taicpu(p).opcode=A_VMOVAPS) and
  2151. ((taicpu(hp1).opcode=A_VCOMISS))
  2152. )
  2153. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2154. { change
  2155. movapX reg,reg1
  2156. vcomisX reg1,reg1
  2157. to
  2158. vcomisX reg,reg
  2159. }
  2160. begin
  2161. TransferUsedRegs(TmpUsedRegs);
  2162. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2163. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2164. begin
  2165. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2166. debug_op2str(taicpu(p).opcode)+' '+
  2167. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2168. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2169. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2170. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2171. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2172. RemoveCurrentP(p);
  2173. result:=true;
  2174. exit;
  2175. end;
  2176. end
  2177. end;
  2178. end;
  2179. end;
  2180. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2181. var
  2182. hp1 : tai;
  2183. begin
  2184. result:=false;
  2185. { replace
  2186. V<Op>X %mreg1,%mreg2,%mreg3
  2187. VMovX %mreg3,%mreg4
  2188. dealloc %mreg3
  2189. by
  2190. V<Op>X %mreg1,%mreg2,%mreg4
  2191. ?
  2192. }
  2193. if GetNextInstruction(p,hp1) and
  2194. { we mix single and double operations here because we assume that the compiler
  2195. generates vmovapd only after double operations and vmovaps only after single operations }
  2196. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2197. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2198. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2199. begin
  2200. TransferUsedRegs(TmpUsedRegs);
  2201. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2202. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2203. begin
  2204. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2205. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2206. RemoveInstruction(hp1);
  2207. result:=true;
  2208. end;
  2209. end;
  2210. end;
  2211. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2212. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2213. begin
  2214. Result := False;
  2215. { For safety reasons, only check for exact register matches }
  2216. { Check base register }
  2217. if (ref.base = AOldReg) then
  2218. begin
  2219. ref.base := ANewReg;
  2220. Result := True;
  2221. end;
  2222. { Check index register }
  2223. if (ref.index = AOldReg) then
  2224. begin
  2225. ref.index := ANewReg;
  2226. Result := True;
  2227. end;
  2228. end;
  2229. { Replaces all references to AOldReg in an operand to ANewReg }
  2230. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2231. var
  2232. OldSupReg, NewSupReg: TSuperRegister;
  2233. OldSubReg, NewSubReg: TSubRegister;
  2234. OldRegType: TRegisterType;
  2235. ThisOper: POper;
  2236. begin
  2237. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2238. Result := False;
  2239. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2240. InternalError(2020011801);
  2241. OldSupReg := getsupreg(AOldReg);
  2242. OldSubReg := getsubreg(AOldReg);
  2243. OldRegType := getregtype(AOldReg);
  2244. NewSupReg := getsupreg(ANewReg);
  2245. NewSubReg := getsubreg(ANewReg);
  2246. if OldRegType <> getregtype(ANewReg) then
  2247. InternalError(2020011802);
  2248. if OldSubReg <> NewSubReg then
  2249. InternalError(2020011803);
  2250. case ThisOper^.typ of
  2251. top_reg:
  2252. if (
  2253. (ThisOper^.reg = AOldReg) or
  2254. (
  2255. (OldRegType = R_INTREGISTER) and
  2256. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2257. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2258. (
  2259. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2260. {$ifndef x86_64}
  2261. and (
  2262. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2263. don't have an 8-bit representation }
  2264. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2265. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2266. )
  2267. {$endif x86_64}
  2268. )
  2269. )
  2270. ) then
  2271. begin
  2272. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2273. Result := True;
  2274. end;
  2275. top_ref:
  2276. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2277. Result := True;
  2278. else
  2279. ;
  2280. end;
  2281. end;
  2282. { Replaces all references to AOldReg in an instruction to ANewReg }
  2283. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2284. const
  2285. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2286. var
  2287. OperIdx: Integer;
  2288. begin
  2289. Result := False;
  2290. for OperIdx := 0 to p.ops - 1 do
  2291. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2292. begin
  2293. { The shift and rotate instructions can only use CL }
  2294. if not (
  2295. (OperIdx = 0) and
  2296. { This second condition just helps to avoid unnecessarily
  2297. calling MatchInstruction for 10 different opcodes }
  2298. (p.oper[0]^.reg = NR_CL) and
  2299. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2300. ) then
  2301. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2302. end
  2303. else if p.oper[OperIdx]^.typ = top_ref then
  2304. { It's okay to replace registers in references that get written to }
  2305. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2306. end;
  2307. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2308. begin
  2309. with ref^ do
  2310. Result :=
  2311. (index = NR_NO) and
  2312. (
  2313. {$ifdef x86_64}
  2314. (
  2315. (base = NR_RIP) and
  2316. (refaddr in [addr_pic, addr_pic_no_got])
  2317. ) or
  2318. {$endif x86_64}
  2319. (base = NR_STACK_POINTER_REG) or
  2320. (base = current_procinfo.framepointer)
  2321. );
  2322. end;
  2323. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2324. var
  2325. l: asizeint;
  2326. begin
  2327. Result := False;
  2328. { Should have been checked previously }
  2329. if p.opcode <> A_LEA then
  2330. InternalError(2020072501);
  2331. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2332. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2333. not(cs_opt_size in current_settings.optimizerswitches) then
  2334. exit;
  2335. with p.oper[0]^.ref^ do
  2336. begin
  2337. if (base <> p.oper[1]^.reg) or
  2338. (index <> NR_NO) or
  2339. assigned(symbol) then
  2340. exit;
  2341. l:=offset;
  2342. if (l=1) and UseIncDec then
  2343. begin
  2344. p.opcode:=A_INC;
  2345. p.loadreg(0,p.oper[1]^.reg);
  2346. p.ops:=1;
  2347. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2348. end
  2349. else if (l=-1) and UseIncDec then
  2350. begin
  2351. p.opcode:=A_DEC;
  2352. p.loadreg(0,p.oper[1]^.reg);
  2353. p.ops:=1;
  2354. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2355. end
  2356. else
  2357. begin
  2358. if (l<0) and (l<>-2147483648) then
  2359. begin
  2360. p.opcode:=A_SUB;
  2361. p.loadConst(0,-l);
  2362. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2363. end
  2364. else
  2365. begin
  2366. p.opcode:=A_ADD;
  2367. p.loadConst(0,l);
  2368. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2369. end;
  2370. end;
  2371. end;
  2372. Result := True;
  2373. end;
  2374. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2375. var
  2376. CurrentReg, ReplaceReg: TRegister;
  2377. begin
  2378. Result := False;
  2379. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2380. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2381. case hp.opcode of
  2382. A_FSTSW, A_FNSTSW,
  2383. A_IN, A_INS, A_OUT, A_OUTS,
  2384. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2385. { These routines have explicit operands, but they are restricted in
  2386. what they can be (e.g. IN and OUT can only read from AL, AX or
  2387. EAX. }
  2388. Exit;
  2389. A_IMUL:
  2390. begin
  2391. { The 1-operand version writes to implicit registers
  2392. The 2-operand version reads from the first operator, and reads
  2393. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2394. the 3-operand version reads from a register that it doesn't write to
  2395. }
  2396. case hp.ops of
  2397. 1:
  2398. if (
  2399. (
  2400. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2401. ) or
  2402. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2403. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2404. begin
  2405. Result := True;
  2406. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2407. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2408. end;
  2409. 2:
  2410. { Only modify the first parameter }
  2411. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2412. begin
  2413. Result := True;
  2414. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2415. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2416. end;
  2417. 3:
  2418. { Only modify the second parameter }
  2419. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2420. begin
  2421. Result := True;
  2422. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2423. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2424. end;
  2425. else
  2426. InternalError(2020012901);
  2427. end;
  2428. end;
  2429. else
  2430. if (hp.ops > 0) and
  2431. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2432. begin
  2433. Result := True;
  2434. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2435. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2436. end;
  2437. end;
  2438. end;
  2439. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2440. var
  2441. hp2: tai;
  2442. p_SourceReg, p_TargetReg: TRegister;
  2443. begin
  2444. Result := False;
  2445. { Backward optimisation. If we have:
  2446. func. %reg1,%reg2
  2447. mov %reg2,%reg3
  2448. (dealloc %reg2)
  2449. Change to:
  2450. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2451. Perform similar optimisations with 1, 3 and 4-operand instructions
  2452. that only have one output.
  2453. }
  2454. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2455. begin
  2456. p_SourceReg := taicpu(p).oper[0]^.reg;
  2457. p_TargetReg := taicpu(p).oper[1]^.reg;
  2458. TransferUsedRegs(TmpUsedRegs);
  2459. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2460. GetLastInstruction(p, hp2) and
  2461. (hp2.typ = ait_instruction) and
  2462. { Have to make sure it's an instruction that only reads from
  2463. the first operands and only writes (not reads or modifies) to
  2464. the last one; in essence, a pure function such as BSR, POPCNT
  2465. or ANDN }
  2466. (
  2467. (
  2468. (taicpu(hp2).ops = 1) and
  2469. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2470. ) or
  2471. (
  2472. (taicpu(hp2).ops = 2) and
  2473. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2474. ) or
  2475. (
  2476. (taicpu(hp2).ops = 3) and
  2477. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2478. ) or
  2479. (
  2480. (taicpu(hp2).ops = 4) and
  2481. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2482. )
  2483. ) and
  2484. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2485. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2486. begin
  2487. case taicpu(hp2).opcode of
  2488. A_FSTSW, A_FNSTSW,
  2489. A_IN, A_INS, A_OUT, A_OUTS,
  2490. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2491. { These routines have explicit operands, but they are restricted in
  2492. what they can be (e.g. IN and OUT can only read from AL, AX or
  2493. EAX. }
  2494. ;
  2495. else
  2496. begin
  2497. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2498. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2499. if not RegInInstruction(p_TargetReg, hp2) then
  2500. begin
  2501. { Since we're allocating from an earlier point, we
  2502. need to remove the register from the tracking }
  2503. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2504. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2505. end;
  2506. RemoveCurrentp(p, hp1);
  2507. { If the Func was another MOV instruction, we might get
  2508. "mov %reg,%reg" that doesn't get removed in Pass 2
  2509. otherwise, so deal with it here (also do something
  2510. similar with lea (%reg),%reg}
  2511. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2512. begin
  2513. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2514. if p = hp2 then
  2515. RemoveCurrentp(p)
  2516. else
  2517. RemoveInstruction(hp2);
  2518. end;
  2519. Result := True;
  2520. Exit;
  2521. end;
  2522. end;
  2523. end;
  2524. end;
  2525. end;
  2526. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2527. var
  2528. hp1, hp2, hp3: tai;
  2529. DoOptimisation, TempBool: Boolean;
  2530. {$ifdef x86_64}
  2531. NewConst: TCGInt;
  2532. {$endif x86_64}
  2533. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2534. begin
  2535. if taicpu(hp1).opcode = signed_movop then
  2536. begin
  2537. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2538. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2539. end
  2540. else
  2541. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2542. end;
  2543. function TryConstMerge(var p1, p2: tai): Boolean;
  2544. var
  2545. ThisRef: TReference;
  2546. begin
  2547. Result := False;
  2548. ThisRef := taicpu(p2).oper[1]^.ref^;
  2549. { Only permit writes to the stack, since we can guarantee alignment with that }
  2550. if (ThisRef.index = NR_NO) and
  2551. (
  2552. (ThisRef.base = NR_STACK_POINTER_REG) or
  2553. (ThisRef.base = current_procinfo.framepointer)
  2554. ) then
  2555. begin
  2556. case taicpu(p).opsize of
  2557. S_B:
  2558. begin
  2559. { Word writes must be on a 2-byte boundary }
  2560. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2561. begin
  2562. { Reduce offset of second reference to see if it is sequential with the first }
  2563. Dec(ThisRef.offset, 1);
  2564. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2565. begin
  2566. { Make sure the constants aren't represented as a
  2567. negative number, as these won't merge properly }
  2568. taicpu(p1).opsize := S_W;
  2569. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2570. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2571. RemoveInstruction(p2);
  2572. Result := True;
  2573. end;
  2574. end;
  2575. end;
  2576. S_W:
  2577. begin
  2578. { Longword writes must be on a 4-byte boundary }
  2579. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2580. begin
  2581. { Reduce offset of second reference to see if it is sequential with the first }
  2582. Dec(ThisRef.offset, 2);
  2583. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2584. begin
  2585. { Make sure the constants aren't represented as a
  2586. negative number, as these won't merge properly }
  2587. taicpu(p1).opsize := S_L;
  2588. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2589. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2590. RemoveInstruction(p2);
  2591. Result := True;
  2592. end;
  2593. end;
  2594. end;
  2595. {$ifdef x86_64}
  2596. S_L:
  2597. begin
  2598. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2599. see if the constants can be encoded this way. }
  2600. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2601. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2602. { Quadword writes must be on an 8-byte boundary }
  2603. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2604. begin
  2605. { Reduce offset of second reference to see if it is sequential with the first }
  2606. Dec(ThisRef.offset, 4);
  2607. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2608. begin
  2609. { Make sure the constants aren't represented as a
  2610. negative number, as these won't merge properly }
  2611. taicpu(p1).opsize := S_Q;
  2612. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2613. taicpu(p1).oper[0]^.val := NewConst;
  2614. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2615. RemoveInstruction(p2);
  2616. Result := True;
  2617. end;
  2618. end;
  2619. end;
  2620. {$endif x86_64}
  2621. else
  2622. ;
  2623. end;
  2624. end;
  2625. end;
  2626. var
  2627. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2628. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2629. NewSize: topsize; NewOffset: asizeint;
  2630. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2631. SourceRef, TargetRef: TReference;
  2632. MovAligned, MovUnaligned: TAsmOp;
  2633. ThisRef: TReference;
  2634. JumpTracking: TLinkedList;
  2635. begin
  2636. Result:=false;
  2637. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2638. { remove mov reg1,reg1? }
  2639. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2640. then
  2641. begin
  2642. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2643. { take care of the register (de)allocs following p }
  2644. RemoveCurrentP(p, hp1);
  2645. Result:=true;
  2646. exit;
  2647. end;
  2648. { All the next optimisations require a next instruction }
  2649. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2650. Exit;
  2651. { Prevent compiler warnings }
  2652. p_TargetReg := NR_NO;
  2653. if taicpu(p).oper[1]^.typ = top_reg then
  2654. begin
  2655. { Saves on a large number of dereferences }
  2656. p_TargetReg := taicpu(p).oper[1]^.reg;
  2657. { Look for:
  2658. mov %reg1,%reg2
  2659. ??? %reg2,r/m
  2660. Change to:
  2661. mov %reg1,%reg2
  2662. ??? %reg1,r/m
  2663. }
  2664. if taicpu(p).oper[0]^.typ = top_reg then
  2665. begin
  2666. if RegReadByInstruction(p_TargetReg, hp1) and
  2667. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2668. begin
  2669. { A change has occurred, just not in p }
  2670. Result := True;
  2671. TransferUsedRegs(TmpUsedRegs);
  2672. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2673. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2674. { Just in case something didn't get modified (e.g. an
  2675. implicit register) }
  2676. not RegReadByInstruction(p_TargetReg, hp1) then
  2677. begin
  2678. { We can remove the original MOV }
  2679. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2680. RemoveCurrentp(p, hp1);
  2681. { UsedRegs got updated by RemoveCurrentp }
  2682. Result := True;
  2683. Exit;
  2684. end;
  2685. { If we know a MOV instruction has become a null operation, we might as well
  2686. get rid of it now to save time. }
  2687. if (taicpu(hp1).opcode = A_MOV) and
  2688. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2689. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2690. { Just being a register is enough to confirm it's a null operation }
  2691. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2692. begin
  2693. Result := True;
  2694. { Speed-up to reduce a pipeline stall... if we had something like...
  2695. movl %eax,%edx
  2696. movw %dx,%ax
  2697. ... the second instruction would change to movw %ax,%ax, but
  2698. given that it is now %ax that's active rather than %eax,
  2699. penalties might occur due to a partial register write, so instead,
  2700. change it to a MOVZX instruction when optimising for speed.
  2701. }
  2702. if not (cs_opt_size in current_settings.optimizerswitches) and
  2703. IsMOVZXAcceptable and
  2704. (taicpu(hp1).opsize < taicpu(p).opsize)
  2705. {$ifdef x86_64}
  2706. { operations already implicitly set the upper 64 bits to zero }
  2707. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2708. {$endif x86_64}
  2709. then
  2710. begin
  2711. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2712. case taicpu(p).opsize of
  2713. S_W:
  2714. if taicpu(hp1).opsize = S_B then
  2715. taicpu(hp1).opsize := S_BL
  2716. else
  2717. InternalError(2020012911);
  2718. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2719. case taicpu(hp1).opsize of
  2720. S_B:
  2721. taicpu(hp1).opsize := S_BL;
  2722. S_W:
  2723. taicpu(hp1).opsize := S_WL;
  2724. else
  2725. InternalError(2020012912);
  2726. end;
  2727. else
  2728. InternalError(2020012910);
  2729. end;
  2730. taicpu(hp1).opcode := A_MOVZX;
  2731. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2732. end
  2733. else
  2734. begin
  2735. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2736. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2737. RemoveInstruction(hp1);
  2738. { The instruction after what was hp1 is now the immediate next instruction,
  2739. so we can continue to make optimisations if it's present }
  2740. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2741. Exit;
  2742. hp1 := hp2;
  2743. end;
  2744. end;
  2745. end;
  2746. end;
  2747. end;
  2748. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2749. overwrites the original destination register. e.g.
  2750. movl ###,%reg2d
  2751. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2752. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2753. }
  2754. if (taicpu(p).oper[1]^.typ = top_reg) and
  2755. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2756. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2757. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2758. begin
  2759. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2760. begin
  2761. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2762. case taicpu(p).oper[0]^.typ of
  2763. top_const:
  2764. { We have something like:
  2765. movb $x, %regb
  2766. movzbl %regb,%regd
  2767. Change to:
  2768. movl $x, %regd
  2769. }
  2770. begin
  2771. case taicpu(hp1).opsize of
  2772. S_BW:
  2773. begin
  2774. convert_mov_value(A_MOVSX, $FF);
  2775. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2776. taicpu(p).opsize := S_W;
  2777. end;
  2778. S_BL:
  2779. begin
  2780. convert_mov_value(A_MOVSX, $FF);
  2781. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2782. taicpu(p).opsize := S_L;
  2783. end;
  2784. S_WL:
  2785. begin
  2786. convert_mov_value(A_MOVSX, $FFFF);
  2787. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2788. taicpu(p).opsize := S_L;
  2789. end;
  2790. {$ifdef x86_64}
  2791. S_BQ:
  2792. begin
  2793. convert_mov_value(A_MOVSX, $FF);
  2794. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2795. taicpu(p).opsize := S_Q;
  2796. end;
  2797. S_WQ:
  2798. begin
  2799. convert_mov_value(A_MOVSX, $FFFF);
  2800. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2801. taicpu(p).opsize := S_Q;
  2802. end;
  2803. S_LQ:
  2804. begin
  2805. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2806. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2807. taicpu(p).opsize := S_Q;
  2808. end;
  2809. {$endif x86_64}
  2810. else
  2811. { If hp1 was a MOV instruction, it should have been
  2812. optimised already }
  2813. InternalError(2020021001);
  2814. end;
  2815. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2816. RemoveInstruction(hp1);
  2817. Result := True;
  2818. Exit;
  2819. end;
  2820. top_ref:
  2821. begin
  2822. { We have something like:
  2823. movb mem, %regb
  2824. movzbl %regb,%regd
  2825. Change to:
  2826. movzbl mem, %regd
  2827. }
  2828. ThisRef := taicpu(p).oper[0]^.ref^;
  2829. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2830. begin
  2831. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2832. taicpu(hp1).loadref(0, ThisRef);
  2833. { Make sure any registers in the references are properly tracked }
  2834. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2835. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2836. if (ThisRef.index <> NR_NO) then
  2837. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2838. RemoveCurrentP(p, hp1);
  2839. Result := True;
  2840. Exit;
  2841. end;
  2842. end;
  2843. else
  2844. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2845. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2846. Exit;
  2847. end;
  2848. end
  2849. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2850. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2851. optimised }
  2852. else
  2853. begin
  2854. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2855. RemoveCurrentP(p, hp1);
  2856. Result := True;
  2857. Exit;
  2858. end;
  2859. end;
  2860. if (taicpu(hp1).opcode = A_AND) and
  2861. (taicpu(p).oper[1]^.typ = top_reg) and
  2862. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2863. begin
  2864. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2865. begin
  2866. case taicpu(p).opsize of
  2867. S_L:
  2868. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2869. begin
  2870. { Optimize out:
  2871. mov x, %reg
  2872. and ffffffffh, %reg
  2873. }
  2874. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2875. RemoveInstruction(hp1);
  2876. Result:=true;
  2877. exit;
  2878. end;
  2879. S_Q: { TODO: Confirm if this is even possible }
  2880. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2881. begin
  2882. { Optimize out:
  2883. mov x, %reg
  2884. and ffffffffffffffffh, %reg
  2885. }
  2886. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2887. RemoveInstruction(hp1);
  2888. Result:=true;
  2889. exit;
  2890. end;
  2891. else
  2892. ;
  2893. end;
  2894. if (
  2895. (taicpu(p).oper[0]^.typ=top_reg) or
  2896. (
  2897. (taicpu(p).oper[0]^.typ=top_ref) and
  2898. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2899. )
  2900. ) and
  2901. GetNextInstruction(hp1,hp2) and
  2902. MatchInstruction(hp2,A_TEST,[]) and
  2903. (
  2904. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2905. (
  2906. { If the register being tested is smaller than the one
  2907. that received a bitwise AND, permit it if the constant
  2908. fits into the smaller size }
  2909. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2910. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2911. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2912. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2913. (
  2914. (
  2915. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2916. (taicpu(hp1).oper[0]^.val <= $FF)
  2917. ) or
  2918. (
  2919. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2920. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2921. {$ifdef x86_64}
  2922. ) or
  2923. (
  2924. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2925. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2926. {$endif x86_64}
  2927. )
  2928. )
  2929. )
  2930. ) and
  2931. (
  2932. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2933. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2934. ) and
  2935. GetNextInstruction(hp2,hp3) and
  2936. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2937. (taicpu(hp3).condition in [C_E,C_NE]) then
  2938. begin
  2939. TransferUsedRegs(TmpUsedRegs);
  2940. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2941. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2942. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2943. begin
  2944. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2945. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2946. taicpu(hp1).opcode:=A_TEST;
  2947. { Shrink the TEST instruction down to the smallest possible size }
  2948. case taicpu(hp1).oper[0]^.val of
  2949. 0..255:
  2950. if (taicpu(hp1).opsize <> S_B)
  2951. {$ifndef x86_64}
  2952. and (
  2953. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2954. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2955. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2956. )
  2957. {$endif x86_64}
  2958. then
  2959. begin
  2960. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2961. { Only print debug message if the TEST instruction
  2962. is a different size before and after }
  2963. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2964. taicpu(hp1).opsize := S_B;
  2965. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2966. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2967. end;
  2968. 256..65535:
  2969. if (taicpu(hp1).opsize <> S_W) then
  2970. begin
  2971. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2972. { Only print debug message if the TEST instruction
  2973. is a different size before and after }
  2974. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2975. taicpu(hp1).opsize := S_W;
  2976. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2977. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2978. end;
  2979. {$ifdef x86_64}
  2980. 65536..$7FFFFFFF:
  2981. if (taicpu(hp1).opsize <> S_L) then
  2982. begin
  2983. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2984. { Only print debug message if the TEST instruction
  2985. is a different size before and after }
  2986. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2987. taicpu(hp1).opsize := S_L;
  2988. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2989. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2990. end;
  2991. {$endif x86_64}
  2992. else
  2993. ;
  2994. end;
  2995. RemoveInstruction(hp2);
  2996. RemoveCurrentP(p, hp1);
  2997. Result:=true;
  2998. exit;
  2999. end;
  3000. end;
  3001. end
  3002. else if IsMOVZXAcceptable and
  3003. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3004. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3005. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3006. then
  3007. begin
  3008. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3009. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3010. case taicpu(p).opsize of
  3011. S_B:
  3012. if (taicpu(hp1).oper[0]^.val = $ff) then
  3013. begin
  3014. { Convert:
  3015. movb x, %regl movb x, %regl
  3016. andw ffh, %regw andl ffh, %regd
  3017. To:
  3018. movzbw x, %regd movzbl x, %regd
  3019. (Identical registers, just different sizes)
  3020. }
  3021. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3022. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3023. case taicpu(hp1).opsize of
  3024. S_W: NewSize := S_BW;
  3025. S_L: NewSize := S_BL;
  3026. {$ifdef x86_64}
  3027. S_Q: NewSize := S_BQ;
  3028. {$endif x86_64}
  3029. else
  3030. InternalError(2018011510);
  3031. end;
  3032. end
  3033. else
  3034. NewSize := S_NO;
  3035. S_W:
  3036. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3037. begin
  3038. { Convert:
  3039. movw x, %regw
  3040. andl ffffh, %regd
  3041. To:
  3042. movzwl x, %regd
  3043. (Identical registers, just different sizes)
  3044. }
  3045. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3046. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3047. case taicpu(hp1).opsize of
  3048. S_L: NewSize := S_WL;
  3049. {$ifdef x86_64}
  3050. S_Q: NewSize := S_WQ;
  3051. {$endif x86_64}
  3052. else
  3053. InternalError(2018011511);
  3054. end;
  3055. end
  3056. else
  3057. NewSize := S_NO;
  3058. else
  3059. NewSize := S_NO;
  3060. end;
  3061. if NewSize <> S_NO then
  3062. begin
  3063. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3064. { The actual optimization }
  3065. taicpu(p).opcode := A_MOVZX;
  3066. taicpu(p).changeopsize(NewSize);
  3067. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3068. { Safeguard if "and" is followed by a conditional command }
  3069. TransferUsedRegs(TmpUsedRegs);
  3070. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3071. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3072. begin
  3073. { At this point, the "and" command is effectively equivalent to
  3074. "test %reg,%reg". This will be handled separately by the
  3075. Peephole Optimizer. [Kit] }
  3076. DebugMsg(SPeepholeOptimization + PreMessage +
  3077. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3078. end
  3079. else
  3080. begin
  3081. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3082. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3083. RemoveInstruction(hp1);
  3084. end;
  3085. Result := True;
  3086. Exit;
  3087. end;
  3088. end;
  3089. end;
  3090. if (taicpu(hp1).opcode = A_OR) and
  3091. (taicpu(p).oper[1]^.typ = top_reg) and
  3092. MatchOperand(taicpu(p).oper[0]^, 0) and
  3093. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3094. begin
  3095. { mov 0, %reg
  3096. or ###,%reg
  3097. Change to (only if the flags are not used):
  3098. mov ###,%reg
  3099. }
  3100. TransferUsedRegs(TmpUsedRegs);
  3101. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3102. DoOptimisation := True;
  3103. { Even if the flags are used, we might be able to do the optimisation
  3104. if the conditions are predictable }
  3105. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3106. begin
  3107. { Only perform if ### = %reg (the same register) or equal to 0,
  3108. so %reg is guaranteed to still have a value of zero }
  3109. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3110. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3111. begin
  3112. hp2 := hp1;
  3113. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3114. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3115. GetNextInstruction(hp2, hp3) do
  3116. begin
  3117. { Don't continue modifying if the flags state is getting changed }
  3118. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3119. Break;
  3120. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3121. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3122. begin
  3123. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3124. begin
  3125. { Condition is always true }
  3126. case taicpu(hp3).opcode of
  3127. A_Jcc:
  3128. begin
  3129. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3130. { Check for jump shortcuts before we destroy the condition }
  3131. DoJumpOptimizations(hp3, TempBool);
  3132. MakeUnconditional(taicpu(hp3));
  3133. Result := True;
  3134. end;
  3135. A_CMOVcc:
  3136. begin
  3137. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3138. taicpu(hp3).opcode := A_MOV;
  3139. taicpu(hp3).condition := C_None;
  3140. Result := True;
  3141. end;
  3142. A_SETcc:
  3143. begin
  3144. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3145. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3146. taicpu(hp3).opcode := A_MOV;
  3147. taicpu(hp3).ops := 2;
  3148. taicpu(hp3).condition := C_None;
  3149. taicpu(hp3).opsize := S_B;
  3150. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3151. taicpu(hp3).loadconst(0, 1);
  3152. Result := True;
  3153. end;
  3154. else
  3155. InternalError(2021090701);
  3156. end;
  3157. end
  3158. 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
  3159. begin
  3160. { Condition is always false }
  3161. case taicpu(hp3).opcode of
  3162. A_Jcc:
  3163. begin
  3164. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3165. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3166. RemoveInstruction(hp3);
  3167. Result := True;
  3168. { Since hp3 was deleted, hp2 must not be updated }
  3169. Continue;
  3170. end;
  3171. A_CMOVcc:
  3172. begin
  3173. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3174. RemoveInstruction(hp3);
  3175. Result := True;
  3176. { Since hp3 was deleted, hp2 must not be updated }
  3177. Continue;
  3178. end;
  3179. A_SETcc:
  3180. begin
  3181. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3182. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3183. taicpu(hp3).opcode := A_MOV;
  3184. taicpu(hp3).ops := 2;
  3185. taicpu(hp3).condition := C_None;
  3186. taicpu(hp3).opsize := S_B;
  3187. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3188. taicpu(hp3).loadconst(0, 0);
  3189. Result := True;
  3190. end;
  3191. else
  3192. InternalError(2021090702);
  3193. end;
  3194. end
  3195. else
  3196. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3197. DoOptimisation := False;
  3198. end;
  3199. hp2 := hp3;
  3200. end;
  3201. { Flags are still in use - don't optimise }
  3202. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3203. DoOptimisation := False;
  3204. end
  3205. else
  3206. DoOptimisation := False;
  3207. end;
  3208. if DoOptimisation then
  3209. begin
  3210. {$ifdef x86_64}
  3211. { OR only supports 32-bit sign-extended constants for 64-bit
  3212. instructions, so compensate for this if the constant is
  3213. encoded as a value greater than or equal to 2^31 }
  3214. if (taicpu(hp1).opsize = S_Q) and
  3215. (taicpu(hp1).oper[0]^.typ = top_const) and
  3216. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3217. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3218. {$endif x86_64}
  3219. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3220. taicpu(hp1).opcode := A_MOV;
  3221. RemoveCurrentP(p, hp1);
  3222. Result := True;
  3223. Exit;
  3224. end;
  3225. end;
  3226. { Next instruction is also a MOV ? }
  3227. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3228. begin
  3229. if MatchOpType(taicpu(p), top_const, top_ref) and
  3230. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3231. TryConstMerge(p, hp1) then
  3232. begin
  3233. Result := True;
  3234. { In case we have four byte writes in a row, check for 2 more
  3235. right now so we don't have to wait for another iteration of
  3236. pass 1
  3237. }
  3238. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3239. case taicpu(p).opsize of
  3240. S_W:
  3241. begin
  3242. if GetNextInstruction(p, hp1) and
  3243. MatchInstruction(hp1, A_MOV, [S_B]) and
  3244. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3245. GetNextInstruction(hp1, hp2) and
  3246. MatchInstruction(hp2, A_MOV, [S_B]) and
  3247. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3248. { Try to merge the two bytes }
  3249. TryConstMerge(hp1, hp2) then
  3250. { Now try to merge the two words (hp2 will get deleted) }
  3251. TryConstMerge(p, hp1);
  3252. end;
  3253. S_L:
  3254. begin
  3255. { Though this only really benefits x86_64 and not i386, it
  3256. gets a potential optimisation done faster and hence
  3257. reduces the number of times OptPass1MOV is entered }
  3258. if GetNextInstruction(p, hp1) and
  3259. MatchInstruction(hp1, A_MOV, [S_W]) and
  3260. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3261. GetNextInstruction(hp1, hp2) and
  3262. MatchInstruction(hp2, A_MOV, [S_W]) and
  3263. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3264. { Try to merge the two words }
  3265. TryConstMerge(hp1, hp2) then
  3266. { This will always fail on i386, so don't bother
  3267. calling it unless we're doing x86_64 }
  3268. {$ifdef x86_64}
  3269. { Now try to merge the two longwords (hp2 will get deleted) }
  3270. TryConstMerge(p, hp1)
  3271. {$endif x86_64}
  3272. ;
  3273. end;
  3274. else
  3275. ;
  3276. end;
  3277. Exit;
  3278. end;
  3279. if (taicpu(p).oper[1]^.typ = top_reg) and
  3280. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3281. begin
  3282. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3283. TransferUsedRegs(TmpUsedRegs);
  3284. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3285. { we have
  3286. mov x, %treg
  3287. mov %treg, y
  3288. }
  3289. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3290. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3291. { we've got
  3292. mov x, %treg
  3293. mov %treg, y
  3294. with %treg is not used after }
  3295. case taicpu(p).oper[0]^.typ Of
  3296. { top_reg is covered by DeepMOVOpt }
  3297. top_const:
  3298. begin
  3299. { change
  3300. mov const, %treg
  3301. mov %treg, y
  3302. to
  3303. mov const, y
  3304. }
  3305. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3306. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3307. begin
  3308. if taicpu(hp1).oper[1]^.typ=top_reg then
  3309. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3310. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3311. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3312. RemoveInstruction(hp1);
  3313. Result:=true;
  3314. Exit;
  3315. end;
  3316. end;
  3317. top_ref:
  3318. case taicpu(hp1).oper[1]^.typ of
  3319. top_reg:
  3320. begin
  3321. { change
  3322. mov mem, %treg
  3323. mov %treg, %reg
  3324. to
  3325. mov mem, %reg"
  3326. }
  3327. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3328. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3329. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3330. RemoveInstruction(hp1);
  3331. Result:=true;
  3332. Exit;
  3333. end;
  3334. top_ref:
  3335. begin
  3336. {$ifdef x86_64}
  3337. { Look for the following to simplify:
  3338. mov x(mem1), %reg
  3339. mov %reg, y(mem2)
  3340. mov x+8(mem1), %reg
  3341. mov %reg, y+8(mem2)
  3342. Change to:
  3343. movdqu x(mem1), %xmmreg
  3344. movdqu %xmmreg, y(mem2)
  3345. ...but only as long as the memory blocks don't overlap
  3346. }
  3347. SourceRef := taicpu(p).oper[0]^.ref^;
  3348. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3349. if (taicpu(p).opsize = S_Q) and
  3350. GetNextInstruction(hp1, hp2) and
  3351. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3352. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3353. begin
  3354. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3355. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3356. Inc(SourceRef.offset, 8);
  3357. if UseAVX then
  3358. begin
  3359. MovAligned := A_VMOVDQA;
  3360. MovUnaligned := A_VMOVDQU;
  3361. end
  3362. else
  3363. begin
  3364. MovAligned := A_MOVDQA;
  3365. MovUnaligned := A_MOVDQU;
  3366. end;
  3367. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3368. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3369. begin
  3370. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3371. Inc(TargetRef.offset, 8);
  3372. if GetNextInstruction(hp2, hp3) and
  3373. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3374. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3375. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3376. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3377. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3378. begin
  3379. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3380. if NewMMReg <> NR_NO then
  3381. begin
  3382. { Remember that the offsets are 8 ahead }
  3383. if ((SourceRef.offset mod 16) = 8) and
  3384. (
  3385. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3386. (SourceRef.base = current_procinfo.framepointer) or
  3387. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3388. ) then
  3389. taicpu(p).opcode := MovAligned
  3390. else
  3391. taicpu(p).opcode := MovUnaligned;
  3392. taicpu(p).opsize := S_XMM;
  3393. taicpu(p).oper[1]^.reg := NewMMReg;
  3394. if ((TargetRef.offset mod 16) = 8) and
  3395. (
  3396. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3397. (TargetRef.base = current_procinfo.framepointer) or
  3398. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3399. ) then
  3400. taicpu(hp1).opcode := MovAligned
  3401. else
  3402. taicpu(hp1).opcode := MovUnaligned;
  3403. taicpu(hp1).opsize := S_XMM;
  3404. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3405. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3406. RemoveInstruction(hp2);
  3407. RemoveInstruction(hp3);
  3408. Result := True;
  3409. Exit;
  3410. end;
  3411. end;
  3412. end
  3413. else
  3414. begin
  3415. { See if the next references are 8 less rather than 8 greater }
  3416. Dec(SourceRef.offset, 16); { -8 the other way }
  3417. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3418. begin
  3419. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3420. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3421. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3422. GetNextInstruction(hp2, hp3) and
  3423. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3424. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3425. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3426. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3427. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3428. begin
  3429. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3430. if NewMMReg <> NR_NO then
  3431. begin
  3432. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3433. if ((SourceRef.offset mod 16) = 0) and
  3434. (
  3435. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3436. (SourceRef.base = current_procinfo.framepointer) or
  3437. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3438. ) then
  3439. taicpu(hp2).opcode := MovAligned
  3440. else
  3441. taicpu(hp2).opcode := MovUnaligned;
  3442. taicpu(hp2).opsize := S_XMM;
  3443. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3444. if ((TargetRef.offset mod 16) = 0) and
  3445. (
  3446. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3447. (TargetRef.base = current_procinfo.framepointer) or
  3448. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3449. ) then
  3450. taicpu(hp3).opcode := MovAligned
  3451. else
  3452. taicpu(hp3).opcode := MovUnaligned;
  3453. taicpu(hp3).opsize := S_XMM;
  3454. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3455. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3456. RemoveInstruction(hp1);
  3457. RemoveCurrentP(p, hp2);
  3458. Result := True;
  3459. Exit;
  3460. end;
  3461. end;
  3462. end;
  3463. end;
  3464. end;
  3465. {$endif x86_64}
  3466. end;
  3467. else
  3468. { The write target should be a reg or a ref }
  3469. InternalError(2021091601);
  3470. end;
  3471. else
  3472. ;
  3473. end
  3474. else
  3475. { %treg is used afterwards, but all eventualities
  3476. other than the first MOV instruction being a constant
  3477. are covered by DeepMOVOpt, so only check for that }
  3478. if (taicpu(p).oper[0]^.typ = top_const) and
  3479. (
  3480. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3481. not (cs_opt_size in current_settings.optimizerswitches) or
  3482. (taicpu(hp1).opsize = S_B)
  3483. ) and
  3484. (
  3485. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3486. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3487. ) then
  3488. begin
  3489. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3490. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3491. end;
  3492. end;
  3493. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3494. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3495. { mov reg1, mem1 or mov mem1, reg1
  3496. mov mem2, reg2 mov reg2, mem2}
  3497. begin
  3498. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3499. { mov reg1, mem1 or mov mem1, reg1
  3500. mov mem2, reg1 mov reg2, mem1}
  3501. begin
  3502. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3503. { Removes the second statement from
  3504. mov reg1, mem1/reg2
  3505. mov mem1/reg2, reg1 }
  3506. begin
  3507. if taicpu(p).oper[0]^.typ=top_reg then
  3508. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3509. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3510. RemoveInstruction(hp1);
  3511. Result:=true;
  3512. exit;
  3513. end
  3514. else
  3515. begin
  3516. TransferUsedRegs(TmpUsedRegs);
  3517. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3518. if (taicpu(p).oper[1]^.typ = top_ref) and
  3519. { mov reg1, mem1
  3520. mov mem2, reg1 }
  3521. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3522. GetNextInstruction(hp1, hp2) and
  3523. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3524. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3525. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3526. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3527. { change to
  3528. mov reg1, mem1 mov reg1, mem1
  3529. mov mem2, reg1 cmp reg1, mem2
  3530. cmp mem1, reg1
  3531. }
  3532. begin
  3533. RemoveInstruction(hp2);
  3534. taicpu(hp1).opcode := A_CMP;
  3535. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3536. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3537. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3538. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3539. end;
  3540. end;
  3541. end
  3542. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3543. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3544. begin
  3545. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3546. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3547. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3548. end
  3549. else
  3550. begin
  3551. TransferUsedRegs(TmpUsedRegs);
  3552. if GetNextInstruction(hp1, hp2) and
  3553. MatchOpType(taicpu(p),top_ref,top_reg) and
  3554. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3555. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3556. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3557. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3558. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3559. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3560. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3561. { mov mem1, %reg1
  3562. mov %reg1, mem2
  3563. mov mem2, reg2
  3564. to:
  3565. mov mem1, reg2
  3566. mov reg2, mem2}
  3567. begin
  3568. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3569. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3570. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3571. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3572. RemoveInstruction(hp2);
  3573. Result := True;
  3574. end
  3575. {$ifdef i386}
  3576. { this is enabled for i386 only, as the rules to create the reg sets below
  3577. are too complicated for x86-64, so this makes this code too error prone
  3578. on x86-64
  3579. }
  3580. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3581. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3582. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3583. { mov mem1, reg1 mov mem1, reg1
  3584. mov reg1, mem2 mov reg1, mem2
  3585. mov mem2, reg2 mov mem2, reg1
  3586. to: to:
  3587. mov mem1, reg1 mov mem1, reg1
  3588. mov mem1, reg2 mov reg1, mem2
  3589. mov reg1, mem2
  3590. or (if mem1 depends on reg1
  3591. and/or if mem2 depends on reg2)
  3592. to:
  3593. mov mem1, reg1
  3594. mov reg1, mem2
  3595. mov reg1, reg2
  3596. }
  3597. begin
  3598. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3599. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3600. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3601. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3602. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3603. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3604. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3605. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3606. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3607. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3608. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3609. end
  3610. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3611. begin
  3612. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3613. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3614. end
  3615. else
  3616. begin
  3617. RemoveInstruction(hp2);
  3618. end
  3619. {$endif i386}
  3620. ;
  3621. end;
  3622. end
  3623. { movl [mem1],reg1
  3624. movl [mem1],reg2
  3625. to
  3626. movl [mem1],reg1
  3627. movl reg1,reg2
  3628. }
  3629. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3630. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3631. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3632. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3633. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3634. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3635. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3636. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3637. begin
  3638. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3639. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3640. end;
  3641. { movl const1,[mem1]
  3642. movl [mem1],reg1
  3643. to
  3644. movl const1,reg1
  3645. movl reg1,[mem1]
  3646. }
  3647. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3648. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3649. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3650. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3651. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3652. begin
  3653. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3654. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3655. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3656. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3657. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3658. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3659. Result:=true;
  3660. exit;
  3661. end;
  3662. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3663. { Change:
  3664. movl %reg1,%reg2
  3665. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3666. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3667. To:
  3668. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3669. movl x(%reg1),%reg1
  3670. movl %reg1,%regX
  3671. }
  3672. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3673. begin
  3674. p_SourceReg := taicpu(p).oper[0]^.reg;
  3675. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3676. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3677. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3678. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3679. GetNextInstruction(hp1, hp2) and
  3680. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3681. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3682. begin
  3683. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3684. if RegInRef(p_TargetReg, SourceRef) and
  3685. { If %reg1 also appears in the second reference, then it will
  3686. not refer to the same memory block as the first reference }
  3687. not RegInRef(p_SourceReg, SourceRef) then
  3688. begin
  3689. { Check to see if the references match if %reg2 is changed to %reg1 }
  3690. if SourceRef.base = p_TargetReg then
  3691. SourceRef.base := p_SourceReg;
  3692. if SourceRef.index = p_TargetReg then
  3693. SourceRef.index := p_SourceReg;
  3694. { RefsEqual also checks to ensure both references are non-volatile }
  3695. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3696. begin
  3697. taicpu(hp2).loadreg(0, p_SourceReg);
  3698. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3699. Result := True;
  3700. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3701. begin
  3702. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3703. RemoveCurrentP(p, hp1);
  3704. Exit;
  3705. end
  3706. else
  3707. begin
  3708. { Check to see if %reg2 is no longer in use }
  3709. TransferUsedRegs(TmpUsedRegs);
  3710. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3711. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3712. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3713. begin
  3714. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3715. RemoveCurrentP(p, hp1);
  3716. Exit;
  3717. end;
  3718. end;
  3719. { If we reach this point, p and hp1 weren't actually modified,
  3720. so we can do a bit more work on this pass }
  3721. end;
  3722. end;
  3723. end;
  3724. end;
  3725. end;
  3726. { search further than the next instruction for a mov (as long as it's not a jump) }
  3727. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3728. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3729. (taicpu(p).oper[1]^.typ = top_reg) and
  3730. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3731. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3732. begin
  3733. { we work with hp2 here, so hp1 can be still used later on when
  3734. checking for GetNextInstruction_p }
  3735. hp3 := hp1;
  3736. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3737. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3738. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3739. TransferUsedRegs(TmpUsedRegs);
  3740. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3741. if NotFirstIteration then
  3742. JumpTracking := TLinkedList.Create
  3743. else
  3744. JumpTracking := nil;
  3745. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3746. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3747. (hp2.typ=ait_instruction) do
  3748. begin
  3749. case taicpu(hp2).opcode of
  3750. A_POP:
  3751. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3752. begin
  3753. if not CrossJump and
  3754. not RegUsedBetween(p_TargetReg, p, hp2) then
  3755. begin
  3756. { We can remove the original MOV since the register
  3757. wasn't used between it and its popping from the stack }
  3758. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3759. RemoveCurrentp(p, hp1);
  3760. Result := True;
  3761. JumpTracking.Free;
  3762. Exit;
  3763. end;
  3764. { Can't go any further }
  3765. Break;
  3766. end;
  3767. A_MOV:
  3768. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3769. ((taicpu(p).oper[0]^.typ=top_const) or
  3770. ((taicpu(p).oper[0]^.typ=top_reg) and
  3771. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3772. )
  3773. ) then
  3774. begin
  3775. { we have
  3776. mov x, %treg
  3777. mov %treg, y
  3778. }
  3779. { We don't need to call UpdateUsedRegs for every instruction between
  3780. p and hp2 because the register we're concerned about will not
  3781. become deallocated (otherwise GetNextInstructionUsingReg would
  3782. have stopped at an earlier instruction). [Kit] }
  3783. TempRegUsed :=
  3784. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3785. RegReadByInstruction(p_TargetReg, hp3) or
  3786. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3787. case taicpu(p).oper[0]^.typ Of
  3788. top_reg:
  3789. begin
  3790. { change
  3791. mov %reg, %treg
  3792. mov %treg, y
  3793. to
  3794. mov %reg, y
  3795. }
  3796. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3797. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3798. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3799. begin
  3800. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3801. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3802. if TempRegUsed then
  3803. begin
  3804. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3805. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3806. { Set the start of the next GetNextInstructionUsingRegCond search
  3807. to start at the entry right before hp2 (which is about to be removed) }
  3808. hp3 := tai(hp2.Previous);
  3809. RemoveInstruction(hp2);
  3810. { See if there's more we can optimise }
  3811. Continue;
  3812. end
  3813. else
  3814. begin
  3815. RemoveInstruction(hp2);
  3816. { We can remove the original MOV too }
  3817. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3818. RemoveCurrentP(p, hp1);
  3819. Result:=true;
  3820. JumpTracking.Free;
  3821. Exit;
  3822. end;
  3823. end
  3824. else
  3825. begin
  3826. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3827. taicpu(hp2).loadReg(0, p_SourceReg);
  3828. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3829. { Check to see if the register also appears in the reference }
  3830. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3831. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3832. { Don't remove the first instruction if the temporary register is in use }
  3833. if not TempRegUsed and
  3834. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3835. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3836. begin
  3837. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3838. RemoveCurrentP(p, hp1);
  3839. Result:=true;
  3840. JumpTracking.Free;
  3841. Exit;
  3842. end;
  3843. { No need to set Result to True here. If there's another instruction later
  3844. on that can be optimised, it will be detected when the main Pass 1 loop
  3845. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3846. end;
  3847. end;
  3848. top_const:
  3849. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3850. begin
  3851. { change
  3852. mov const, %treg
  3853. mov %treg, y
  3854. to
  3855. mov const, y
  3856. }
  3857. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3858. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3859. begin
  3860. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3861. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3862. if TempRegUsed then
  3863. begin
  3864. { Don't remove the first instruction if the temporary register is in use }
  3865. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3866. { No need to set Result to True. If there's another instruction later on
  3867. that can be optimised, it will be detected when the main Pass 1 loop
  3868. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3869. end
  3870. else
  3871. begin
  3872. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3873. RemoveCurrentP(p, hp1);
  3874. Result:=true;
  3875. Exit;
  3876. end;
  3877. end;
  3878. end;
  3879. else
  3880. Internalerror(2019103001);
  3881. end;
  3882. end
  3883. else
  3884. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3885. begin
  3886. if not CrossJump and
  3887. not RegUsedBetween(p_TargetReg, p, hp2) and
  3888. not RegReadByInstruction(p_TargetReg, hp2) then
  3889. begin
  3890. { Register is not used before it is overwritten }
  3891. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3892. RemoveCurrentp(p, hp1);
  3893. Result := True;
  3894. Exit;
  3895. end;
  3896. if (taicpu(p).oper[0]^.typ = top_const) and
  3897. (taicpu(hp2).oper[0]^.typ = top_const) then
  3898. begin
  3899. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3900. begin
  3901. { Same value - register hasn't changed }
  3902. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3903. RemoveInstruction(hp2);
  3904. Result := True;
  3905. { See if there's more we can optimise }
  3906. Continue;
  3907. end;
  3908. end;
  3909. end;
  3910. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3911. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3912. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3913. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3914. begin
  3915. {
  3916. Change from:
  3917. mov ###, %reg
  3918. ...
  3919. movs/z %reg,%reg (Same register, just different sizes)
  3920. To:
  3921. movs/z ###, %reg (Longer version)
  3922. ...
  3923. (remove)
  3924. }
  3925. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3926. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3927. { Keep the first instruction as mov if ### is a constant }
  3928. if taicpu(p).oper[0]^.typ = top_const then
  3929. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3930. else
  3931. begin
  3932. taicpu(p).opcode := taicpu(hp2).opcode;
  3933. taicpu(p).opsize := taicpu(hp2).opsize;
  3934. end;
  3935. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3936. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3937. RemoveInstruction(hp2);
  3938. Result := True;
  3939. JumpTracking.Free;
  3940. Exit;
  3941. end;
  3942. else
  3943. { Move down to the MatchOpType if-block below };
  3944. end;
  3945. { Also catches MOV/S/Z instructions that aren't modified }
  3946. if taicpu(p).oper[0]^.typ = top_reg then
  3947. begin
  3948. p_SourceReg := taicpu(p).oper[0]^.reg;
  3949. if
  3950. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3951. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3952. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3953. begin
  3954. Result := True;
  3955. { Just in case something didn't get modified (e.g. an
  3956. implicit register). Also, if it does read from this
  3957. register, then there's no longer an advantage to
  3958. changing the register on subsequent instructions.}
  3959. if not RegReadByInstruction(p_TargetReg, hp2) then
  3960. begin
  3961. { If a conditional jump was crossed, do not delete
  3962. the original MOV no matter what }
  3963. if not CrossJump and
  3964. { RegEndOfLife returns True if the register is
  3965. deallocated before the next instruction or has
  3966. been loaded with a new value }
  3967. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3968. begin
  3969. { We can remove the original MOV }
  3970. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3971. RemoveCurrentp(p, hp1);
  3972. JumpTracking.Free;
  3973. Result := True;
  3974. Exit;
  3975. end;
  3976. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3977. begin
  3978. { See if there's more we can optimise }
  3979. hp3 := hp2;
  3980. Continue;
  3981. end;
  3982. end;
  3983. end;
  3984. end;
  3985. { Break out of the while loop under normal circumstances }
  3986. Break;
  3987. end;
  3988. JumpTracking.Free;
  3989. end;
  3990. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3991. (taicpu(p).oper[1]^.typ = top_reg) and
  3992. (taicpu(p).opsize = S_L) and
  3993. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3994. (hp2.typ = ait_instruction) and
  3995. (taicpu(hp2).opcode = A_AND) and
  3996. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3997. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3998. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3999. ) then
  4000. begin
  4001. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4002. begin
  4003. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4004. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4005. begin
  4006. { Optimize out:
  4007. mov x, %reg
  4008. and ffffffffh, %reg
  4009. }
  4010. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4011. RemoveInstruction(hp2);
  4012. Result:=true;
  4013. exit;
  4014. end;
  4015. end;
  4016. end;
  4017. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4018. x >= RetOffset) as it doesn't do anything (it writes either to a
  4019. parameter or to the temporary storage room for the function
  4020. result)
  4021. }
  4022. if IsExitCode(hp1) and
  4023. (taicpu(p).oper[1]^.typ = top_ref) and
  4024. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4025. (
  4026. (
  4027. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4028. not (
  4029. assigned(current_procinfo.procdef.funcretsym) and
  4030. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4031. )
  4032. ) or
  4033. { Also discard writes to the stack that are below the base pointer,
  4034. as this is temporary storage rather than a function result on the
  4035. stack, say. }
  4036. (
  4037. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4038. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4039. )
  4040. ) then
  4041. begin
  4042. RemoveCurrentp(p, hp1);
  4043. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4044. RemoveLastDeallocForFuncRes(p);
  4045. Result:=true;
  4046. exit;
  4047. end;
  4048. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4049. begin
  4050. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4051. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4052. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4053. begin
  4054. { change
  4055. mov reg1, mem1
  4056. test/cmp x, mem1
  4057. to
  4058. mov reg1, mem1
  4059. test/cmp x, reg1
  4060. }
  4061. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4062. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4063. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4064. Result := True;
  4065. Exit;
  4066. end;
  4067. if DoMovCmpMemOpt(p, hp1, True) then
  4068. begin
  4069. Result := True;
  4070. Exit;
  4071. end;
  4072. end;
  4073. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4074. { If the flags register is in use, don't change the instruction to an
  4075. ADD otherwise this will scramble the flags. [Kit] }
  4076. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4077. begin
  4078. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4079. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4080. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4081. ) or
  4082. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4083. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4084. )
  4085. ) then
  4086. { mov reg1,ref
  4087. lea reg2,[reg1,reg2]
  4088. to
  4089. add reg2,ref}
  4090. begin
  4091. TransferUsedRegs(TmpUsedRegs);
  4092. { reg1 may not be used afterwards }
  4093. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4094. begin
  4095. Taicpu(hp1).opcode:=A_ADD;
  4096. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4097. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4098. RemoveCurrentp(p, hp1);
  4099. result:=true;
  4100. exit;
  4101. end;
  4102. end;
  4103. { If the LEA instruction can be converted into an arithmetic instruction,
  4104. it may be possible to then fold it in the next optimisation, otherwise
  4105. there's nothing more that can be optimised here. }
  4106. if not ConvertLEA(taicpu(hp1)) then
  4107. Exit;
  4108. end;
  4109. if (taicpu(p).oper[1]^.typ = top_reg) and
  4110. (hp1.typ = ait_instruction) and
  4111. GetNextInstruction(hp1, hp2) and
  4112. MatchInstruction(hp2,A_MOV,[]) and
  4113. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4114. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4115. (
  4116. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4117. {$ifdef x86_64}
  4118. or
  4119. (
  4120. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4121. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4122. )
  4123. {$endif x86_64}
  4124. ) then
  4125. begin
  4126. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4127. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4128. { change movsX/movzX reg/ref, reg2
  4129. add/sub/or/... reg3/$const, reg2
  4130. mov reg2 reg/ref
  4131. dealloc reg2
  4132. to
  4133. add/sub/or/... reg3/$const, reg/ref }
  4134. begin
  4135. TransferUsedRegs(TmpUsedRegs);
  4136. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4137. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4138. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4139. begin
  4140. { by example:
  4141. movswl %si,%eax movswl %si,%eax p
  4142. decl %eax addl %edx,%eax hp1
  4143. movw %ax,%si movw %ax,%si hp2
  4144. ->
  4145. movswl %si,%eax movswl %si,%eax p
  4146. decw %eax addw %edx,%eax hp1
  4147. movw %ax,%si movw %ax,%si hp2
  4148. }
  4149. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4150. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4151. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4152. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4153. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4154. {
  4155. ->
  4156. movswl %si,%eax movswl %si,%eax p
  4157. decw %si addw %dx,%si hp1
  4158. movw %ax,%si movw %ax,%si hp2
  4159. }
  4160. case taicpu(hp1).ops of
  4161. 1:
  4162. begin
  4163. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4164. if taicpu(hp1).oper[0]^.typ=top_reg then
  4165. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4166. end;
  4167. 2:
  4168. begin
  4169. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4170. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4171. (taicpu(hp1).opcode<>A_SHL) and
  4172. (taicpu(hp1).opcode<>A_SHR) and
  4173. (taicpu(hp1).opcode<>A_SAR) then
  4174. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4175. end;
  4176. else
  4177. internalerror(2008042701);
  4178. end;
  4179. {
  4180. ->
  4181. decw %si addw %dx,%si p
  4182. }
  4183. RemoveInstruction(hp2);
  4184. RemoveCurrentP(p, hp1);
  4185. Result:=True;
  4186. Exit;
  4187. end;
  4188. end;
  4189. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4190. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4191. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4192. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4193. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4194. )
  4195. {$ifdef i386}
  4196. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4197. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4198. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4199. {$endif i386}
  4200. then
  4201. { change movsX/movzX reg/ref, reg2
  4202. add/sub/or/... regX/$const, reg2
  4203. mov reg2, reg3
  4204. dealloc reg2
  4205. to
  4206. movsX/movzX reg/ref, reg3
  4207. add/sub/or/... reg3/$const, reg3
  4208. }
  4209. begin
  4210. TransferUsedRegs(TmpUsedRegs);
  4211. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4212. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4213. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4214. begin
  4215. { by example:
  4216. movswl %si,%eax movswl %si,%eax p
  4217. decl %eax addl %edx,%eax hp1
  4218. movw %ax,%si movw %ax,%si hp2
  4219. ->
  4220. movswl %si,%eax movswl %si,%eax p
  4221. decw %eax addw %edx,%eax hp1
  4222. movw %ax,%si movw %ax,%si hp2
  4223. }
  4224. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4225. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4226. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4227. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4228. { limit size of constants as well to avoid assembler errors, but
  4229. check opsize to avoid overflow when left shifting the 1 }
  4230. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4231. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4232. {$ifdef x86_64}
  4233. { Be careful of, for example:
  4234. movl %reg1,%reg2
  4235. addl %reg3,%reg2
  4236. movq %reg2,%reg4
  4237. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4238. }
  4239. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4240. begin
  4241. taicpu(hp2).changeopsize(S_L);
  4242. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4243. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4244. end;
  4245. {$endif x86_64}
  4246. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4247. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4248. if taicpu(p).oper[0]^.typ=top_reg then
  4249. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4250. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4251. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4252. {
  4253. ->
  4254. movswl %si,%eax movswl %si,%eax p
  4255. decw %si addw %dx,%si hp1
  4256. movw %ax,%si movw %ax,%si hp2
  4257. }
  4258. case taicpu(hp1).ops of
  4259. 1:
  4260. begin
  4261. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4262. if taicpu(hp1).oper[0]^.typ=top_reg then
  4263. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4264. end;
  4265. 2:
  4266. begin
  4267. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4268. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4269. (taicpu(hp1).opcode<>A_SHL) and
  4270. (taicpu(hp1).opcode<>A_SHR) and
  4271. (taicpu(hp1).opcode<>A_SAR) then
  4272. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4273. end;
  4274. else
  4275. internalerror(2018111801);
  4276. end;
  4277. {
  4278. ->
  4279. decw %si addw %dx,%si p
  4280. }
  4281. RemoveInstruction(hp2);
  4282. end;
  4283. end;
  4284. end;
  4285. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4286. GetNextInstruction(hp1, hp2) and
  4287. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4288. MatchOperand(Taicpu(p).oper[0]^,0) and
  4289. (Taicpu(p).oper[1]^.typ = top_reg) and
  4290. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4291. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4292. { mov reg1,0
  4293. bts reg1,operand1 --> mov reg1,operand2
  4294. or reg1,operand2 bts reg1,operand1}
  4295. begin
  4296. Taicpu(hp2).opcode:=A_MOV;
  4297. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4298. asml.remove(hp1);
  4299. insertllitem(hp2,hp2.next,hp1);
  4300. RemoveCurrentp(p, hp1);
  4301. Result:=true;
  4302. exit;
  4303. end;
  4304. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4305. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4306. GetNextInstruction(hp1, hp2) and
  4307. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4308. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4309. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4310. { change
  4311. mov reg1,reg2
  4312. sub reg3,reg2
  4313. cmp reg3,reg1
  4314. into
  4315. mov reg1,reg2
  4316. sub reg3,reg2
  4317. }
  4318. begin
  4319. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4320. RemoveInstruction(hp2);
  4321. Result:=true;
  4322. exit;
  4323. end;
  4324. {
  4325. mov ref,reg0
  4326. <op> reg0,reg1
  4327. dealloc reg0
  4328. to
  4329. <op> ref,reg1
  4330. }
  4331. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4332. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4333. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4334. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4335. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4336. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4337. begin
  4338. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4339. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4340. RemoveCurrentp(p, hp1);
  4341. Result:=true;
  4342. exit;
  4343. end;
  4344. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4345. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4346. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4347. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4348. begin
  4349. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4350. {$ifdef x86_64}
  4351. { Convert:
  4352. movq x(ref),%reg64
  4353. shrq y,%reg64
  4354. To:
  4355. movl x+4(ref),%reg32
  4356. shrl y-32,%reg32 (Remove if y = 32)
  4357. }
  4358. if (taicpu(p).opsize = S_Q) and
  4359. (taicpu(hp1).opcode = A_SHR) and
  4360. (taicpu(hp1).oper[0]^.val >= 32) then
  4361. begin
  4362. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4363. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4364. { Convert to 32-bit }
  4365. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4366. taicpu(p).opsize := S_L;
  4367. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4368. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4369. if (taicpu(hp1).oper[0]^.val = 32) then
  4370. begin
  4371. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4372. RemoveInstruction(hp1);
  4373. end
  4374. else
  4375. begin
  4376. { This will potentially open up more arithmetic operations since
  4377. the peephole optimizer now has a big hint that only the lower
  4378. 32 bits are currently in use (and opcodes are smaller in size) }
  4379. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4380. taicpu(hp1).opsize := S_L;
  4381. Dec(taicpu(hp1).oper[0]^.val, 32);
  4382. DebugMsg(SPeepholeOptimization + PreMessage +
  4383. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4384. end;
  4385. Result := True;
  4386. Exit;
  4387. end;
  4388. {$endif x86_64}
  4389. { Convert:
  4390. movl x(ref),%reg
  4391. shrl $24,%reg
  4392. To:
  4393. movzbl x+3(ref),%reg
  4394. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4395. Also accept sar instead of shr, but convert to movsx instead of movzx
  4396. }
  4397. if taicpu(hp1).opcode = A_SHR then
  4398. MovUnaligned := A_MOVZX
  4399. else
  4400. MovUnaligned := A_MOVSX;
  4401. NewSize := S_NO;
  4402. NewOffset := 0;
  4403. case taicpu(p).opsize of
  4404. S_B:
  4405. { No valid combinations };
  4406. S_W:
  4407. if (taicpu(hp1).oper[0]^.val = 8) then
  4408. begin
  4409. NewSize := S_BW;
  4410. NewOffset := 1;
  4411. end;
  4412. S_L:
  4413. case taicpu(hp1).oper[0]^.val of
  4414. 16:
  4415. begin
  4416. NewSize := S_WL;
  4417. NewOffset := 2;
  4418. end;
  4419. 24:
  4420. begin
  4421. NewSize := S_BL;
  4422. NewOffset := 3;
  4423. end;
  4424. else
  4425. ;
  4426. end;
  4427. {$ifdef x86_64}
  4428. S_Q:
  4429. case taicpu(hp1).oper[0]^.val of
  4430. 32:
  4431. begin
  4432. if taicpu(hp1).opcode = A_SAR then
  4433. begin
  4434. { 32-bit to 64-bit is a distinct instruction }
  4435. MovUnaligned := A_MOVSXD;
  4436. NewSize := S_LQ;
  4437. NewOffset := 4;
  4438. end
  4439. else
  4440. { Should have been handled by MovShr2Mov above }
  4441. InternalError(2022081811);
  4442. end;
  4443. 48:
  4444. begin
  4445. NewSize := S_WQ;
  4446. NewOffset := 6;
  4447. end;
  4448. 56:
  4449. begin
  4450. NewSize := S_BQ;
  4451. NewOffset := 7;
  4452. end;
  4453. else
  4454. ;
  4455. end;
  4456. {$endif x86_64}
  4457. else
  4458. InternalError(2022081810);
  4459. end;
  4460. if (NewSize <> S_NO) and
  4461. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4462. begin
  4463. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4464. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4465. debug_op2str(MovUnaligned);
  4466. {$ifdef x86_64}
  4467. if MovUnaligned <> A_MOVSXD then
  4468. { Don't add size suffix for MOVSXD }
  4469. {$endif x86_64}
  4470. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4471. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4472. taicpu(p).opcode := MovUnaligned;
  4473. taicpu(p).opsize := NewSize;
  4474. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4475. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4476. RemoveInstruction(hp1);
  4477. Result := True;
  4478. Exit;
  4479. end;
  4480. end;
  4481. { Backward optimisation shared with OptPass2MOV }
  4482. if FuncMov2Func(p, hp1) then
  4483. begin
  4484. Result := True;
  4485. Exit;
  4486. end;
  4487. end;
  4488. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4489. var
  4490. hp1 : tai;
  4491. begin
  4492. Result:=false;
  4493. if taicpu(p).ops <> 2 then
  4494. exit;
  4495. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4496. GetNextInstruction(p,hp1) then
  4497. begin
  4498. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4499. (taicpu(hp1).ops = 2) then
  4500. begin
  4501. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4502. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4503. { movXX reg1, mem1 or movXX mem1, reg1
  4504. movXX mem2, reg2 movXX reg2, mem2}
  4505. begin
  4506. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4507. { movXX reg1, mem1 or movXX mem1, reg1
  4508. movXX mem2, reg1 movXX reg2, mem1}
  4509. begin
  4510. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4511. begin
  4512. { Removes the second statement from
  4513. movXX reg1, mem1/reg2
  4514. movXX mem1/reg2, reg1
  4515. }
  4516. if taicpu(p).oper[0]^.typ=top_reg then
  4517. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4518. { Removes the second statement from
  4519. movXX mem1/reg1, reg2
  4520. movXX reg2, mem1/reg1
  4521. }
  4522. if (taicpu(p).oper[1]^.typ=top_reg) and
  4523. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4524. begin
  4525. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4526. RemoveInstruction(hp1);
  4527. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4528. Result:=true;
  4529. exit;
  4530. end
  4531. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4532. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4533. begin
  4534. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4535. RemoveInstruction(hp1);
  4536. Result:=true;
  4537. exit;
  4538. end;
  4539. end
  4540. end;
  4541. end;
  4542. end;
  4543. end;
  4544. end;
  4545. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4546. var
  4547. hp1 : tai;
  4548. begin
  4549. result:=false;
  4550. { replace
  4551. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4552. MovX %mreg2,%mreg1
  4553. dealloc %mreg2
  4554. by
  4555. <Op>X %mreg2,%mreg1
  4556. ?
  4557. }
  4558. if GetNextInstruction(p,hp1) and
  4559. { we mix single and double opperations here because we assume that the compiler
  4560. generates vmovapd only after double operations and vmovaps only after single operations }
  4561. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4562. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4563. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4564. (taicpu(p).oper[0]^.typ=top_reg) then
  4565. begin
  4566. TransferUsedRegs(TmpUsedRegs);
  4567. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4568. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4569. begin
  4570. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4571. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4572. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4573. RemoveInstruction(hp1);
  4574. result:=true;
  4575. end;
  4576. end;
  4577. end;
  4578. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4579. var
  4580. hp1, p_label, p_dist, hp1_dist: tai;
  4581. JumpLabel, JumpLabel_dist: TAsmLabel;
  4582. FirstValue, SecondValue: TCGInt;
  4583. begin
  4584. Result := False;
  4585. if (taicpu(p).oper[0]^.typ = top_const) and
  4586. (taicpu(p).oper[0]^.val <> -1) then
  4587. begin
  4588. { Convert unsigned maximum constants to -1 to aid optimisation }
  4589. case taicpu(p).opsize of
  4590. S_B:
  4591. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4592. begin
  4593. taicpu(p).oper[0]^.val := -1;
  4594. Result := True;
  4595. Exit;
  4596. end;
  4597. S_W:
  4598. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4599. begin
  4600. taicpu(p).oper[0]^.val := -1;
  4601. Result := True;
  4602. Exit;
  4603. end;
  4604. S_L:
  4605. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4606. begin
  4607. taicpu(p).oper[0]^.val := -1;
  4608. Result := True;
  4609. Exit;
  4610. end;
  4611. {$ifdef x86_64}
  4612. S_Q:
  4613. { Storing anything greater than $7FFFFFFF is not possible so do
  4614. nothing };
  4615. {$endif x86_64}
  4616. else
  4617. InternalError(2021121001);
  4618. end;
  4619. end;
  4620. if GetNextInstruction(p, hp1) and
  4621. TrySwapMovCmp(p, hp1) then
  4622. begin
  4623. Result := True;
  4624. Exit;
  4625. end;
  4626. { Search for:
  4627. test $x,(reg/ref)
  4628. jne @lbl1
  4629. test $y,(reg/ref) (same register or reference)
  4630. jne @lbl1
  4631. Change to:
  4632. test $(x or y),(reg/ref)
  4633. jne @lbl1
  4634. (Note, this doesn't work with je instead of jne)
  4635. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4636. Also search for:
  4637. test $x,(reg/ref)
  4638. je @lbl1
  4639. test $y,(reg/ref)
  4640. je/jne @lbl2
  4641. If (x or y) = x, then the second jump is deterministic
  4642. }
  4643. if (
  4644. (
  4645. (taicpu(p).oper[0]^.typ = top_const) or
  4646. (
  4647. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4648. (taicpu(p).oper[0]^.typ = top_reg) and
  4649. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4650. )
  4651. ) and
  4652. MatchInstruction(hp1, A_JCC, [])
  4653. ) then
  4654. begin
  4655. if (taicpu(p).oper[0]^.typ = top_reg) and
  4656. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4657. FirstValue := -1
  4658. else
  4659. FirstValue := taicpu(p).oper[0]^.val;
  4660. { If we have several test/jne's in a row, it might be the case that
  4661. the second label doesn't go to the same location, but the one
  4662. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4663. so accommodate for this with a while loop.
  4664. }
  4665. hp1_dist := hp1;
  4666. if GetNextInstruction(hp1, p_dist) and
  4667. (p_dist.typ = ait_instruction) and
  4668. (
  4669. (
  4670. (taicpu(p_dist).opcode = A_TEST) and
  4671. (
  4672. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4673. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4674. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4675. )
  4676. ) or
  4677. (
  4678. { cmp 0,%reg = test %reg,%reg }
  4679. (taicpu(p_dist).opcode = A_CMP) and
  4680. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4681. )
  4682. ) and
  4683. { Make sure the destination operands are actually the same }
  4684. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4685. GetNextInstruction(p_dist, hp1_dist) and
  4686. MatchInstruction(hp1_dist, A_JCC, []) then
  4687. begin
  4688. if
  4689. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4690. (
  4691. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4692. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4693. ) then
  4694. SecondValue := -1
  4695. else
  4696. SecondValue := taicpu(p_dist).oper[0]^.val;
  4697. { If both of the TEST constants are identical, delete the second
  4698. TEST that is unnecessary. }
  4699. if (FirstValue = SecondValue) then
  4700. begin
  4701. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4702. RemoveInstruction(p_dist);
  4703. { Don't let the flags register become deallocated and reallocated between the jumps }
  4704. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4705. Result := True;
  4706. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4707. begin
  4708. { Since the second jump's condition is a subset of the first, we
  4709. know it will never branch because the first jump dominates it.
  4710. Get it out of the way now rather than wait for the jump
  4711. optimisations for a speed boost. }
  4712. if IsJumpToLabel(taicpu(hp1_dist)) then
  4713. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4714. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4715. RemoveInstruction(hp1_dist);
  4716. end
  4717. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4718. begin
  4719. { If the inverse of the first condition is a subset of the second,
  4720. the second one will definitely branch if the first one doesn't }
  4721. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4722. MakeUnconditional(taicpu(hp1_dist));
  4723. RemoveDeadCodeAfterJump(hp1_dist);
  4724. end;
  4725. Exit;
  4726. end;
  4727. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4728. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4729. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4730. then the second jump will never branch, so it can also be
  4731. removed regardless of where it goes }
  4732. (
  4733. (FirstValue = -1) or
  4734. (SecondValue = -1) or
  4735. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4736. ) then
  4737. begin
  4738. { Same jump location... can be a register since nothing's changed }
  4739. { If any of the entries are equivalent to test %reg,%reg, then the
  4740. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4741. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4742. if IsJumpToLabel(taicpu(hp1_dist)) then
  4743. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4744. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4745. RemoveInstruction(hp1_dist);
  4746. { Only remove the second test if no jumps or other conditional instructions follow }
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4749. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4750. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4751. RemoveInstruction(p_dist);
  4752. Result := True;
  4753. Exit;
  4754. end;
  4755. end;
  4756. end;
  4757. { Search for:
  4758. test %reg,%reg
  4759. j(c1) @lbl1
  4760. ...
  4761. @lbl:
  4762. test %reg,%reg (same register)
  4763. j(c2) @lbl2
  4764. If c2 is a subset of c1, change to:
  4765. test %reg,%reg
  4766. j(c1) @lbl2
  4767. (@lbl1 may become a dead label as a result)
  4768. }
  4769. if (taicpu(p).oper[1]^.typ = top_reg) and
  4770. (taicpu(p).oper[0]^.typ = top_reg) and
  4771. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4772. MatchInstruction(hp1, A_JCC, []) and
  4773. IsJumpToLabel(taicpu(hp1)) then
  4774. begin
  4775. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4776. p_label := nil;
  4777. if Assigned(JumpLabel) then
  4778. p_label := getlabelwithsym(JumpLabel);
  4779. if Assigned(p_label) and
  4780. GetNextInstruction(p_label, p_dist) and
  4781. MatchInstruction(p_dist, A_TEST, []) and
  4782. { It's fine if the second test uses smaller sub-registers }
  4783. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4784. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4785. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4786. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4787. GetNextInstruction(p_dist, hp1_dist) and
  4788. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4789. begin
  4790. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4791. if JumpLabel = JumpLabel_dist then
  4792. { This is an infinite loop }
  4793. Exit;
  4794. { Best optimisation when the first condition is a subset (or equal) of the second }
  4795. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4796. begin
  4797. { Any registers used here will already be allocated }
  4798. if Assigned(JumpLabel) then
  4799. JumpLabel.DecRefs;
  4800. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4801. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4802. Result := True;
  4803. Exit;
  4804. end;
  4805. end;
  4806. end;
  4807. end;
  4808. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4809. var
  4810. hp1, hp2: tai;
  4811. ActiveReg: TRegister;
  4812. OldOffset: asizeint;
  4813. ThisConst: TCGInt;
  4814. function RegDeallocated: Boolean;
  4815. begin
  4816. TransferUsedRegs(TmpUsedRegs);
  4817. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4818. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4819. end;
  4820. begin
  4821. result:=false;
  4822. hp1 := nil;
  4823. { replace
  4824. addX const,%reg1
  4825. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4826. dealloc %reg1
  4827. by
  4828. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4829. }
  4830. if MatchOpType(taicpu(p),top_const,top_reg) then
  4831. begin
  4832. ActiveReg := taicpu(p).oper[1]^.reg;
  4833. { Ensures the entire register was updated }
  4834. if (taicpu(p).opsize >= S_L) and
  4835. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4836. MatchInstruction(hp1,A_LEA,[]) and
  4837. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4838. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4839. (
  4840. { Cover the case where the register in the reference is also the destination register }
  4841. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4842. (
  4843. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4844. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4845. RegDeallocated
  4846. )
  4847. ) then
  4848. begin
  4849. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4850. {$push}
  4851. {$R-}{$Q-}
  4852. { Explicitly disable overflow checking for these offset calculation
  4853. as those do not matter for the final result }
  4854. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4855. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4856. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4857. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4858. {$pop}
  4859. {$ifdef x86_64}
  4860. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4861. begin
  4862. { Overflow; abort }
  4863. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4864. end
  4865. else
  4866. {$endif x86_64}
  4867. begin
  4868. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4869. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4870. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4871. RemoveCurrentP(p, hp1)
  4872. else
  4873. RemoveCurrentP(p);
  4874. result:=true;
  4875. Exit;
  4876. end;
  4877. end;
  4878. if (
  4879. { Save calling GetNextInstructionUsingReg again }
  4880. Assigned(hp1) or
  4881. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4882. ) and
  4883. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4884. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4885. begin
  4886. if taicpu(hp1).oper[0]^.typ = top_const then
  4887. begin
  4888. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4889. if taicpu(hp1).opcode = A_ADD then
  4890. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4891. else
  4892. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4893. Result := True;
  4894. { Handle any overflows }
  4895. case taicpu(p).opsize of
  4896. S_B:
  4897. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4898. S_W:
  4899. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4900. S_L:
  4901. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4902. {$ifdef x86_64}
  4903. S_Q:
  4904. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4905. { Overflow; abort }
  4906. Result := False
  4907. else
  4908. taicpu(p).oper[0]^.val := ThisConst;
  4909. {$endif x86_64}
  4910. else
  4911. InternalError(2021102610);
  4912. end;
  4913. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4914. if Result then
  4915. begin
  4916. if (taicpu(p).oper[0]^.val < 0) and
  4917. (
  4918. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4919. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4920. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4921. ) then
  4922. begin
  4923. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4924. taicpu(p).opcode := A_SUB;
  4925. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4926. end
  4927. else
  4928. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4929. RemoveInstruction(hp1);
  4930. end;
  4931. end
  4932. else
  4933. begin
  4934. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4935. TransferUsedRegs(TmpUsedRegs);
  4936. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4937. hp2 := p;
  4938. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4939. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4940. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4941. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4942. begin
  4943. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4944. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4945. Asml.Remove(p);
  4946. Asml.InsertAfter(p, hp1);
  4947. p := hp1;
  4948. Result := True;
  4949. Exit;
  4950. end;
  4951. end;
  4952. end;
  4953. if DoArithCombineOpt(p) then
  4954. Result:=true;
  4955. end;
  4956. end;
  4957. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4958. var
  4959. hp1: tai;
  4960. ref: Integer;
  4961. saveref: treference;
  4962. Multiple: TCGInt;
  4963. Adjacent: Boolean;
  4964. begin
  4965. Result:=false;
  4966. { play save and throw an error if LEA uses a seg register prefix,
  4967. this is most likely an error somewhere else }
  4968. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4969. internalerror(2022022001);
  4970. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4971. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4972. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4973. (
  4974. { do not mess with leas accessing the stack pointer
  4975. unless it's a null operation }
  4976. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4977. (
  4978. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4979. (taicpu(p).oper[0]^.ref^.offset = 0)
  4980. )
  4981. ) and
  4982. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4983. begin
  4984. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4985. begin
  4986. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4987. begin
  4988. taicpu(p).opcode := A_MOV;
  4989. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4990. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4991. end
  4992. else
  4993. begin
  4994. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4995. RemoveCurrentP(p);
  4996. end;
  4997. Result:=true;
  4998. exit;
  4999. end
  5000. else if (
  5001. { continue to use lea to adjust the stack pointer,
  5002. it is the recommended way, but only if not optimizing for size }
  5003. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5004. (cs_opt_size in current_settings.optimizerswitches)
  5005. ) and
  5006. { If the flags register is in use, don't change the instruction
  5007. to an ADD otherwise this will scramble the flags. [Kit] }
  5008. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5009. ConvertLEA(taicpu(p)) then
  5010. begin
  5011. Result:=true;
  5012. exit;
  5013. end;
  5014. end;
  5015. { Don't optimise if the stack or frame pointer is the destination register }
  5016. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5017. Exit;
  5018. if GetNextInstruction(p,hp1) and
  5019. (hp1.typ=ait_instruction) then
  5020. begin
  5021. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5022. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5023. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5024. begin
  5025. TransferUsedRegs(TmpUsedRegs);
  5026. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5027. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5028. begin
  5029. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5030. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5031. RemoveInstruction(hp1);
  5032. result:=true;
  5033. exit;
  5034. end;
  5035. end;
  5036. { changes
  5037. lea <ref1>, reg1
  5038. <op> ...,<ref. with reg1>,...
  5039. to
  5040. <op> ...,<ref1>,... }
  5041. { find a reference which uses reg1 }
  5042. 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
  5043. ref:=0
  5044. 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
  5045. ref:=1
  5046. else
  5047. ref:=-1;
  5048. if (ref<>-1) and
  5049. { reg1 must be either the base or the index }
  5050. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5051. begin
  5052. { reg1 can be removed from the reference }
  5053. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5054. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5055. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5056. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5057. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5058. else
  5059. Internalerror(2019111201);
  5060. { check if the can insert all data of the lea into the second instruction }
  5061. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5062. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5063. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5064. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5065. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5066. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5067. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5068. {$ifdef x86_64}
  5069. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5070. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5071. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5072. )
  5073. {$endif x86_64}
  5074. then
  5075. begin
  5076. { reg1 might not used by the second instruction after it is remove from the reference }
  5077. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5078. begin
  5079. TransferUsedRegs(TmpUsedRegs);
  5080. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5081. { reg1 is not updated so it might not be used afterwards }
  5082. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5083. begin
  5084. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5085. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5086. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5087. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5088. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5089. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5090. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5091. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5092. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5093. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5094. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5095. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5096. RemoveCurrentP(p, hp1);
  5097. result:=true;
  5098. exit;
  5099. end
  5100. end;
  5101. end;
  5102. { recover }
  5103. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5104. end;
  5105. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5106. if Adjacent or
  5107. { Check further ahead (up to 2 instructions ahead for -O2) }
  5108. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5109. begin
  5110. { Check common LEA/LEA conditions }
  5111. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5112. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5113. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5114. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5115. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5116. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5117. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5118. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5119. (
  5120. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5121. calling it (since it calls GetNextInstruction) }
  5122. Adjacent or
  5123. (
  5124. (
  5125. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5126. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5127. ) and (
  5128. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5129. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5130. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5131. )
  5132. )
  5133. ) then
  5134. begin
  5135. { changes
  5136. lea (regX,scale), reg1
  5137. lea offset(reg1,reg1), reg1
  5138. to
  5139. lea offset(regX,scale*2), reg1
  5140. and
  5141. lea (regX,scale1), reg1
  5142. lea offset(reg1,scale2), reg1
  5143. to
  5144. lea offset(regX,scale1*scale2), reg1
  5145. ... so long as the final scale does not exceed 8
  5146. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5147. }
  5148. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5149. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5150. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5151. (
  5152. (
  5153. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5154. ) or (
  5155. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5156. (
  5157. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5158. (
  5159. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5160. Adjacent or
  5161. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5162. )
  5163. )
  5164. )
  5165. ) and (
  5166. (
  5167. { lea (reg1,scale2), reg1 variant }
  5168. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5169. (
  5170. (
  5171. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5172. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5173. ) or (
  5174. { lea (regX,regX), reg1 variant }
  5175. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5176. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5177. )
  5178. )
  5179. ) or (
  5180. { lea (reg1,reg1), reg1 variant }
  5181. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5182. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5183. )
  5184. ) then
  5185. begin
  5186. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5187. { Make everything homogeneous to make calculations easier }
  5188. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5189. begin
  5190. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5191. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5192. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5193. else
  5194. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5195. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5196. end;
  5197. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5198. begin
  5199. { Just to prevent miscalculations }
  5200. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5201. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5202. else
  5203. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5204. end
  5205. else
  5206. begin
  5207. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5208. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5209. end;
  5210. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5211. RemoveCurrentP(p);
  5212. result:=true;
  5213. exit;
  5214. end
  5215. { changes
  5216. lea offset1(regX), reg1
  5217. lea offset2(reg1), reg1
  5218. to
  5219. lea offset1+offset2(regX), reg1 }
  5220. else if
  5221. (
  5222. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5223. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5224. ) or (
  5225. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5226. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5227. (
  5228. (
  5229. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5230. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5231. ) or (
  5232. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5233. (
  5234. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5235. (
  5236. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5237. (
  5238. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5239. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5240. )
  5241. )
  5242. )
  5243. )
  5244. )
  5245. ) then
  5246. begin
  5247. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5248. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5249. begin
  5250. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5251. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5252. { if the register is used as index and base, we have to increase for base as well
  5253. and adapt base }
  5254. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5255. begin
  5256. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5257. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5258. end;
  5259. end
  5260. else
  5261. begin
  5262. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5263. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5264. end;
  5265. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5266. begin
  5267. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5268. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5269. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5270. end;
  5271. RemoveCurrentP(p);
  5272. result:=true;
  5273. exit;
  5274. end;
  5275. end;
  5276. { Change:
  5277. leal/q $x(%reg1),%reg2
  5278. ...
  5279. shll/q $y,%reg2
  5280. To:
  5281. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5282. }
  5283. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5284. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5285. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5286. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5287. (taicpu(hp1).oper[0]^.val <= 3) then
  5288. begin
  5289. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5290. TransferUsedRegs(TmpUsedRegs);
  5291. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5292. if
  5293. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5294. (this works even if scalefactor is zero) }
  5295. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5296. { Ensure offset doesn't go out of bounds }
  5297. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5298. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5299. (
  5300. (
  5301. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5302. (
  5303. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5304. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5305. (
  5306. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5307. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5308. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5309. )
  5310. )
  5311. ) or (
  5312. (
  5313. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5314. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5315. ) and
  5316. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5317. )
  5318. ) then
  5319. begin
  5320. repeat
  5321. with taicpu(p).oper[0]^.ref^ do
  5322. begin
  5323. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5324. if index = base then
  5325. begin
  5326. if Multiple > 4 then
  5327. { Optimisation will no longer work because resultant
  5328. scale factor will exceed 8 }
  5329. Break;
  5330. base := NR_NO;
  5331. scalefactor := 2;
  5332. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5333. end
  5334. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5335. begin
  5336. { Scale factor only works on the index register }
  5337. index := base;
  5338. base := NR_NO;
  5339. end;
  5340. { For safety }
  5341. if scalefactor <= 1 then
  5342. begin
  5343. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5344. scalefactor := Multiple;
  5345. end
  5346. else
  5347. begin
  5348. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5349. scalefactor := scalefactor * Multiple;
  5350. end;
  5351. offset := offset * Multiple;
  5352. end;
  5353. RemoveInstruction(hp1);
  5354. Result := True;
  5355. Exit;
  5356. { This repeat..until loop exists for the benefit of Break }
  5357. until True;
  5358. end;
  5359. end;
  5360. end;
  5361. end;
  5362. end;
  5363. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5364. var
  5365. hp1 : tai;
  5366. SubInstr: Boolean;
  5367. ThisConst: TCGInt;
  5368. const
  5369. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5370. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5371. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5372. begin
  5373. Result := False;
  5374. if taicpu(p).oper[0]^.typ <> top_const then
  5375. { Should have been confirmed before calling }
  5376. InternalError(2021102601);
  5377. SubInstr := (taicpu(p).opcode = A_SUB);
  5378. if GetLastInstruction(p, hp1) and
  5379. (hp1.typ = ait_instruction) and
  5380. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5381. begin
  5382. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5383. { Bad size }
  5384. InternalError(2022042001);
  5385. case taicpu(hp1).opcode Of
  5386. A_INC:
  5387. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5388. begin
  5389. if SubInstr then
  5390. ThisConst := taicpu(p).oper[0]^.val - 1
  5391. else
  5392. ThisConst := taicpu(p).oper[0]^.val + 1;
  5393. end
  5394. else
  5395. Exit;
  5396. A_DEC:
  5397. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5398. begin
  5399. if SubInstr then
  5400. ThisConst := taicpu(p).oper[0]^.val + 1
  5401. else
  5402. ThisConst := taicpu(p).oper[0]^.val - 1;
  5403. end
  5404. else
  5405. Exit;
  5406. A_SUB:
  5407. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5408. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5409. begin
  5410. if SubInstr then
  5411. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5412. else
  5413. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5414. end
  5415. else
  5416. Exit;
  5417. A_ADD:
  5418. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5419. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5420. begin
  5421. if SubInstr then
  5422. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5423. else
  5424. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5425. end
  5426. else
  5427. Exit;
  5428. else
  5429. Exit;
  5430. end;
  5431. { Check that the values are in range }
  5432. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5433. { Overflow; abort }
  5434. Exit;
  5435. if (ThisConst = 0) then
  5436. begin
  5437. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5438. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5439. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5440. RemoveInstruction(hp1);
  5441. hp1 := tai(p.next);
  5442. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5443. if not GetLastInstruction(hp1, p) then
  5444. p := hp1;
  5445. end
  5446. else
  5447. begin
  5448. if taicpu(hp1).opercnt=1 then
  5449. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5450. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5451. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5452. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5453. else
  5454. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5455. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5456. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5457. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5458. RemoveInstruction(hp1);
  5459. taicpu(p).loadconst(0, ThisConst);
  5460. end;
  5461. Result := True;
  5462. end;
  5463. end;
  5464. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5465. begin
  5466. Result := False;
  5467. if UpdateTmpUsedRegs then
  5468. TransferUsedRegs(TmpUsedRegs);
  5469. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5470. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5471. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5472. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5473. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5474. (
  5475. (
  5476. (taicpu(hp1).opcode = A_TEST)
  5477. ) or (
  5478. (taicpu(hp1).opcode = A_CMP) and
  5479. { A sanity check more than anything }
  5480. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5481. )
  5482. ) then
  5483. begin
  5484. { change
  5485. mov mem, %reg
  5486. cmp/test x, %reg / test %reg,%reg
  5487. (reg deallocated)
  5488. to
  5489. cmp/test x, mem / cmp 0, mem
  5490. }
  5491. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5492. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5493. begin
  5494. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5495. if (taicpu(hp1).opcode = A_TEST) and
  5496. (
  5497. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5498. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5499. ) then
  5500. begin
  5501. taicpu(hp1).opcode := A_CMP;
  5502. taicpu(hp1).loadconst(0, 0);
  5503. end;
  5504. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5505. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5506. RemoveCurrentP(p, hp1);
  5507. Result := True;
  5508. Exit;
  5509. end;
  5510. end;
  5511. end;
  5512. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5513. var
  5514. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5515. ThisReg, SecondReg: TRegister;
  5516. JumpLoc: TAsmLabel;
  5517. NewSize: TOpSize;
  5518. begin
  5519. Result := False;
  5520. {
  5521. Convert:
  5522. j<c> .L1
  5523. .L2:
  5524. mov 1,reg
  5525. jmp .L3 (or ret, although it might not be a RET yet)
  5526. .L1:
  5527. mov 0,reg
  5528. jmp .L3 (or ret)
  5529. ( As long as .L3 <> .L1 or .L2)
  5530. To:
  5531. mov 0,reg
  5532. set<not(c)> reg
  5533. jmp .L3 (or ret)
  5534. .L2:
  5535. mov 1,reg
  5536. jmp .L3 (or ret)
  5537. .L1:
  5538. mov 0,reg
  5539. jmp .L3 (or ret)
  5540. }
  5541. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5542. Exit;
  5543. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5544. if GetNextInstruction(hp_label, hp2) and
  5545. MatchInstruction(hp2,A_MOV,[]) and
  5546. (taicpu(hp2).oper[0]^.typ = top_const) and
  5547. (
  5548. (
  5549. (taicpu(hp2).oper[1]^.typ = top_reg)
  5550. {$ifdef i386}
  5551. { Under i386, ESI, EDI, EBP and ESP
  5552. don't have an 8-bit representation }
  5553. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5554. {$endif i386}
  5555. ) or (
  5556. {$ifdef i386}
  5557. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5558. {$endif i386}
  5559. (taicpu(hp2).opsize = S_B)
  5560. )
  5561. ) and
  5562. GetNextInstruction(hp2, hp3) and
  5563. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5564. (
  5565. (taicpu(hp3).opcode=A_RET) or
  5566. (
  5567. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5568. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5569. )
  5570. ) and
  5571. GetNextInstruction(hp3, hp4) and
  5572. SkipAligns(hp4, hp4) and
  5573. (hp4.typ=ait_label) and
  5574. (tai_label(hp4).labsym=JumpLoc) and
  5575. (
  5576. not (cs_opt_size in current_settings.optimizerswitches) or
  5577. { If the initial jump is the label's only reference, then it will
  5578. become a dead label if the other conditions are met and hence
  5579. remove at least 2 instructions, including a jump }
  5580. (JumpLoc.getrefs = 1)
  5581. ) and
  5582. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5583. that will be optimised out }
  5584. GetNextInstruction(hp4, hp5) and
  5585. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5586. (taicpu(hp5).oper[0]^.typ = top_const) and
  5587. (
  5588. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5589. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5590. ) and
  5591. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5592. GetNextInstruction(hp5,hp6) and
  5593. (
  5594. (hp6.typ<>ait_label) or
  5595. SkipLabels(hp6, hp6)
  5596. ) and
  5597. (hp6.typ=ait_instruction) then
  5598. begin
  5599. { First, let's look at the two jumps that are hp3 and hp6 }
  5600. if not
  5601. (
  5602. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5603. (
  5604. (taicpu(hp6).opcode=A_RET) or
  5605. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5606. )
  5607. ) then
  5608. { If condition is False, then the JMP/RET instructions matched conventionally }
  5609. begin
  5610. { See if one of the jumps can be instantly converted into a RET }
  5611. if (taicpu(hp3).opcode=A_JMP) then
  5612. begin
  5613. { Reuse hp5 }
  5614. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5615. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5616. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5617. Exit;
  5618. if MatchInstruction(hp5, A_RET, []) then
  5619. begin
  5620. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5621. ConvertJumpToRET(hp3, hp5);
  5622. Result := True;
  5623. end
  5624. else
  5625. Exit;
  5626. end;
  5627. if (taicpu(hp6).opcode=A_JMP) then
  5628. begin
  5629. { Reuse hp5 }
  5630. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5631. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5632. Exit;
  5633. if MatchInstruction(hp5, A_RET, []) then
  5634. begin
  5635. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5636. ConvertJumpToRET(hp6, hp5);
  5637. Result := True;
  5638. end
  5639. else
  5640. Exit;
  5641. end;
  5642. if not
  5643. (
  5644. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5645. (
  5646. (taicpu(hp6).opcode=A_RET) or
  5647. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5648. )
  5649. ) then
  5650. { Still doesn't match }
  5651. Exit;
  5652. end;
  5653. if (taicpu(hp2).oper[0]^.val = 1) then
  5654. begin
  5655. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5656. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5657. end
  5658. else
  5659. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5660. if taicpu(hp2).opsize=S_B then
  5661. begin
  5662. if taicpu(hp2).oper[1]^.typ = top_reg then
  5663. begin
  5664. SecondReg := taicpu(hp2).oper[1]^.reg;
  5665. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5666. end
  5667. else
  5668. begin
  5669. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5670. SecondReg := NR_NO;
  5671. end;
  5672. hp_pos := p;
  5673. hp_allocstart := hp4;
  5674. end
  5675. else
  5676. begin
  5677. { Will be a register because the size can't be S_B otherwise }
  5678. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5679. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5680. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5681. if (cs_opt_size in current_settings.optimizerswitches) then
  5682. begin
  5683. { Favour using MOVZX when optimising for size }
  5684. case taicpu(hp2).opsize of
  5685. S_W:
  5686. NewSize := S_BW;
  5687. S_L:
  5688. NewSize := S_BL;
  5689. {$ifdef x86_64}
  5690. S_Q:
  5691. begin
  5692. NewSize := S_BL;
  5693. { Will implicitly zero-extend to 64-bit }
  5694. setsubreg(SecondReg, R_SUBD);
  5695. end;
  5696. {$endif x86_64}
  5697. else
  5698. InternalError(2022101301);
  5699. end;
  5700. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5701. { Inserting it right before p will guarantee that the flags are also tracked }
  5702. Asml.InsertBefore(hp5, p);
  5703. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5704. hp_pos := hp5;
  5705. hp_allocstart := hp4;
  5706. end
  5707. else
  5708. begin
  5709. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5710. { Inserting it right before p will guarantee that the flags are also tracked }
  5711. Asml.InsertBefore(hp5, p);
  5712. hp_pos := p;
  5713. hp_allocstart := hp5;
  5714. end;
  5715. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5716. end;
  5717. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5718. taicpu(hp4).condition := taicpu(p).condition;
  5719. asml.InsertBefore(hp4, hp_pos);
  5720. if taicpu(hp3).is_jmp then
  5721. begin
  5722. JumpLoc.decrefs;
  5723. MakeUnconditional(taicpu(p));
  5724. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5725. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5726. end
  5727. else
  5728. ConvertJumpToRET(p, hp3);
  5729. if SecondReg <> NR_NO then
  5730. { Ensure the destination register is allocated over this region }
  5731. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5732. if (JumpLoc.getrefs = 0) then
  5733. RemoveDeadCodeAfterJump(hp3);
  5734. Result:=true;
  5735. exit;
  5736. end;
  5737. end;
  5738. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5739. var
  5740. hp1, hp2: tai;
  5741. ActiveReg: TRegister;
  5742. OldOffset: asizeint;
  5743. ThisConst: TCGInt;
  5744. function RegDeallocated: Boolean;
  5745. begin
  5746. TransferUsedRegs(TmpUsedRegs);
  5747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5748. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5749. end;
  5750. begin
  5751. Result:=false;
  5752. hp1 := nil;
  5753. { replace
  5754. subX const,%reg1
  5755. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5756. dealloc %reg1
  5757. by
  5758. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5759. }
  5760. if MatchOpType(taicpu(p),top_const,top_reg) then
  5761. begin
  5762. ActiveReg := taicpu(p).oper[1]^.reg;
  5763. { Ensures the entire register was updated }
  5764. if (taicpu(p).opsize >= S_L) and
  5765. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5766. MatchInstruction(hp1,A_LEA,[]) and
  5767. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5768. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5769. (
  5770. { Cover the case where the register in the reference is also the destination register }
  5771. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5772. (
  5773. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5774. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5775. RegDeallocated
  5776. )
  5777. ) then
  5778. begin
  5779. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5780. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5781. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5782. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5783. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5784. {$ifdef x86_64}
  5785. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5786. begin
  5787. { Overflow; abort }
  5788. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5789. end
  5790. else
  5791. {$endif x86_64}
  5792. begin
  5793. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5794. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5795. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5796. RemoveCurrentP(p, hp1)
  5797. else
  5798. RemoveCurrentP(p);
  5799. result:=true;
  5800. Exit;
  5801. end;
  5802. end;
  5803. if (
  5804. { Save calling GetNextInstructionUsingReg again }
  5805. Assigned(hp1) or
  5806. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5807. ) and
  5808. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5809. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5810. begin
  5811. if taicpu(hp1).oper[0]^.typ = top_const then
  5812. begin
  5813. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5814. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5815. Result := True;
  5816. { Handle any overflows }
  5817. case taicpu(p).opsize of
  5818. S_B:
  5819. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5820. S_W:
  5821. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5822. S_L:
  5823. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5824. {$ifdef x86_64}
  5825. S_Q:
  5826. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5827. { Overflow; abort }
  5828. Result := False
  5829. else
  5830. taicpu(p).oper[0]^.val := ThisConst;
  5831. {$endif x86_64}
  5832. else
  5833. InternalError(2021102611);
  5834. end;
  5835. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5836. if Result then
  5837. begin
  5838. if (taicpu(p).oper[0]^.val < 0) and
  5839. (
  5840. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5841. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5842. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5843. ) then
  5844. begin
  5845. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5846. taicpu(p).opcode := A_SUB;
  5847. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5848. end
  5849. else
  5850. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5851. RemoveInstruction(hp1);
  5852. end;
  5853. end
  5854. else
  5855. begin
  5856. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5857. TransferUsedRegs(TmpUsedRegs);
  5858. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5859. hp2 := p;
  5860. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5861. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5862. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5863. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5864. begin
  5865. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5866. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5867. Asml.Remove(p);
  5868. Asml.InsertAfter(p, hp1);
  5869. p := hp1;
  5870. Result := True;
  5871. Exit;
  5872. end;
  5873. end;
  5874. end;
  5875. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5876. { * change "sub/add const1, reg" or "dec reg" followed by
  5877. "sub const2, reg" to one "sub ..., reg" }
  5878. {$ifdef i386}
  5879. if (taicpu(p).oper[0]^.val = 2) and
  5880. (ActiveReg = NR_ESP) and
  5881. { Don't do the sub/push optimization if the sub }
  5882. { comes from setting up the stack frame (JM) }
  5883. (not(GetLastInstruction(p,hp1)) or
  5884. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5885. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5886. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5887. begin
  5888. hp1 := tai(p.next);
  5889. while Assigned(hp1) and
  5890. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5891. not RegReadByInstruction(NR_ESP,hp1) and
  5892. not RegModifiedByInstruction(NR_ESP,hp1) do
  5893. hp1 := tai(hp1.next);
  5894. if Assigned(hp1) and
  5895. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5896. begin
  5897. taicpu(hp1).changeopsize(S_L);
  5898. if taicpu(hp1).oper[0]^.typ=top_reg then
  5899. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5900. hp1 := tai(p.next);
  5901. RemoveCurrentp(p, hp1);
  5902. Result:=true;
  5903. exit;
  5904. end;
  5905. end;
  5906. {$endif i386}
  5907. if DoArithCombineOpt(p) then
  5908. Result:=true;
  5909. end;
  5910. end;
  5911. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5912. var
  5913. TmpBool1,TmpBool2 : Boolean;
  5914. tmpref : treference;
  5915. hp1,hp2: tai;
  5916. mask: tcgint;
  5917. begin
  5918. Result:=false;
  5919. { All these optimisations work on "shl/sal const,%reg" }
  5920. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5921. Exit;
  5922. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5923. (taicpu(p).oper[0]^.val <= 3) then
  5924. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5925. begin
  5926. { should we check the next instruction? }
  5927. TmpBool1 := True;
  5928. { have we found an add/sub which could be
  5929. integrated in the lea? }
  5930. TmpBool2 := False;
  5931. reference_reset(tmpref,2,[]);
  5932. TmpRef.index := taicpu(p).oper[1]^.reg;
  5933. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5934. while TmpBool1 and
  5935. GetNextInstruction(p, hp1) and
  5936. (tai(hp1).typ = ait_instruction) and
  5937. ((((taicpu(hp1).opcode = A_ADD) or
  5938. (taicpu(hp1).opcode = A_SUB)) and
  5939. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5940. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5941. (((taicpu(hp1).opcode = A_INC) or
  5942. (taicpu(hp1).opcode = A_DEC)) and
  5943. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5944. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5945. ((taicpu(hp1).opcode = A_LEA) and
  5946. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5947. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5948. (not GetNextInstruction(hp1,hp2) or
  5949. not instrReadsFlags(hp2)) Do
  5950. begin
  5951. TmpBool1 := False;
  5952. if taicpu(hp1).opcode=A_LEA then
  5953. begin
  5954. if (TmpRef.base = NR_NO) and
  5955. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5956. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5957. { Segment register isn't a concern here }
  5958. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5959. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5960. begin
  5961. TmpBool1 := True;
  5962. TmpBool2 := True;
  5963. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5964. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5965. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5966. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5967. RemoveInstruction(hp1);
  5968. end
  5969. end
  5970. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5971. begin
  5972. TmpBool1 := True;
  5973. TmpBool2 := True;
  5974. case taicpu(hp1).opcode of
  5975. A_ADD:
  5976. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5977. A_SUB:
  5978. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5979. else
  5980. internalerror(2019050536);
  5981. end;
  5982. RemoveInstruction(hp1);
  5983. end
  5984. else
  5985. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5986. (((taicpu(hp1).opcode = A_ADD) and
  5987. (TmpRef.base = NR_NO)) or
  5988. (taicpu(hp1).opcode = A_INC) or
  5989. (taicpu(hp1).opcode = A_DEC)) then
  5990. begin
  5991. TmpBool1 := True;
  5992. TmpBool2 := True;
  5993. case taicpu(hp1).opcode of
  5994. A_ADD:
  5995. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5996. A_INC:
  5997. inc(TmpRef.offset);
  5998. A_DEC:
  5999. dec(TmpRef.offset);
  6000. else
  6001. internalerror(2019050535);
  6002. end;
  6003. RemoveInstruction(hp1);
  6004. end;
  6005. end;
  6006. if TmpBool2
  6007. {$ifndef x86_64}
  6008. or
  6009. ((current_settings.optimizecputype < cpu_Pentium2) and
  6010. (taicpu(p).oper[0]^.val <= 3) and
  6011. not(cs_opt_size in current_settings.optimizerswitches))
  6012. {$endif x86_64}
  6013. then
  6014. begin
  6015. if not(TmpBool2) and
  6016. (taicpu(p).oper[0]^.val=1) then
  6017. begin
  6018. taicpu(p).opcode := A_ADD;
  6019. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6020. end
  6021. else
  6022. begin
  6023. taicpu(p).opcode := A_LEA;
  6024. taicpu(p).loadref(0, TmpRef);
  6025. end;
  6026. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6027. Result := True;
  6028. end;
  6029. end
  6030. {$ifndef x86_64}
  6031. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6032. begin
  6033. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6034. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6035. (unlike shl, which is only Tairable in the U pipe) }
  6036. if taicpu(p).oper[0]^.val=1 then
  6037. begin
  6038. taicpu(p).opcode := A_ADD;
  6039. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6040. Result := True;
  6041. end
  6042. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6043. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6044. else if (taicpu(p).opsize = S_L) and
  6045. (taicpu(p).oper[0]^.val<= 3) then
  6046. begin
  6047. reference_reset(tmpref,2,[]);
  6048. TmpRef.index := taicpu(p).oper[1]^.reg;
  6049. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6050. taicpu(p).opcode := A_LEA;
  6051. taicpu(p).loadref(0, TmpRef);
  6052. Result := True;
  6053. end;
  6054. end
  6055. {$endif x86_64}
  6056. else if
  6057. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6058. (
  6059. (
  6060. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6061. SetAndTest(hp1, hp2)
  6062. {$ifdef x86_64}
  6063. ) or
  6064. (
  6065. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6066. GetNextInstruction(hp1, hp2) and
  6067. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6068. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6069. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6070. {$endif x86_64}
  6071. )
  6072. ) and
  6073. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6074. begin
  6075. { Change:
  6076. shl x, %reg1
  6077. mov -(1<<x), %reg2
  6078. and %reg2, %reg1
  6079. Or:
  6080. shl x, %reg1
  6081. and -(1<<x), %reg1
  6082. To just:
  6083. shl x, %reg1
  6084. Since the and operation only zeroes bits that are already zero from the shl operation
  6085. }
  6086. case taicpu(p).oper[0]^.val of
  6087. 8:
  6088. mask:=$FFFFFFFFFFFFFF00;
  6089. 16:
  6090. mask:=$FFFFFFFFFFFF0000;
  6091. 32:
  6092. mask:=$FFFFFFFF00000000;
  6093. 63:
  6094. { Constant pre-calculated to prevent overflow errors with Int64 }
  6095. mask:=$8000000000000000;
  6096. else
  6097. begin
  6098. if taicpu(p).oper[0]^.val >= 64 then
  6099. { Shouldn't happen realistically, since the register
  6100. is guaranteed to be set to zero at this point }
  6101. mask := 0
  6102. else
  6103. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6104. end;
  6105. end;
  6106. if taicpu(hp1).oper[0]^.val = mask then
  6107. begin
  6108. { Everything checks out, perform the optimisation, as long as
  6109. the FLAGS register isn't being used}
  6110. TransferUsedRegs(TmpUsedRegs);
  6111. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6112. {$ifdef x86_64}
  6113. if (hp1 <> hp2) then
  6114. begin
  6115. { "shl/mov/and" version }
  6116. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6117. { Don't do the optimisation if the FLAGS register is in use }
  6118. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6119. begin
  6120. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6121. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6122. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6123. begin
  6124. RemoveInstruction(hp1);
  6125. Result := True;
  6126. end;
  6127. { Only set Result to True if the 'mov' instruction was removed }
  6128. RemoveInstruction(hp2);
  6129. end;
  6130. end
  6131. else
  6132. {$endif x86_64}
  6133. begin
  6134. { "shl/and" version }
  6135. { Don't do the optimisation if the FLAGS register is in use }
  6136. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6137. begin
  6138. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6139. RemoveInstruction(hp1);
  6140. Result := True;
  6141. end;
  6142. end;
  6143. Exit;
  6144. end
  6145. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6146. begin
  6147. { Even if the mask doesn't allow for its removal, we might be
  6148. able to optimise the mask for the "shl/and" version, which
  6149. may permit other peephole optimisations }
  6150. {$ifdef DEBUG_AOPTCPU}
  6151. mask := taicpu(hp1).oper[0]^.val and mask;
  6152. if taicpu(hp1).oper[0]^.val <> mask then
  6153. begin
  6154. DebugMsg(
  6155. SPeepholeOptimization +
  6156. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6157. ' to $' + debug_tostr(mask) +
  6158. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6159. taicpu(hp1).oper[0]^.val := mask;
  6160. end;
  6161. {$else DEBUG_AOPTCPU}
  6162. { If debugging is off, just set the operand even if it's the same }
  6163. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6164. {$endif DEBUG_AOPTCPU}
  6165. end;
  6166. end;
  6167. {
  6168. change
  6169. shl/sal const,reg
  6170. <op> ...(...,reg,1),...
  6171. into
  6172. <op> ...(...,reg,1 shl const),...
  6173. if const in 1..3
  6174. }
  6175. if MatchOpType(taicpu(p), top_const, top_reg) and
  6176. (taicpu(p).oper[0]^.val in [1..3]) and
  6177. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6178. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6179. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6180. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6181. MatchOpType(taicpu(hp1),top_ref))
  6182. ) and
  6183. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6184. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6185. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6186. begin
  6187. TransferUsedRegs(TmpUsedRegs);
  6188. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6189. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6190. begin
  6191. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6192. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6193. RemoveCurrentP(p);
  6194. Result:=true;
  6195. end;
  6196. end;
  6197. end;
  6198. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6199. begin
  6200. case shr_size of
  6201. S_B:
  6202. { No valid combinations }
  6203. Result := False;
  6204. S_W:
  6205. Result := (Shift >= 8) and (movz_size = S_BW);
  6206. S_L:
  6207. Result :=
  6208. (Shift >= 24) { Any opsize is valid for this shift } or
  6209. ((Shift >= 16) and (movz_size = S_WL));
  6210. {$ifdef x86_64}
  6211. S_Q:
  6212. Result :=
  6213. (Shift >= 56) { Any opsize is valid for this shift } or
  6214. ((Shift >= 48) and (movz_size = S_WL));
  6215. {$endif x86_64}
  6216. else
  6217. InternalError(2022081510);
  6218. end;
  6219. end;
  6220. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6221. var
  6222. hp1, hp2: tai;
  6223. Shift: TCGInt;
  6224. LimitSize: Topsize;
  6225. DoNotMerge: Boolean;
  6226. begin
  6227. Result := False;
  6228. { All these optimisations work on "shr const,%reg" }
  6229. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6230. Exit;
  6231. DoNotMerge := False;
  6232. Shift := taicpu(p).oper[0]^.val;
  6233. LimitSize := taicpu(p).opsize;
  6234. hp1 := p;
  6235. repeat
  6236. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6237. Exit;
  6238. case taicpu(hp1).opcode of
  6239. A_TEST, A_CMP, A_Jcc:
  6240. { Skip over conditional jumps and relevant comparisons }
  6241. Continue;
  6242. A_MOVZX:
  6243. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6244. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6245. begin
  6246. { Since the original register is being read as is, subsequent
  6247. SHRs must not be merged at this point }
  6248. DoNotMerge := True;
  6249. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6250. begin
  6251. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6252. begin
  6253. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6254. taicpu(hp1).opcode := A_MOV;
  6255. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6256. case taicpu(hp1).opsize of
  6257. S_BW:
  6258. taicpu(hp1).opsize := S_W;
  6259. S_BL, S_WL:
  6260. taicpu(hp1).opsize := S_L;
  6261. else
  6262. InternalError(2022081503);
  6263. end;
  6264. { p itself hasn't changed, so no need to set Result to True }
  6265. Include(OptsToCheck, aoc_ForceNewIteration);
  6266. { See if there's anything afterwards that can be
  6267. optimised, since the input register hasn't changed }
  6268. Continue;
  6269. end;
  6270. { NOTE: If the MOVZX instruction reads and writes the same
  6271. register, defer this to the post-peephole optimisation stage }
  6272. Exit;
  6273. end;
  6274. end;
  6275. A_SHL, A_SAL, A_SHR:
  6276. if (taicpu(hp1).opsize <= LimitSize) and
  6277. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6278. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6279. begin
  6280. { Make sure the sizes don't exceed the register size limit
  6281. (measured by the shift value falling below the limit) }
  6282. if taicpu(hp1).opsize < LimitSize then
  6283. LimitSize := taicpu(hp1).opsize;
  6284. if taicpu(hp1).opcode = A_SHR then
  6285. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6286. else
  6287. begin
  6288. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6289. DoNotMerge := True;
  6290. end;
  6291. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6292. Exit;
  6293. { Since we've established that the combined shift is within
  6294. limits, we can actually combine the adjacent SHR
  6295. instructions even if they're different sizes }
  6296. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6297. begin
  6298. hp2 := tai(hp1.Previous);
  6299. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6300. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6301. RemoveInstruction(hp1);
  6302. hp1 := hp2;
  6303. { Though p has changed, only the constant has, and its
  6304. effects can still be detected on the next iteration of
  6305. the repeat..until loop }
  6306. Include(OptsToCheck, aoc_ForceNewIteration);
  6307. end;
  6308. { Move onto the next instruction }
  6309. Continue;
  6310. end;
  6311. else
  6312. ;
  6313. end;
  6314. Break;
  6315. until False;
  6316. end;
  6317. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6318. var
  6319. CurrentRef: TReference;
  6320. FullReg: TRegister;
  6321. hp1, hp2: tai;
  6322. begin
  6323. Result := False;
  6324. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6325. Exit;
  6326. { We assume you've checked if the operand is actually a reference by
  6327. this point. If it isn't, you'll most likely get an access violation }
  6328. CurrentRef := first_mov.oper[1]^.ref^;
  6329. { Memory must be aligned }
  6330. if (CurrentRef.offset mod 4) <> 0 then
  6331. Exit;
  6332. Inc(CurrentRef.offset);
  6333. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6334. if MatchOperand(second_mov.oper[0]^, 0) and
  6335. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6336. GetNextInstruction(second_mov, hp1) and
  6337. (hp1.typ = ait_instruction) and
  6338. (taicpu(hp1).opcode = A_MOV) and
  6339. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6340. (taicpu(hp1).oper[0]^.val = 0) then
  6341. begin
  6342. Inc(CurrentRef.offset);
  6343. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6344. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6345. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6346. begin
  6347. case taicpu(hp1).opsize of
  6348. S_B:
  6349. if GetNextInstruction(hp1, hp2) and
  6350. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6351. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6352. (taicpu(hp2).oper[0]^.val = 0) then
  6353. begin
  6354. Inc(CurrentRef.offset);
  6355. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6356. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6357. (taicpu(hp2).opsize = S_B) then
  6358. begin
  6359. RemoveInstruction(hp1);
  6360. RemoveInstruction(hp2);
  6361. first_mov.opsize := S_L;
  6362. if first_mov.oper[0]^.typ = top_reg then
  6363. begin
  6364. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6365. { Reuse second_mov as a MOVZX instruction }
  6366. second_mov.opcode := A_MOVZX;
  6367. second_mov.opsize := S_BL;
  6368. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6369. second_mov.loadreg(1, FullReg);
  6370. first_mov.oper[0]^.reg := FullReg;
  6371. asml.Remove(second_mov);
  6372. asml.InsertBefore(second_mov, first_mov);
  6373. end
  6374. else
  6375. { It's a value }
  6376. begin
  6377. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6378. RemoveInstruction(second_mov);
  6379. end;
  6380. Result := True;
  6381. Exit;
  6382. end;
  6383. end;
  6384. S_W:
  6385. begin
  6386. RemoveInstruction(hp1);
  6387. first_mov.opsize := S_L;
  6388. if first_mov.oper[0]^.typ = top_reg then
  6389. begin
  6390. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6391. { Reuse second_mov as a MOVZX instruction }
  6392. second_mov.opcode := A_MOVZX;
  6393. second_mov.opsize := S_BL;
  6394. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6395. second_mov.loadreg(1, FullReg);
  6396. first_mov.oper[0]^.reg := FullReg;
  6397. asml.Remove(second_mov);
  6398. asml.InsertBefore(second_mov, first_mov);
  6399. end
  6400. else
  6401. { It's a value }
  6402. begin
  6403. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6404. RemoveInstruction(second_mov);
  6405. end;
  6406. Result := True;
  6407. Exit;
  6408. end;
  6409. else
  6410. ;
  6411. end;
  6412. end;
  6413. end;
  6414. end;
  6415. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6416. { returns true if a "continue" should be done after this optimization }
  6417. var
  6418. hp1, hp2: tai;
  6419. begin
  6420. Result := false;
  6421. if MatchOpType(taicpu(p),top_ref) and
  6422. GetNextInstruction(p, hp1) and
  6423. (hp1.typ = ait_instruction) and
  6424. (((taicpu(hp1).opcode = A_FLD) and
  6425. (taicpu(p).opcode = A_FSTP)) or
  6426. ((taicpu(p).opcode = A_FISTP) and
  6427. (taicpu(hp1).opcode = A_FILD))) and
  6428. MatchOpType(taicpu(hp1),top_ref) and
  6429. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6430. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6431. begin
  6432. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6433. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6434. GetNextInstruction(hp1, hp2) and
  6435. (((hp2.typ = ait_instruction) and
  6436. IsExitCode(hp2) and
  6437. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6438. not(assigned(current_procinfo.procdef.funcretsym) and
  6439. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6440. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6441. { fstp <temp>
  6442. fld <temp>
  6443. <dealloc> <temp>
  6444. }
  6445. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6446. (tai_tempalloc(hp2).allocation=false) and
  6447. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6448. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6449. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6450. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6451. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6452. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6453. )
  6454. )
  6455. ) then
  6456. begin
  6457. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6458. RemoveInstruction(hp1);
  6459. RemoveCurrentP(p, hp2);
  6460. { first case: exit code }
  6461. if hp2.typ = ait_instruction then
  6462. RemoveLastDeallocForFuncRes(p);
  6463. Result := true;
  6464. end
  6465. else
  6466. { we can do this only in fast math mode as fstp is rounding ...
  6467. ... still disabled as it breaks the compiler and/or rtl }
  6468. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6469. { ... or if another fstp equal to the first one follows }
  6470. (GetNextInstruction(hp1,hp2) and
  6471. (hp2.typ = ait_instruction) and
  6472. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6473. (taicpu(p).opsize=taicpu(hp2).opsize))
  6474. ) and
  6475. { fst can't store an extended/comp value }
  6476. (taicpu(p).opsize <> S_FX) and
  6477. (taicpu(p).opsize <> S_IQ) then
  6478. begin
  6479. if (taicpu(p).opcode = A_FSTP) then
  6480. taicpu(p).opcode := A_FST
  6481. else
  6482. taicpu(p).opcode := A_FIST;
  6483. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6484. RemoveInstruction(hp1);
  6485. end;
  6486. end;
  6487. end;
  6488. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6489. var
  6490. hp1, hp2: tai;
  6491. begin
  6492. result:=false;
  6493. if MatchOpType(taicpu(p),top_reg) and
  6494. GetNextInstruction(p, hp1) and
  6495. (hp1.typ = Ait_Instruction) and
  6496. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6497. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6498. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6499. { change to
  6500. fld reg fxxx reg,st
  6501. fxxxp st, st1 (hp1)
  6502. Remark: non commutative operations must be reversed!
  6503. }
  6504. begin
  6505. case taicpu(hp1).opcode Of
  6506. A_FMULP,A_FADDP,
  6507. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6508. begin
  6509. case taicpu(hp1).opcode Of
  6510. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6511. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6512. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6513. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6514. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6515. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6516. else
  6517. internalerror(2019050534);
  6518. end;
  6519. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6520. taicpu(hp1).oper[1]^.reg := NR_ST;
  6521. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6522. RemoveCurrentP(p, hp1);
  6523. Result:=true;
  6524. exit;
  6525. end;
  6526. else
  6527. ;
  6528. end;
  6529. end
  6530. else
  6531. if MatchOpType(taicpu(p),top_ref) and
  6532. GetNextInstruction(p, hp2) and
  6533. (hp2.typ = Ait_Instruction) and
  6534. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6535. (taicpu(p).opsize in [S_FS, S_FL]) and
  6536. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6537. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6538. if GetLastInstruction(p, hp1) and
  6539. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6540. MatchOpType(taicpu(hp1),top_ref) and
  6541. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6542. if ((taicpu(hp2).opcode = A_FMULP) or
  6543. (taicpu(hp2).opcode = A_FADDP)) then
  6544. { change to
  6545. fld/fst mem1 (hp1) fld/fst mem1
  6546. fld mem1 (p) fadd/
  6547. faddp/ fmul st, st
  6548. fmulp st, st1 (hp2) }
  6549. begin
  6550. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6551. RemoveCurrentP(p, hp1);
  6552. if (taicpu(hp2).opcode = A_FADDP) then
  6553. taicpu(hp2).opcode := A_FADD
  6554. else
  6555. taicpu(hp2).opcode := A_FMUL;
  6556. taicpu(hp2).oper[1]^.reg := NR_ST;
  6557. end
  6558. else
  6559. { change to
  6560. fld/fst mem1 (hp1) fld/fst mem1
  6561. fld mem1 (p) fld st
  6562. }
  6563. begin
  6564. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6565. taicpu(p).changeopsize(S_FL);
  6566. taicpu(p).loadreg(0,NR_ST);
  6567. end
  6568. else
  6569. begin
  6570. case taicpu(hp2).opcode Of
  6571. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6572. { change to
  6573. fld/fst mem1 (hp1) fld/fst mem1
  6574. fld mem2 (p) fxxx mem2
  6575. fxxxp st, st1 (hp2) }
  6576. begin
  6577. case taicpu(hp2).opcode Of
  6578. A_FADDP: taicpu(p).opcode := A_FADD;
  6579. A_FMULP: taicpu(p).opcode := A_FMUL;
  6580. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6581. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6582. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6583. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6584. else
  6585. internalerror(2019050533);
  6586. end;
  6587. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6588. RemoveInstruction(hp2);
  6589. end
  6590. else
  6591. ;
  6592. end
  6593. end
  6594. end;
  6595. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6596. begin
  6597. Result := condition_in(cond1, cond2) or
  6598. { Not strictly subsets due to the actual flags checked, but because we're
  6599. comparing integers, E is a subset of AE and GE and their aliases }
  6600. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6601. end;
  6602. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6603. var
  6604. v: TCGInt;
  6605. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6606. FirstMatch: Boolean;
  6607. NewReg: TRegister;
  6608. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6609. begin
  6610. Result:=false;
  6611. { All these optimisations need a next instruction }
  6612. if not GetNextInstruction(p, hp1) then
  6613. Exit;
  6614. { Search for:
  6615. cmp ###,###
  6616. j(c1) @lbl1
  6617. ...
  6618. @lbl:
  6619. cmp ###,### (same comparison as above)
  6620. j(c2) @lbl2
  6621. If c1 is a subset of c2, change to:
  6622. cmp ###,###
  6623. j(c1) @lbl2
  6624. (@lbl1 may become a dead label as a result)
  6625. }
  6626. { Also handle cases where there are multiple jumps in a row }
  6627. p_jump := hp1;
  6628. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6629. begin
  6630. if IsJumpToLabel(taicpu(p_jump)) then
  6631. begin
  6632. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6633. p_label := nil;
  6634. if Assigned(JumpLabel) then
  6635. p_label := getlabelwithsym(JumpLabel);
  6636. if Assigned(p_label) and
  6637. GetNextInstruction(p_label, p_dist) and
  6638. MatchInstruction(p_dist, A_CMP, []) and
  6639. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6640. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6641. GetNextInstruction(p_dist, hp1_dist) and
  6642. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6643. begin
  6644. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6645. if JumpLabel = JumpLabel_dist then
  6646. { This is an infinite loop }
  6647. Exit;
  6648. { Best optimisation when the first condition is a subset (or equal) of the second }
  6649. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6650. begin
  6651. { Any registers used here will already be allocated }
  6652. if Assigned(JumpLabel) then
  6653. JumpLabel.DecRefs;
  6654. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6655. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6656. Result := True;
  6657. { Don't exit yet. Since p and p_jump haven't actually been
  6658. removed, we can check for more on this iteration }
  6659. end
  6660. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6661. GetNextInstruction(hp1_dist, hp1_label) and
  6662. SkipAligns(hp1_label, hp1_label) and
  6663. (hp1_label.typ = ait_label) then
  6664. begin
  6665. JumpLabel_far := tai_label(hp1_label).labsym;
  6666. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6667. { This is an infinite loop }
  6668. Exit;
  6669. if Assigned(JumpLabel_far) then
  6670. begin
  6671. { In this situation, if the first jump branches, the second one will never,
  6672. branch so change the destination label to after the second jump }
  6673. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6674. if Assigned(JumpLabel) then
  6675. JumpLabel.DecRefs;
  6676. JumpLabel_far.IncRefs;
  6677. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6678. Result := True;
  6679. { Don't exit yet. Since p and p_jump haven't actually been
  6680. removed, we can check for more on this iteration }
  6681. Continue;
  6682. end;
  6683. end;
  6684. end;
  6685. end;
  6686. { Search for:
  6687. cmp ###,###
  6688. j(c1) @lbl1
  6689. cmp ###,### (same as first)
  6690. Remove second cmp
  6691. }
  6692. if GetNextInstruction(p_jump, hp2) and
  6693. (
  6694. (
  6695. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6696. (
  6697. (
  6698. MatchOpType(taicpu(p), top_const, top_reg) and
  6699. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6700. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6701. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6702. ) or (
  6703. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6704. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6705. )
  6706. )
  6707. ) or (
  6708. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6709. MatchOperand(taicpu(p).oper[0]^, 0) and
  6710. (taicpu(p).oper[1]^.typ = top_reg) and
  6711. MatchInstruction(hp2, A_TEST, []) and
  6712. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6713. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6714. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6715. )
  6716. ) then
  6717. begin
  6718. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6719. RemoveInstruction(hp2);
  6720. Result := True;
  6721. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6722. end;
  6723. GetNextInstruction(p_jump, p_jump);
  6724. end;
  6725. {
  6726. Try to optimise the following:
  6727. cmp $x,### ($x and $y can be registers or constants)
  6728. je @lbl1 (only reference)
  6729. cmp $y,### (### are identical)
  6730. @Lbl:
  6731. sete %reg1
  6732. Change to:
  6733. cmp $x,###
  6734. sete %reg2 (allocate new %reg2)
  6735. cmp $y,###
  6736. sete %reg1
  6737. orb %reg2,%reg1
  6738. (dealloc %reg2)
  6739. This adds an instruction (so don't perform under -Os), but it removes
  6740. a conditional branch.
  6741. }
  6742. if not (cs_opt_size in current_settings.optimizerswitches) and
  6743. (
  6744. (hp1 = p_jump) or
  6745. GetNextInstruction(p, hp1)
  6746. ) and
  6747. MatchInstruction(hp1, A_Jcc, []) and
  6748. IsJumpToLabel(taicpu(hp1)) and
  6749. (taicpu(hp1).condition in [C_E, C_Z]) and
  6750. GetNextInstruction(hp1, hp2) and
  6751. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6752. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6753. { The first operand of CMP instructions can only be a register or
  6754. immediate anyway, so no need to check }
  6755. GetNextInstruction(hp2, p_label) and
  6756. (
  6757. (p_label.typ = ait_label) or
  6758. (
  6759. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6760. to potentially cut down on the iterations of Pass 1 }
  6761. MatchInstruction(p_label, A_Jcc, []) and
  6762. IsJumpToLabel(taicpu(p_label)) and
  6763. { Use p_dist to hold the jump briefly }
  6764. SetAndTest(p_label, p_dist) and
  6765. GetNextInstruction(p_dist, p_label) and
  6766. (p_label.typ = ait_label) and
  6767. (tai_label(p_label).labsym.getrefs >= 2) and
  6768. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6769. { We might as well collapse the jump now }
  6770. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6771. )
  6772. ) and
  6773. (tai_label(p_label).labsym.getrefs = 1) and
  6774. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6775. GetNextInstruction(p_label, p_dist) and
  6776. MatchInstruction(p_dist, A_SETcc, []) and
  6777. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6778. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6779. { Get the instruction after the SETcc instruction so we can
  6780. allocate a new register over the entire range }
  6781. GetNextInstruction(p_dist, hp1_dist) then
  6782. begin
  6783. TransferUsedRegs(TmpUsedRegs);
  6784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6785. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6786. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6787. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6788. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6789. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6790. begin
  6791. { Register can appear in p if it's not used afterwards, so only
  6792. allocate between hp1 and hp1_dist }
  6793. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6794. if NewReg <> NR_NO then
  6795. begin
  6796. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6797. { Change the jump instruction into a SETcc instruction }
  6798. taicpu(hp1).opcode := A_SETcc;
  6799. taicpu(hp1).opsize := S_B;
  6800. taicpu(hp1).loadreg(0, NewReg);
  6801. { This is now a dead label }
  6802. tai_label(p_label).labsym.decrefs;
  6803. { Prefer adding before the next instruction so the FLAGS
  6804. register is deallocated first }
  6805. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6806. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6807. AsmL.InsertBefore(
  6808. hp2,
  6809. hp1_dist
  6810. );
  6811. { Make sure the new register is in use over the new instruction
  6812. (long-winded, but things work best when the FLAGS register
  6813. is not allocated here) }
  6814. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6815. Result := True;
  6816. { Don't exit yet, as p wasn't changed and hp1, while
  6817. modified, is still intact and might be optimised by the
  6818. SETcc optimisation below }
  6819. end;
  6820. end;
  6821. end;
  6822. if taicpu(p).oper[0]^.typ = top_const then
  6823. begin
  6824. if (taicpu(p).oper[0]^.val = 0) and
  6825. (taicpu(p).oper[1]^.typ = top_reg) and
  6826. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6827. begin
  6828. hp2 := p;
  6829. FirstMatch := True;
  6830. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6831. anything meaningful once it's converted to "test %reg,%reg";
  6832. additionally, some jumps will always (or never) branch, so
  6833. evaluate every jump immediately following the
  6834. comparison, optimising the conditions if possible.
  6835. Similarly with SETcc... those that are always set to 0 or 1
  6836. are changed to MOV instructions }
  6837. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6838. (
  6839. GetNextInstruction(hp2, hp1) and
  6840. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6841. ) do
  6842. begin
  6843. FirstMatch := False;
  6844. case taicpu(hp1).condition of
  6845. C_B, C_C, C_NAE, C_O:
  6846. { For B/NAE:
  6847. Will never branch since an unsigned integer can never be below zero
  6848. For C/O:
  6849. Result cannot overflow because 0 is being subtracted
  6850. }
  6851. begin
  6852. if taicpu(hp1).opcode = A_Jcc then
  6853. begin
  6854. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6855. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6856. RemoveInstruction(hp1);
  6857. { Since hp1 was deleted, hp2 must not be updated }
  6858. Continue;
  6859. end
  6860. else
  6861. begin
  6862. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6863. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6864. taicpu(hp1).opcode := A_MOV;
  6865. taicpu(hp1).ops := 2;
  6866. taicpu(hp1).condition := C_None;
  6867. taicpu(hp1).opsize := S_B;
  6868. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6869. taicpu(hp1).loadconst(0, 0);
  6870. end;
  6871. end;
  6872. C_BE, C_NA:
  6873. begin
  6874. { Will only branch if equal to zero }
  6875. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6876. taicpu(hp1).condition := C_E;
  6877. end;
  6878. C_A, C_NBE:
  6879. begin
  6880. { Will only branch if not equal to zero }
  6881. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6882. taicpu(hp1).condition := C_NE;
  6883. end;
  6884. C_AE, C_NB, C_NC, C_NO:
  6885. begin
  6886. { Will always branch }
  6887. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6888. if taicpu(hp1).opcode = A_Jcc then
  6889. begin
  6890. MakeUnconditional(taicpu(hp1));
  6891. { Any jumps/set that follow will now be dead code }
  6892. RemoveDeadCodeAfterJump(taicpu(hp1));
  6893. Break;
  6894. end
  6895. else
  6896. begin
  6897. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6898. taicpu(hp1).opcode := A_MOV;
  6899. taicpu(hp1).ops := 2;
  6900. taicpu(hp1).condition := C_None;
  6901. taicpu(hp1).opsize := S_B;
  6902. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6903. taicpu(hp1).loadconst(0, 1);
  6904. end;
  6905. end;
  6906. C_None:
  6907. InternalError(2020012201);
  6908. C_P, C_PE, C_NP, C_PO:
  6909. { We can't handle parity checks and they should never be generated
  6910. after a general-purpose CMP (it's used in some floating-point
  6911. comparisons that don't use CMP) }
  6912. InternalError(2020012202);
  6913. else
  6914. { Zero/Equality, Sign, their complements and all of the
  6915. signed comparisons do not need to be converted };
  6916. end;
  6917. hp2 := hp1;
  6918. end;
  6919. { Convert the instruction to a TEST }
  6920. taicpu(p).opcode := A_TEST;
  6921. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6922. Result := True;
  6923. Exit;
  6924. end
  6925. else if (taicpu(p).oper[0]^.val = 1) and
  6926. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6927. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6928. begin
  6929. { Convert; To:
  6930. cmp $1,r/m cmp $0,r/m
  6931. jl @lbl jle @lbl
  6932. }
  6933. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6934. taicpu(p).oper[0]^.val := 0;
  6935. taicpu(hp1).condition := C_LE;
  6936. { If the instruction is now "cmp $0,%reg", convert it to a
  6937. TEST (and effectively do the work of the "cmp $0,%reg" in
  6938. the block above)
  6939. If it's a reference, we can get away with not setting
  6940. Result to True because he haven't evaluated the jump
  6941. in this pass yet.
  6942. }
  6943. if (taicpu(p).oper[1]^.typ = top_reg) then
  6944. begin
  6945. taicpu(p).opcode := A_TEST;
  6946. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6947. Result := True;
  6948. end;
  6949. Exit;
  6950. end
  6951. else if (taicpu(p).oper[1]^.typ = top_reg)
  6952. {$ifdef x86_64}
  6953. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6954. {$endif x86_64}
  6955. then
  6956. begin
  6957. { cmp register,$8000 neg register
  6958. je target --> jo target
  6959. .... only if register is deallocated before jump.}
  6960. case Taicpu(p).opsize of
  6961. S_B: v:=$80;
  6962. S_W: v:=$8000;
  6963. S_L: v:=qword($80000000);
  6964. else
  6965. internalerror(2013112905);
  6966. end;
  6967. if (taicpu(p).oper[0]^.val=v) and
  6968. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6969. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6970. begin
  6971. TransferUsedRegs(TmpUsedRegs);
  6972. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6973. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6976. Taicpu(p).opcode:=A_NEG;
  6977. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6978. Taicpu(p).clearop(1);
  6979. Taicpu(p).ops:=1;
  6980. if Taicpu(hp1).condition=C_E then
  6981. Taicpu(hp1).condition:=C_O
  6982. else
  6983. Taicpu(hp1).condition:=C_NO;
  6984. Result:=true;
  6985. exit;
  6986. end;
  6987. end;
  6988. end;
  6989. end;
  6990. if TrySwapMovCmp(p, hp1) then
  6991. begin
  6992. Result := True;
  6993. Exit;
  6994. end;
  6995. end;
  6996. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6997. var
  6998. hp1: tai;
  6999. begin
  7000. {
  7001. remove the second (v)pxor from
  7002. pxor reg,reg
  7003. ...
  7004. pxor reg,reg
  7005. }
  7006. Result:=false;
  7007. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7008. MatchOpType(taicpu(p),top_reg,top_reg) and
  7009. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7010. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7011. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7012. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7013. begin
  7014. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7015. RemoveInstruction(hp1);
  7016. Result:=true;
  7017. Exit;
  7018. end
  7019. {
  7020. replace
  7021. pxor reg1,reg1
  7022. movapd/s reg1,reg2
  7023. dealloc reg1
  7024. by
  7025. pxor reg2,reg2
  7026. }
  7027. else if GetNextInstruction(p,hp1) and
  7028. { we mix single and double opperations here because we assume that the compiler
  7029. generates vmovapd only after double operations and vmovaps only after single operations }
  7030. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7031. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7032. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7033. (taicpu(p).oper[0]^.typ=top_reg) then
  7034. begin
  7035. TransferUsedRegs(TmpUsedRegs);
  7036. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7037. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7038. begin
  7039. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7040. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7041. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7042. RemoveInstruction(hp1);
  7043. result:=true;
  7044. end;
  7045. end;
  7046. end;
  7047. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7048. var
  7049. hp1: tai;
  7050. begin
  7051. {
  7052. remove the second (v)pxor from
  7053. (v)pxor reg,reg
  7054. ...
  7055. (v)pxor reg,reg
  7056. }
  7057. Result:=false;
  7058. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7059. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7060. begin
  7061. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7062. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7063. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7064. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7065. begin
  7066. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7067. RemoveInstruction(hp1);
  7068. Result:=true;
  7069. Exit;
  7070. end;
  7071. {$ifdef x86_64}
  7072. {
  7073. replace
  7074. vpxor reg1,reg1,reg1
  7075. vmov reg,mem
  7076. by
  7077. movq $0,mem
  7078. }
  7079. if GetNextInstruction(p,hp1) and
  7080. MatchInstruction(hp1,A_VMOVSD,[]) and
  7081. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7082. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7083. begin
  7084. TransferUsedRegs(TmpUsedRegs);
  7085. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7086. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7087. begin
  7088. taicpu(hp1).loadconst(0,0);
  7089. taicpu(hp1).opcode:=A_MOV;
  7090. taicpu(hp1).opsize:=S_Q;
  7091. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7092. RemoveCurrentP(p);
  7093. result:=true;
  7094. Exit;
  7095. end;
  7096. end;
  7097. {$endif x86_64}
  7098. end
  7099. {
  7100. replace
  7101. vpxor reg1,reg1,reg2
  7102. by
  7103. vpxor reg2,reg2,reg2
  7104. to avoid unncessary data dependencies
  7105. }
  7106. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7107. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7108. begin
  7109. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7110. { avoid unncessary data dependency }
  7111. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7112. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7113. result:=true;
  7114. exit;
  7115. end;
  7116. Result:=OptPass1VOP(p);
  7117. end;
  7118. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7119. var
  7120. hp1 : tai;
  7121. begin
  7122. result:=false;
  7123. { replace
  7124. IMul const,%mreg1,%mreg2
  7125. Mov %reg2,%mreg3
  7126. dealloc %mreg3
  7127. by
  7128. Imul const,%mreg1,%mreg23
  7129. }
  7130. if (taicpu(p).ops=3) and
  7131. GetNextInstruction(p,hp1) and
  7132. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7133. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7134. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7135. begin
  7136. TransferUsedRegs(TmpUsedRegs);
  7137. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7138. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7139. begin
  7140. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7141. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7142. RemoveInstruction(hp1);
  7143. result:=true;
  7144. end;
  7145. end;
  7146. end;
  7147. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7148. var
  7149. hp1 : tai;
  7150. begin
  7151. result:=false;
  7152. { replace
  7153. IMul %reg0,%reg1,%reg2
  7154. Mov %reg2,%reg3
  7155. dealloc %reg2
  7156. by
  7157. Imul %reg0,%reg1,%reg3
  7158. }
  7159. if GetNextInstruction(p,hp1) and
  7160. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7161. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7162. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7163. begin
  7164. TransferUsedRegs(TmpUsedRegs);
  7165. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7166. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7167. begin
  7168. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7169. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7170. RemoveInstruction(hp1);
  7171. result:=true;
  7172. end;
  7173. end;
  7174. end;
  7175. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7176. var
  7177. hp1: tai;
  7178. begin
  7179. Result:=false;
  7180. { get rid of
  7181. (v)cvtss2sd reg0,<reg1,>reg2
  7182. (v)cvtss2sd reg2,<reg2,>reg0
  7183. }
  7184. if GetNextInstruction(p,hp1) and
  7185. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7186. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7187. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7188. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7189. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7190. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7191. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7192. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7193. )
  7194. ) then
  7195. begin
  7196. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7197. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7198. begin
  7199. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7200. RemoveCurrentP(p);
  7201. RemoveInstruction(hp1);
  7202. end
  7203. else
  7204. begin
  7205. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7206. if taicpu(hp1).opcode=A_CVTSD2SS then
  7207. begin
  7208. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7209. taicpu(p).opcode:=A_MOVAPS;
  7210. end
  7211. else
  7212. begin
  7213. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7214. taicpu(p).opcode:=A_VMOVAPS;
  7215. end;
  7216. taicpu(p).ops:=2;
  7217. RemoveInstruction(hp1);
  7218. end;
  7219. Result:=true;
  7220. Exit;
  7221. end;
  7222. end;
  7223. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7224. var
  7225. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7226. ThisReg: TRegister;
  7227. begin
  7228. Result := False;
  7229. if not GetNextInstruction(p,hp1) then
  7230. Exit;
  7231. {
  7232. convert
  7233. j<c> .L1
  7234. mov 1,reg
  7235. jmp .L2
  7236. .L1
  7237. mov 0,reg
  7238. .L2
  7239. into
  7240. mov 0,reg
  7241. set<not(c)> reg
  7242. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7243. would destroy the flag contents
  7244. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7245. executed at the same time as a previous comparison.
  7246. set<not(c)> reg
  7247. movzx reg, reg
  7248. }
  7249. if MatchInstruction(hp1,A_MOV,[]) and
  7250. (taicpu(hp1).oper[0]^.typ = top_const) and
  7251. (
  7252. (
  7253. (taicpu(hp1).oper[1]^.typ = top_reg)
  7254. {$ifdef i386}
  7255. { Under i386, ESI, EDI, EBP and ESP
  7256. don't have an 8-bit representation }
  7257. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7258. {$endif i386}
  7259. ) or (
  7260. {$ifdef i386}
  7261. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7262. {$endif i386}
  7263. (taicpu(hp1).opsize = S_B)
  7264. )
  7265. ) and
  7266. GetNextInstruction(hp1,hp2) and
  7267. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7268. GetNextInstruction(hp2,hp3) and
  7269. SkipAligns(hp3, hp3) and
  7270. (hp3.typ=ait_label) and
  7271. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7272. GetNextInstruction(hp3,hp4) and
  7273. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7274. (taicpu(hp4).oper[0]^.typ = top_const) and
  7275. (
  7276. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7277. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7278. ) and
  7279. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7280. GetNextInstruction(hp4,hp5) and
  7281. SkipAligns(hp5, hp5) and
  7282. (hp5.typ=ait_label) and
  7283. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7284. begin
  7285. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7286. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7287. tai_label(hp3).labsym.DecRefs;
  7288. { If this isn't the only reference to the middle label, we can
  7289. still make a saving - only that the first jump and everything
  7290. that follows will remain. }
  7291. if (tai_label(hp3).labsym.getrefs = 0) then
  7292. begin
  7293. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7294. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7295. else
  7296. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7297. { remove jump, first label and second MOV (also catching any aligns) }
  7298. repeat
  7299. if not GetNextInstruction(hp2, hp3) then
  7300. InternalError(2021040810);
  7301. RemoveInstruction(hp2);
  7302. hp2 := hp3;
  7303. until hp2 = hp5;
  7304. { Don't decrement reference count before the removal loop
  7305. above, otherwise GetNextInstruction won't stop on the
  7306. the label }
  7307. tai_label(hp5).labsym.DecRefs;
  7308. end
  7309. else
  7310. begin
  7311. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7312. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7313. else
  7314. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7315. end;
  7316. taicpu(p).opcode:=A_SETcc;
  7317. taicpu(p).opsize:=S_B;
  7318. taicpu(p).is_jmp:=False;
  7319. if taicpu(hp1).opsize=S_B then
  7320. begin
  7321. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7322. if taicpu(hp1).oper[1]^.typ = top_reg then
  7323. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7324. RemoveInstruction(hp1);
  7325. end
  7326. else
  7327. begin
  7328. { Will be a register because the size can't be S_B otherwise }
  7329. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7330. taicpu(p).loadreg(0, ThisReg);
  7331. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7332. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7333. begin
  7334. case taicpu(hp1).opsize of
  7335. S_W:
  7336. taicpu(hp1).opsize := S_BW;
  7337. S_L:
  7338. taicpu(hp1).opsize := S_BL;
  7339. {$ifdef x86_64}
  7340. S_Q:
  7341. begin
  7342. taicpu(hp1).opsize := S_BL;
  7343. { Change the destination register to 32-bit }
  7344. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7345. end;
  7346. {$endif x86_64}
  7347. else
  7348. InternalError(2021040820);
  7349. end;
  7350. taicpu(hp1).opcode := A_MOVZX;
  7351. taicpu(hp1).loadreg(0, ThisReg);
  7352. end
  7353. else
  7354. begin
  7355. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7356. { hp1 is already a MOV instruction with the correct register }
  7357. taicpu(hp1).loadconst(0, 0);
  7358. { Inserting it right before p will guarantee that the flags are also tracked }
  7359. asml.Remove(hp1);
  7360. asml.InsertBefore(hp1, p);
  7361. end;
  7362. end;
  7363. Result:=true;
  7364. exit;
  7365. end
  7366. else if (hp1.typ = ait_label) then
  7367. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7368. end;
  7369. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7370. var
  7371. hp1, hp2, hp3: tai;
  7372. SourceRef, TargetRef: TReference;
  7373. CurrentReg: TRegister;
  7374. begin
  7375. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7376. if not UseAVX then
  7377. InternalError(2021100501);
  7378. Result := False;
  7379. { Look for the following to simplify:
  7380. vmovdqa/u x(mem1), %xmmreg
  7381. vmovdqa/u %xmmreg, y(mem2)
  7382. vmovdqa/u x+16(mem1), %xmmreg
  7383. vmovdqa/u %xmmreg, y+16(mem2)
  7384. Change to:
  7385. vmovdqa/u x(mem1), %ymmreg
  7386. vmovdqa/u %ymmreg, y(mem2)
  7387. vpxor %ymmreg, %ymmreg, %ymmreg
  7388. ( The VPXOR instruction is to zero the upper half, thus removing the
  7389. need to call the potentially expensive VZEROUPPER instruction. Other
  7390. peephole optimisations can remove VPXOR if it's unnecessary )
  7391. }
  7392. TransferUsedRegs(TmpUsedRegs);
  7393. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7394. { NOTE: In the optimisations below, if the references dictate that an
  7395. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7396. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7397. if (taicpu(p).opsize = S_XMM) and
  7398. MatchOpType(taicpu(p), top_ref, top_reg) and
  7399. GetNextInstruction(p, hp1) and
  7400. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7401. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7402. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7403. begin
  7404. SourceRef := taicpu(p).oper[0]^.ref^;
  7405. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7406. if GetNextInstruction(hp1, hp2) and
  7407. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7408. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7409. begin
  7410. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7411. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7412. Inc(SourceRef.offset, 16);
  7413. { Reuse the register in the first block move }
  7414. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7415. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7416. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7417. begin
  7418. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7419. Inc(TargetRef.offset, 16);
  7420. if GetNextInstruction(hp2, hp3) and
  7421. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7422. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7423. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7424. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7425. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7426. begin
  7427. { Update the register tracking to the new size }
  7428. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7429. { Remember that the offsets are 16 ahead }
  7430. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7431. if not (
  7432. ((SourceRef.offset mod 32) = 16) and
  7433. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7434. ) then
  7435. taicpu(p).opcode := A_VMOVDQU;
  7436. taicpu(p).opsize := S_YMM;
  7437. taicpu(p).oper[1]^.reg := CurrentReg;
  7438. if not (
  7439. ((TargetRef.offset mod 32) = 16) and
  7440. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7441. ) then
  7442. taicpu(hp1).opcode := A_VMOVDQU;
  7443. taicpu(hp1).opsize := S_YMM;
  7444. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7445. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7446. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7447. if (pi_uses_ymm in current_procinfo.flags) then
  7448. RemoveInstruction(hp2)
  7449. else
  7450. begin
  7451. taicpu(hp2).opcode := A_VPXOR;
  7452. taicpu(hp2).opsize := S_YMM;
  7453. taicpu(hp2).loadreg(0, CurrentReg);
  7454. taicpu(hp2).loadreg(1, CurrentReg);
  7455. taicpu(hp2).loadreg(2, CurrentReg);
  7456. taicpu(hp2).ops := 3;
  7457. end;
  7458. RemoveInstruction(hp3);
  7459. Result := True;
  7460. Exit;
  7461. end;
  7462. end
  7463. else
  7464. begin
  7465. { See if the next references are 16 less rather than 16 greater }
  7466. Dec(SourceRef.offset, 32); { -16 the other way }
  7467. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7468. begin
  7469. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7470. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7471. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7472. GetNextInstruction(hp2, hp3) and
  7473. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7474. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7475. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7476. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7477. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7478. begin
  7479. { Update the register tracking to the new size }
  7480. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7481. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7482. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7483. if not(
  7484. ((SourceRef.offset mod 32) = 0) and
  7485. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7486. ) then
  7487. taicpu(hp2).opcode := A_VMOVDQU;
  7488. taicpu(hp2).opsize := S_YMM;
  7489. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7490. if not (
  7491. ((TargetRef.offset mod 32) = 0) and
  7492. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7493. ) then
  7494. taicpu(hp3).opcode := A_VMOVDQU;
  7495. taicpu(hp3).opsize := S_YMM;
  7496. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7497. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7498. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7499. if (pi_uses_ymm in current_procinfo.flags) then
  7500. RemoveInstruction(hp1)
  7501. else
  7502. begin
  7503. taicpu(hp1).opcode := A_VPXOR;
  7504. taicpu(hp1).opsize := S_YMM;
  7505. taicpu(hp1).loadreg(0, CurrentReg);
  7506. taicpu(hp1).loadreg(1, CurrentReg);
  7507. taicpu(hp1).loadreg(2, CurrentReg);
  7508. taicpu(hp1).ops := 3;
  7509. Asml.Remove(hp1);
  7510. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7511. end;
  7512. RemoveCurrentP(p, hp2);
  7513. Result := True;
  7514. Exit;
  7515. end;
  7516. end;
  7517. end;
  7518. end;
  7519. end;
  7520. end;
  7521. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7522. var
  7523. hp2, hp3, first_assignment: tai;
  7524. IncCount, OperIdx: Integer;
  7525. OrigLabel: TAsmLabel;
  7526. begin
  7527. Count := 0;
  7528. Result := False;
  7529. first_assignment := nil;
  7530. if (LoopCount >= 20) then
  7531. begin
  7532. { Guard against infinite loops }
  7533. Exit;
  7534. end;
  7535. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7536. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7537. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7538. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7539. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7540. Exit;
  7541. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7542. {
  7543. change
  7544. jmp .L1
  7545. ...
  7546. .L1:
  7547. mov ##, ## ( multiple movs possible )
  7548. jmp/ret
  7549. into
  7550. mov ##, ##
  7551. jmp/ret
  7552. }
  7553. if not Assigned(hp1) then
  7554. begin
  7555. hp1 := GetLabelWithSym(OrigLabel);
  7556. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7557. Exit;
  7558. end;
  7559. hp2 := hp1;
  7560. while Assigned(hp2) do
  7561. begin
  7562. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7563. SkipLabels(hp2,hp2);
  7564. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7565. Break;
  7566. case taicpu(hp2).opcode of
  7567. A_MOVSS:
  7568. begin
  7569. if taicpu(hp2).ops = 0 then
  7570. { Wrong MOVSS }
  7571. Break;
  7572. Inc(Count);
  7573. if Count >= 5 then
  7574. { Too many to be worthwhile }
  7575. Break;
  7576. GetNextInstruction(hp2, hp2);
  7577. Continue;
  7578. end;
  7579. A_MOV,
  7580. A_MOVD,
  7581. A_MOVQ,
  7582. A_MOVSX,
  7583. {$ifdef x86_64}
  7584. A_MOVSXD,
  7585. {$endif x86_64}
  7586. A_MOVZX,
  7587. A_MOVAPS,
  7588. A_MOVUPS,
  7589. A_MOVSD,
  7590. A_MOVAPD,
  7591. A_MOVUPD,
  7592. A_MOVDQA,
  7593. A_MOVDQU,
  7594. A_VMOVSS,
  7595. A_VMOVAPS,
  7596. A_VMOVUPS,
  7597. A_VMOVSD,
  7598. A_VMOVAPD,
  7599. A_VMOVUPD,
  7600. A_VMOVDQA,
  7601. A_VMOVDQU:
  7602. begin
  7603. Inc(Count);
  7604. if Count >= 5 then
  7605. { Too many to be worthwhile }
  7606. Break;
  7607. GetNextInstruction(hp2, hp2);
  7608. Continue;
  7609. end;
  7610. A_JMP:
  7611. begin
  7612. { Guard against infinite loops }
  7613. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7614. Exit;
  7615. { Analyse this jump first in case it also duplicates assignments }
  7616. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7617. begin
  7618. { Something did change! }
  7619. Result := True;
  7620. Inc(Count, IncCount);
  7621. if Count >= 5 then
  7622. begin
  7623. { Too many to be worthwhile }
  7624. Exit;
  7625. end;
  7626. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7627. Break;
  7628. end;
  7629. Result := True;
  7630. Break;
  7631. end;
  7632. A_RET:
  7633. begin
  7634. Result := True;
  7635. Break;
  7636. end;
  7637. else
  7638. Break;
  7639. end;
  7640. end;
  7641. if Result then
  7642. begin
  7643. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7644. if Count = 0 then
  7645. begin
  7646. Result := False;
  7647. Exit;
  7648. end;
  7649. hp3 := p;
  7650. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7651. while True do
  7652. begin
  7653. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7654. SkipLabels(hp1,hp1);
  7655. if (hp1.typ <> ait_instruction) then
  7656. InternalError(2021040720);
  7657. case taicpu(hp1).opcode of
  7658. A_JMP:
  7659. begin
  7660. { Change the original jump to the new destination }
  7661. OrigLabel.decrefs;
  7662. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7663. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7664. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7665. if not Assigned(first_assignment) then
  7666. InternalError(2021040810)
  7667. else
  7668. p := first_assignment;
  7669. Exit;
  7670. end;
  7671. A_RET:
  7672. begin
  7673. { Now change the jump into a RET instruction }
  7674. ConvertJumpToRET(p, hp1);
  7675. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7676. if not Assigned(first_assignment) then
  7677. InternalError(2021040811)
  7678. else
  7679. p := first_assignment;
  7680. Exit;
  7681. end;
  7682. else
  7683. begin
  7684. { Duplicate the MOV instruction }
  7685. hp3:=tai(hp1.getcopy);
  7686. if first_assignment = nil then
  7687. first_assignment := hp3;
  7688. asml.InsertBefore(hp3, p);
  7689. { Make sure the compiler knows about any final registers written here }
  7690. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7691. with taicpu(hp3).oper[OperIdx]^ do
  7692. begin
  7693. case typ of
  7694. top_ref:
  7695. begin
  7696. if (ref^.base <> NR_NO) and
  7697. (getsupreg(ref^.base) <> RS_ESP) and
  7698. (getsupreg(ref^.base) <> RS_EBP)
  7699. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7700. then
  7701. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7702. if (ref^.index <> NR_NO) and
  7703. (getsupreg(ref^.index) <> RS_ESP) and
  7704. (getsupreg(ref^.index) <> RS_EBP)
  7705. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7706. (ref^.index <> ref^.base) then
  7707. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7708. end;
  7709. top_reg:
  7710. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7711. else
  7712. ;
  7713. end;
  7714. end;
  7715. end;
  7716. end;
  7717. if not GetNextInstruction(hp1, hp1) then
  7718. { Should have dropped out earlier }
  7719. InternalError(2021040710);
  7720. end;
  7721. end;
  7722. end;
  7723. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7724. var
  7725. hp2: tai;
  7726. X: Integer;
  7727. const
  7728. WriteOp: array[0..3] of set of TInsChange = (
  7729. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7730. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7731. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7732. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7733. RegWriteFlags: array[0..7] of set of TInsChange = (
  7734. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7735. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7736. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7737. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7738. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7739. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7740. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7741. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7742. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7743. begin
  7744. { If we have something like:
  7745. cmp ###,%reg1
  7746. mov 0,%reg2
  7747. And no modified registers are shared, move the instruction to before
  7748. the comparison as this means it can be optimised without worrying
  7749. about the FLAGS register. (CMP/MOV is generated by
  7750. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7751. As long as the second instruction doesn't use the flags or one of the
  7752. registers used by CMP or TEST (also check any references that use the
  7753. registers), then it can be moved prior to the comparison.
  7754. }
  7755. Result := False;
  7756. if (hp1.typ <> ait_instruction) or
  7757. taicpu(hp1).is_jmp or
  7758. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7759. Exit;
  7760. { NOP is a pipeline fence, likely marking the beginning of the function
  7761. epilogue, so drop out. Similarly, drop out if POP or RET are
  7762. encountered }
  7763. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7764. Exit;
  7765. if (taicpu(hp1).opcode = A_MOVSS) and
  7766. (taicpu(hp1).ops = 0) then
  7767. { Wrong MOVSS }
  7768. Exit;
  7769. { Check for writes to specific registers first }
  7770. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7771. for X := 0 to 7 do
  7772. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7773. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7774. Exit;
  7775. for X := 0 to taicpu(hp1).ops - 1 do
  7776. begin
  7777. { Check to see if this operand writes to something }
  7778. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7779. { And matches something in the CMP/TEST instruction }
  7780. (
  7781. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7782. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7783. (
  7784. { If it's a register, make sure the register written to doesn't
  7785. appear in the cmp instruction as part of a reference }
  7786. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7787. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7788. )
  7789. ) then
  7790. Exit;
  7791. end;
  7792. { The instruction can be safely moved }
  7793. asml.Remove(hp1);
  7794. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7795. can be optimised into "xor %reg,%reg" later }
  7796. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7797. asml.InsertBefore(hp1, hp2)
  7798. else
  7799. { Note, if p.Previous is nil (even if it should logically never be the
  7800. case), FindRegAllocBackward immediately exits with False and so we
  7801. safely land here (we can't just pass p because FindRegAllocBackward
  7802. immediately exits on an instruction). [Kit] }
  7803. asml.InsertBefore(hp1, p);
  7804. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7805. for X := 0 to taicpu(hp1).ops - 1 do
  7806. case taicpu(hp1).oper[X]^.typ of
  7807. top_reg:
  7808. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7809. top_ref:
  7810. begin
  7811. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7812. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7813. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7814. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7815. end;
  7816. else
  7817. ;
  7818. end;
  7819. if taicpu(hp1).opcode = A_LEA then
  7820. { The flags will be overwritten by the CMP/TEST instruction }
  7821. ConvertLEA(taicpu(hp1));
  7822. Result := True;
  7823. end;
  7824. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7825. function IsXCHGAcceptable: Boolean; inline;
  7826. begin
  7827. { Always accept if optimising for size }
  7828. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7829. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7830. than 3, so it becomes a saving compared to three MOVs with two of
  7831. them able to execute simultaneously. [Kit] }
  7832. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  7833. end;
  7834. var
  7835. NewRef: TReference;
  7836. hp1, hp2, hp3, hp4: Tai;
  7837. {$ifndef x86_64}
  7838. OperIdx: Integer;
  7839. {$endif x86_64}
  7840. NewInstr : Taicpu;
  7841. NewAligh : Tai_align;
  7842. DestLabel: TAsmLabel;
  7843. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7844. var
  7845. NextInstr: tai;
  7846. begin
  7847. Result := False;
  7848. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7849. if not GetNextInstruction(InputInstr, NextInstr) or
  7850. (
  7851. { The FLAGS register isn't always tracked properly, so do not
  7852. perform this optimisation if a conditional statement follows }
  7853. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7854. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7855. ) then
  7856. begin
  7857. reference_reset(NewRef, 1, []);
  7858. NewRef.base := taicpu(p).oper[0]^.reg;
  7859. NewRef.scalefactor := 1;
  7860. if taicpu(InputInstr).opcode = A_ADD then
  7861. begin
  7862. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7863. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7864. end
  7865. else
  7866. begin
  7867. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7868. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7869. end;
  7870. taicpu(p).opcode := A_LEA;
  7871. taicpu(p).loadref(0, NewRef);
  7872. RemoveInstruction(InputInstr);
  7873. Result := True;
  7874. end;
  7875. end;
  7876. begin
  7877. Result:=false;
  7878. { This optimisation adds an instruction, so only do it for speed }
  7879. if not (cs_opt_size in current_settings.optimizerswitches) and
  7880. MatchOpType(taicpu(p), top_const, top_reg) and
  7881. (taicpu(p).oper[0]^.val = 0) then
  7882. begin
  7883. { To avoid compiler warning }
  7884. DestLabel := nil;
  7885. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7886. InternalError(2021040750);
  7887. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7888. Exit;
  7889. case hp1.typ of
  7890. ait_align,
  7891. ait_label:
  7892. begin
  7893. { Change:
  7894. mov $0,%reg mov $0,%reg
  7895. @Lbl1: @Lbl1:
  7896. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7897. je @Lbl2 jne @Lbl2
  7898. To: To:
  7899. mov $0,%reg mov $0,%reg
  7900. jmp @Lbl2 jmp @Lbl3
  7901. (align) (align)
  7902. @Lbl1: @Lbl1:
  7903. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7904. je @Lbl2 je @Lbl2
  7905. @Lbl3: <-- Only if label exists
  7906. (Not if it's optimised for size)
  7907. }
  7908. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  7909. Exit;
  7910. if (hp2.typ = ait_instruction) and
  7911. (
  7912. { Register sizes must exactly match }
  7913. (
  7914. (taicpu(hp2).opcode = A_CMP) and
  7915. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7916. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7917. ) or (
  7918. (taicpu(hp2).opcode = A_TEST) and
  7919. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7920. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7921. )
  7922. ) and GetNextInstruction(hp2, hp3) and
  7923. (hp3.typ = ait_instruction) and
  7924. (taicpu(hp3).opcode = A_JCC) and
  7925. (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
  7926. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7927. begin
  7928. { Check condition of jump }
  7929. { Always true? }
  7930. if condition_in(C_E, taicpu(hp3).condition) then
  7931. begin
  7932. { Copy label symbol and obtain matching label entry for the
  7933. conditional jump, as this will be our destination}
  7934. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7935. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7936. Result := True;
  7937. end
  7938. { Always false? }
  7939. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7940. begin
  7941. { This is only worth it if there's a jump to take }
  7942. case hp2.typ of
  7943. ait_instruction:
  7944. begin
  7945. if taicpu(hp2).opcode = A_JMP then
  7946. begin
  7947. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7948. { An unconditional jump follows the conditional jump which will always be false,
  7949. so use this jump's destination for the new jump }
  7950. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7951. Result := True;
  7952. end
  7953. else if taicpu(hp2).opcode = A_JCC then
  7954. begin
  7955. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7956. if condition_in(C_E, taicpu(hp2).condition) then
  7957. begin
  7958. { A second conditional jump follows the conditional jump which will always be false,
  7959. while the second jump is always True, so use this jump's destination for the new jump }
  7960. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7961. Result := True;
  7962. end;
  7963. { Don't risk it if the jump isn't always true (Result remains False) }
  7964. end;
  7965. end;
  7966. else
  7967. { If anything else don't optimise };
  7968. end;
  7969. end;
  7970. if Result then
  7971. begin
  7972. { Just so we have something to insert as a paremeter}
  7973. reference_reset(NewRef, 1, []);
  7974. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7975. { Now actually load the correct parameter (this also
  7976. increases the reference count) }
  7977. NewInstr.loadsymbol(0, DestLabel, 0);
  7978. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7979. begin
  7980. { Get instruction before original label (may not be p under -O3) }
  7981. if not GetLastInstruction(hp1, hp2) then
  7982. { Shouldn't fail here }
  7983. InternalError(2021040701);
  7984. { Before the aligns too }
  7985. while (hp2.typ = ait_align) do
  7986. if not GetLastInstruction(hp2, hp2) then
  7987. { Shouldn't fail here }
  7988. InternalError(2021040702);
  7989. end
  7990. else
  7991. hp2 := p;
  7992. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7993. AsmL.InsertAfter(NewInstr, hp2);
  7994. { Add new alignment field }
  7995. (* AsmL.InsertAfter(
  7996. cai_align.create_max(
  7997. current_settings.alignment.jumpalign,
  7998. current_settings.alignment.jumpalignskipmax
  7999. ),
  8000. NewInstr
  8001. ); *)
  8002. end;
  8003. Exit;
  8004. end;
  8005. end;
  8006. else
  8007. ;
  8008. end;
  8009. end;
  8010. if not GetNextInstruction(p, hp1) then
  8011. Exit;
  8012. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8013. and DoMovCmpMemOpt(p, hp1, True) then
  8014. begin
  8015. Result := True;
  8016. Exit;
  8017. end
  8018. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8019. begin
  8020. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8021. further, but we can't just put this jump optimisation in pass 1
  8022. because it tends to perform worse when conditional jumps are
  8023. nearby (e.g. when converting CMOV instructions). [Kit] }
  8024. if OptPass2JMP(hp1) then
  8025. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8026. Result := OptPass1MOV(p)
  8027. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8028. returned True and the instruction is still a MOV, thus checking
  8029. the optimisations below }
  8030. { If OptPass2JMP returned False, no optimisations were done to
  8031. the jump and there are no further optimisations that can be done
  8032. to the MOV instruction on this pass }
  8033. end
  8034. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8035. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8036. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8037. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8038. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8039. begin
  8040. { Change:
  8041. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8042. addl/q $x,%reg2 subl/q $x,%reg2
  8043. To:
  8044. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8045. }
  8046. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8047. { be lazy, checking separately for sub would be slightly better }
  8048. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8049. begin
  8050. TransferUsedRegs(TmpUsedRegs);
  8051. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8052. if TryMovArith2Lea(hp1) then
  8053. begin
  8054. Result := True;
  8055. Exit;
  8056. end
  8057. end
  8058. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8059. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8060. { Same as above, but also adds or subtracts to %reg2 in between.
  8061. It's still valid as long as the flags aren't in use }
  8062. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8063. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8064. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8065. { be lazy, checking separately for sub would be slightly better }
  8066. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8067. begin
  8068. TransferUsedRegs(TmpUsedRegs);
  8069. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8070. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8071. if TryMovArith2Lea(hp2) then
  8072. begin
  8073. Result := True;
  8074. Exit;
  8075. end;
  8076. end;
  8077. end
  8078. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8079. {$ifdef x86_64}
  8080. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8081. {$else x86_64}
  8082. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8083. {$endif x86_64}
  8084. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8085. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8086. { mov reg1, reg2 mov reg1, reg2
  8087. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8088. begin
  8089. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8090. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8091. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8092. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8093. TransferUsedRegs(TmpUsedRegs);
  8094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8095. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8096. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8097. then
  8098. begin
  8099. RemoveCurrentP(p, hp1);
  8100. Result:=true;
  8101. end;
  8102. exit;
  8103. end
  8104. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8105. IsXCHGAcceptable and
  8106. { XCHG doesn't support 8-byte registers }
  8107. (taicpu(p).opsize <> S_B) and
  8108. MatchInstruction(hp1, A_MOV, []) and
  8109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8110. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8111. GetNextInstruction(hp1, hp2) and
  8112. MatchInstruction(hp2, A_MOV, []) and
  8113. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8114. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8115. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8116. begin
  8117. { mov %reg1,%reg2
  8118. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8119. mov %reg2,%reg3
  8120. (%reg2 not used afterwards)
  8121. Note that xchg takes 3 cycles to execute, and generally mov's take
  8122. only one cycle apiece, but the first two mov's can be executed in
  8123. parallel, only taking 2 cycles overall. Older processors should
  8124. therefore only optimise for size. [Kit]
  8125. }
  8126. TransferUsedRegs(TmpUsedRegs);
  8127. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8128. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8129. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8130. begin
  8131. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8132. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8133. taicpu(hp1).opcode := A_XCHG;
  8134. RemoveCurrentP(p, hp1);
  8135. RemoveInstruction(hp2);
  8136. Result := True;
  8137. Exit;
  8138. end;
  8139. end
  8140. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8141. MatchInstruction(hp1, A_SAR, []) then
  8142. begin
  8143. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8144. begin
  8145. { the use of %edx also covers the opsize being S_L }
  8146. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8147. begin
  8148. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8149. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8150. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8151. begin
  8152. { Change:
  8153. movl %eax,%edx
  8154. sarl $31,%edx
  8155. To:
  8156. cltd
  8157. }
  8158. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8159. RemoveInstruction(hp1);
  8160. taicpu(p).opcode := A_CDQ;
  8161. taicpu(p).opsize := S_NO;
  8162. taicpu(p).clearop(1);
  8163. taicpu(p).clearop(0);
  8164. taicpu(p).ops:=0;
  8165. Result := True;
  8166. end
  8167. else if (cs_opt_size in current_settings.optimizerswitches) and
  8168. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8169. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8170. begin
  8171. { Change:
  8172. movl %edx,%eax
  8173. sarl $31,%edx
  8174. To:
  8175. movl %edx,%eax
  8176. cltd
  8177. Note that this creates a dependency between the two instructions,
  8178. so only perform if optimising for size.
  8179. }
  8180. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8181. taicpu(hp1).opcode := A_CDQ;
  8182. taicpu(hp1).opsize := S_NO;
  8183. taicpu(hp1).clearop(1);
  8184. taicpu(hp1).clearop(0);
  8185. taicpu(hp1).ops:=0;
  8186. end;
  8187. {$ifndef x86_64}
  8188. end
  8189. { Don't bother if CMOV is supported, because a more optimal
  8190. sequence would have been generated for the Abs() intrinsic }
  8191. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8192. { the use of %eax also covers the opsize being S_L }
  8193. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8194. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8195. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8196. GetNextInstruction(hp1, hp2) and
  8197. MatchInstruction(hp2, A_XOR, [S_L]) and
  8198. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8199. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8200. GetNextInstruction(hp2, hp3) and
  8201. MatchInstruction(hp3, A_SUB, [S_L]) and
  8202. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8203. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8204. begin
  8205. { Change:
  8206. movl %eax,%edx
  8207. sarl $31,%eax
  8208. xorl %eax,%edx
  8209. subl %eax,%edx
  8210. (Instruction that uses %edx)
  8211. (%eax deallocated)
  8212. (%edx deallocated)
  8213. To:
  8214. cltd
  8215. xorl %edx,%eax <-- Note the registers have swapped
  8216. subl %edx,%eax
  8217. (Instruction that uses %eax) <-- %eax rather than %edx
  8218. }
  8219. TransferUsedRegs(TmpUsedRegs);
  8220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8222. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8223. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8224. begin
  8225. if GetNextInstruction(hp3, hp4) and
  8226. not RegModifiedByInstruction(NR_EDX, hp4) and
  8227. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8228. begin
  8229. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8230. taicpu(p).opcode := A_CDQ;
  8231. taicpu(p).clearop(1);
  8232. taicpu(p).clearop(0);
  8233. taicpu(p).ops:=0;
  8234. RemoveInstruction(hp1);
  8235. taicpu(hp2).loadreg(0, NR_EDX);
  8236. taicpu(hp2).loadreg(1, NR_EAX);
  8237. taicpu(hp3).loadreg(0, NR_EDX);
  8238. taicpu(hp3).loadreg(1, NR_EAX);
  8239. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8240. { Convert references in the following instruction (hp4) from %edx to %eax }
  8241. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8242. with taicpu(hp4).oper[OperIdx]^ do
  8243. case typ of
  8244. top_reg:
  8245. if getsupreg(reg) = RS_EDX then
  8246. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8247. top_ref:
  8248. begin
  8249. if getsupreg(reg) = RS_EDX then
  8250. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8251. if getsupreg(reg) = RS_EDX then
  8252. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8253. end;
  8254. else
  8255. ;
  8256. end;
  8257. end;
  8258. end;
  8259. {$else x86_64}
  8260. end;
  8261. end
  8262. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8263. { the use of %rdx also covers the opsize being S_Q }
  8264. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8265. begin
  8266. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8267. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8268. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8269. begin
  8270. { Change:
  8271. movq %rax,%rdx
  8272. sarq $63,%rdx
  8273. To:
  8274. cqto
  8275. }
  8276. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8277. RemoveInstruction(hp1);
  8278. taicpu(p).opcode := A_CQO;
  8279. taicpu(p).opsize := S_NO;
  8280. taicpu(p).clearop(1);
  8281. taicpu(p).clearop(0);
  8282. taicpu(p).ops:=0;
  8283. Result := True;
  8284. end
  8285. else if (cs_opt_size in current_settings.optimizerswitches) and
  8286. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8287. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8288. begin
  8289. { Change:
  8290. movq %rdx,%rax
  8291. sarq $63,%rdx
  8292. To:
  8293. movq %rdx,%rax
  8294. cqto
  8295. Note that this creates a dependency between the two instructions,
  8296. so only perform if optimising for size.
  8297. }
  8298. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8299. taicpu(hp1).opcode := A_CQO;
  8300. taicpu(hp1).opsize := S_NO;
  8301. taicpu(hp1).clearop(1);
  8302. taicpu(hp1).clearop(0);
  8303. taicpu(hp1).ops:=0;
  8304. {$endif x86_64}
  8305. end;
  8306. end;
  8307. end
  8308. else if MatchInstruction(hp1, A_MOV, []) and
  8309. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8310. { Though "GetNextInstruction" could be factored out, along with
  8311. the instructions that depend on hp2, it is an expensive call that
  8312. should be delayed for as long as possible, hence we do cheaper
  8313. checks first that are likely to be False. [Kit] }
  8314. begin
  8315. if (
  8316. (
  8317. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8318. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8319. (
  8320. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8321. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8322. )
  8323. ) or
  8324. (
  8325. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8326. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8327. (
  8328. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8329. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8330. )
  8331. )
  8332. ) and
  8333. GetNextInstruction(hp1, hp2) and
  8334. MatchInstruction(hp2, A_SAR, []) and
  8335. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8336. begin
  8337. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8338. begin
  8339. { Change:
  8340. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8341. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8342. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8343. To:
  8344. movl r/m,%eax <- Note the change in register
  8345. cltd
  8346. }
  8347. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8348. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8349. taicpu(p).loadreg(1, NR_EAX);
  8350. taicpu(hp1).opcode := A_CDQ;
  8351. taicpu(hp1).clearop(1);
  8352. taicpu(hp1).clearop(0);
  8353. taicpu(hp1).ops:=0;
  8354. RemoveInstruction(hp2);
  8355. (*
  8356. {$ifdef x86_64}
  8357. end
  8358. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8359. { This code sequence does not get generated - however it might become useful
  8360. if and when 128-bit signed integer types make an appearance, so the code
  8361. is kept here for when it is eventually needed. [Kit] }
  8362. (
  8363. (
  8364. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8365. (
  8366. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8367. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8368. )
  8369. ) or
  8370. (
  8371. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8372. (
  8373. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8374. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8375. )
  8376. )
  8377. ) and
  8378. GetNextInstruction(hp1, hp2) and
  8379. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8380. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8381. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8382. begin
  8383. { Change:
  8384. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8385. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8386. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8387. To:
  8388. movq r/m,%rax <- Note the change in register
  8389. cqto
  8390. }
  8391. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8392. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8393. taicpu(p).loadreg(1, NR_RAX);
  8394. taicpu(hp1).opcode := A_CQO;
  8395. taicpu(hp1).clearop(1);
  8396. taicpu(hp1).clearop(0);
  8397. taicpu(hp1).ops:=0;
  8398. RemoveInstruction(hp2);
  8399. {$endif x86_64}
  8400. *)
  8401. end;
  8402. end;
  8403. {$ifdef x86_64}
  8404. end
  8405. else if (taicpu(p).opsize = S_L) and
  8406. (taicpu(p).oper[1]^.typ = top_reg) and
  8407. (
  8408. MatchInstruction(hp1, A_MOV,[]) and
  8409. (taicpu(hp1).opsize = S_L) and
  8410. (taicpu(hp1).oper[1]^.typ = top_reg)
  8411. ) and (
  8412. GetNextInstruction(hp1, hp2) and
  8413. (tai(hp2).typ=ait_instruction) and
  8414. (taicpu(hp2).opsize = S_Q) and
  8415. (
  8416. (
  8417. MatchInstruction(hp2, A_ADD,[]) and
  8418. (taicpu(hp2).opsize = S_Q) and
  8419. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8420. (
  8421. (
  8422. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8423. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8424. ) or (
  8425. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8426. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8427. )
  8428. )
  8429. ) or (
  8430. MatchInstruction(hp2, A_LEA,[]) and
  8431. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8432. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8433. (
  8434. (
  8435. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8436. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8437. ) or (
  8438. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8439. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8440. )
  8441. ) and (
  8442. (
  8443. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8444. ) or (
  8445. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8446. )
  8447. )
  8448. )
  8449. )
  8450. ) and (
  8451. GetNextInstruction(hp2, hp3) and
  8452. MatchInstruction(hp3, A_SHR,[]) and
  8453. (taicpu(hp3).opsize = S_Q) and
  8454. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8455. (taicpu(hp3).oper[0]^.val = 1) and
  8456. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8457. ) then
  8458. begin
  8459. { Change movl x, reg1d movl x, reg1d
  8460. movl y, reg2d movl y, reg2d
  8461. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8462. shrq $1, reg1q shrq $1, reg1q
  8463. ( reg1d and reg2d can be switched around in the first two instructions )
  8464. To movl x, reg1d
  8465. addl y, reg1d
  8466. rcrl $1, reg1d
  8467. This corresponds to the common expression (x + y) shr 1, where
  8468. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8469. smaller code, but won't account for x + y causing an overflow). [Kit]
  8470. }
  8471. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8472. { Change first MOV command to have the same register as the final output }
  8473. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8474. else
  8475. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8476. { Change second MOV command to an ADD command. This is easier than
  8477. converting the existing command because it means we don't have to
  8478. touch 'y', which might be a complicated reference, and also the
  8479. fact that the third command might either be ADD or LEA. [Kit] }
  8480. taicpu(hp1).opcode := A_ADD;
  8481. { Delete old ADD/LEA instruction }
  8482. RemoveInstruction(hp2);
  8483. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8484. taicpu(hp3).opcode := A_RCR;
  8485. taicpu(hp3).changeopsize(S_L);
  8486. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8487. {$endif x86_64}
  8488. end;
  8489. if FuncMov2Func(p, hp1) then
  8490. begin
  8491. Result := True;
  8492. Exit;
  8493. end;
  8494. end;
  8495. {$push}
  8496. {$q-}{$r-}
  8497. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8498. var
  8499. ThisReg: TRegister;
  8500. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8501. TargetSubReg: TSubRegister;
  8502. hp1, hp2: tai;
  8503. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8504. { Store list of found instructions so we don't have to call
  8505. GetNextInstructionUsingReg multiple times }
  8506. InstrList: array of taicpu;
  8507. InstrMax, Index: Integer;
  8508. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8509. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8510. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8511. WorkingValue: TCgInt;
  8512. PreMessage: string;
  8513. { Data flow analysis }
  8514. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8515. BitwiseOnly, OrXorUsed,
  8516. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8517. function CheckOverflowConditions: Boolean;
  8518. begin
  8519. Result := True;
  8520. if (TestValSignedMax > SignedUpperLimit) then
  8521. UpperSignedOverflow := True;
  8522. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8523. LowerSignedOverflow := True;
  8524. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8525. LowerUnsignedOverflow := True;
  8526. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8527. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8528. begin
  8529. { Absolute overflow }
  8530. Result := False;
  8531. Exit;
  8532. end;
  8533. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8534. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8535. ShiftDownOverflow := True;
  8536. if (TestValMin < 0) or (TestValMax < 0) then
  8537. begin
  8538. LowerUnsignedOverflow := True;
  8539. UpperUnsignedOverflow := True;
  8540. end;
  8541. end;
  8542. function AdjustInitialLoadAndSize: Boolean;
  8543. begin
  8544. Result := False;
  8545. if not p_removed then
  8546. begin
  8547. if TargetSize = MinSize then
  8548. begin
  8549. { Convert the input MOVZX to a MOV }
  8550. if (taicpu(p).oper[0]^.typ = top_reg) and
  8551. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8552. begin
  8553. { Or remove it completely! }
  8554. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8555. RemoveCurrentP(p);
  8556. p_removed := True;
  8557. end
  8558. else
  8559. begin
  8560. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8561. taicpu(p).opcode := A_MOV;
  8562. taicpu(p).oper[1]^.reg := ThisReg;
  8563. taicpu(p).opsize := TargetSize;
  8564. end;
  8565. Result := True;
  8566. end
  8567. else if TargetSize <> MaxSize then
  8568. begin
  8569. case MaxSize of
  8570. S_L:
  8571. if TargetSize = S_W then
  8572. begin
  8573. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8574. taicpu(p).opsize := S_BW;
  8575. taicpu(p).oper[1]^.reg := ThisReg;
  8576. Result := True;
  8577. end
  8578. else
  8579. InternalError(2020112341);
  8580. S_W:
  8581. if TargetSize = S_L then
  8582. begin
  8583. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8584. taicpu(p).opsize := S_BL;
  8585. taicpu(p).oper[1]^.reg := ThisReg;
  8586. Result := True;
  8587. end
  8588. else
  8589. InternalError(2020112342);
  8590. else
  8591. ;
  8592. end;
  8593. end
  8594. else if not hp1_removed and not RegInUse then
  8595. begin
  8596. { If we have something like:
  8597. movzbl (oper),%regd
  8598. add x, %regd
  8599. movzbl %regb, %regd
  8600. We can reduce the register size to the input of the final
  8601. movzbl instruction. Overflows won't have any effect.
  8602. }
  8603. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8604. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8605. begin
  8606. TargetSize := S_B;
  8607. setsubreg(ThisReg, R_SUBL);
  8608. Result := True;
  8609. end
  8610. else if (taicpu(p).opsize = S_WL) and
  8611. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8612. begin
  8613. TargetSize := S_W;
  8614. setsubreg(ThisReg, R_SUBW);
  8615. Result := True;
  8616. end;
  8617. if Result then
  8618. begin
  8619. { Convert the input MOVZX to a MOV }
  8620. if (taicpu(p).oper[0]^.typ = top_reg) and
  8621. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8622. begin
  8623. { Or remove it completely! }
  8624. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8625. RemoveCurrentP(p);
  8626. p_removed := True;
  8627. end
  8628. else
  8629. begin
  8630. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8631. taicpu(p).opcode := A_MOV;
  8632. taicpu(p).oper[1]^.reg := ThisReg;
  8633. taicpu(p).opsize := TargetSize;
  8634. end;
  8635. end;
  8636. end;
  8637. end;
  8638. end;
  8639. procedure AdjustFinalLoad;
  8640. begin
  8641. if not LowerUnsignedOverflow then
  8642. begin
  8643. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8644. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8645. begin
  8646. { Convert the output MOVZX to a MOV }
  8647. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8648. begin
  8649. { Or remove it completely! }
  8650. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8651. { Be careful; if p = hp1 and p was also removed, p
  8652. will become a dangling pointer }
  8653. if p = hp1 then
  8654. begin
  8655. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8656. p_removed := True;
  8657. end
  8658. else
  8659. RemoveInstruction(hp1);
  8660. hp1_removed := True;
  8661. end
  8662. else
  8663. begin
  8664. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8665. taicpu(hp1).opcode := A_MOV;
  8666. taicpu(hp1).oper[0]^.reg := ThisReg;
  8667. taicpu(hp1).opsize := TargetSize;
  8668. end;
  8669. end
  8670. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8671. begin
  8672. { Need to change the size of the output }
  8673. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8674. taicpu(hp1).oper[0]^.reg := ThisReg;
  8675. taicpu(hp1).opsize := S_BL;
  8676. end;
  8677. end;
  8678. end;
  8679. function CompressInstructions: Boolean;
  8680. var
  8681. LocalIndex: Integer;
  8682. begin
  8683. Result := False;
  8684. { The objective here is to try to find a combination that
  8685. removes one of the MOV/Z instructions. }
  8686. if (
  8687. (taicpu(p).oper[0]^.typ <> top_reg) or
  8688. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8689. ) and
  8690. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8691. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8692. begin
  8693. { Make a preference to remove the second MOVZX instruction }
  8694. case taicpu(hp1).opsize of
  8695. S_BL, S_WL:
  8696. begin
  8697. TargetSize := S_L;
  8698. TargetSubReg := R_SUBD;
  8699. end;
  8700. S_BW:
  8701. begin
  8702. TargetSize := S_W;
  8703. TargetSubReg := R_SUBW;
  8704. end;
  8705. else
  8706. InternalError(2020112302);
  8707. end;
  8708. end
  8709. else
  8710. begin
  8711. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8712. begin
  8713. { Exceeded lower bound but not upper bound }
  8714. TargetSize := MaxSize;
  8715. end
  8716. else if not LowerUnsignedOverflow then
  8717. begin
  8718. { Size didn't exceed lower bound }
  8719. TargetSize := MinSize;
  8720. end
  8721. else
  8722. Exit;
  8723. end;
  8724. case TargetSize of
  8725. S_B:
  8726. TargetSubReg := R_SUBL;
  8727. S_W:
  8728. TargetSubReg := R_SUBW;
  8729. S_L:
  8730. TargetSubReg := R_SUBD;
  8731. else
  8732. InternalError(2020112350);
  8733. end;
  8734. { Update the register to its new size }
  8735. setsubreg(ThisReg, TargetSubReg);
  8736. RegInUse := False;
  8737. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8738. begin
  8739. { Check to see if the active register is used afterwards;
  8740. if not, we can change it and make a saving. }
  8741. TransferUsedRegs(TmpUsedRegs);
  8742. { The target register may be marked as in use to cross
  8743. a jump to a distant label, so exclude it }
  8744. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8745. hp2 := p;
  8746. repeat
  8747. { Explicitly check for the excluded register (don't include the first
  8748. instruction as it may be reading from here }
  8749. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8750. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8751. begin
  8752. RegInUse := True;
  8753. Break;
  8754. end;
  8755. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8756. if not GetNextInstruction(hp2, hp2) then
  8757. InternalError(2020112340);
  8758. until (hp2 = hp1);
  8759. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8760. { We might still be able to get away with this }
  8761. RegInUse := not
  8762. (
  8763. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8764. (hp2.typ = ait_instruction) and
  8765. (
  8766. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8767. instruction that doesn't actually contain ThisReg }
  8768. (cs_opt_level3 in current_settings.optimizerswitches) or
  8769. RegInInstruction(ThisReg, hp2)
  8770. ) and
  8771. RegLoadedWithNewValue(ThisReg, hp2)
  8772. );
  8773. if not RegInUse then
  8774. begin
  8775. { Force the register size to the same as this instruction so it can be removed}
  8776. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8777. begin
  8778. TargetSize := S_L;
  8779. TargetSubReg := R_SUBD;
  8780. end
  8781. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8782. begin
  8783. TargetSize := S_W;
  8784. TargetSubReg := R_SUBW;
  8785. end;
  8786. ThisReg := taicpu(hp1).oper[1]^.reg;
  8787. setsubreg(ThisReg, TargetSubReg);
  8788. RegChanged := True;
  8789. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8790. TransferUsedRegs(TmpUsedRegs);
  8791. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8792. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8793. if p = hp1 then
  8794. begin
  8795. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8796. p_removed := True;
  8797. end
  8798. else
  8799. RemoveInstruction(hp1);
  8800. hp1_removed := True;
  8801. { Instruction will become "mov %reg,%reg" }
  8802. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8803. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8804. begin
  8805. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8806. RemoveCurrentP(p);
  8807. p_removed := True;
  8808. end
  8809. else
  8810. taicpu(p).oper[1]^.reg := ThisReg;
  8811. Result := True;
  8812. end
  8813. else
  8814. begin
  8815. if TargetSize <> MaxSize then
  8816. begin
  8817. { Since the register is in use, we have to force it to
  8818. MaxSize otherwise part of it may become undefined later on }
  8819. TargetSize := MaxSize;
  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(2020112351);
  8829. end;
  8830. setsubreg(ThisReg, TargetSubReg);
  8831. end;
  8832. AdjustFinalLoad;
  8833. end;
  8834. end
  8835. else
  8836. AdjustFinalLoad;
  8837. Result := AdjustInitialLoadAndSize or Result;
  8838. { Now go through every instruction we found and change the
  8839. size. If TargetSize = MaxSize, then almost no changes are
  8840. needed and Result can remain False if it hasn't been set
  8841. yet.
  8842. If RegChanged is True, then the register requires changing
  8843. and so the point about TargetSize = MaxSize doesn't apply. }
  8844. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8845. begin
  8846. for LocalIndex := 0 to InstrMax do
  8847. begin
  8848. { If p_removed is true, then the original MOV/Z was removed
  8849. and removing the AND instruction may not be safe if it
  8850. appears first }
  8851. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8852. InternalError(2020112310);
  8853. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8854. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8855. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8856. InstrList[LocalIndex].opsize := TargetSize;
  8857. end;
  8858. Result := True;
  8859. end;
  8860. end;
  8861. begin
  8862. Result := False;
  8863. p_removed := False;
  8864. hp1_removed := False;
  8865. ThisReg := taicpu(p).oper[1]^.reg;
  8866. { Check for:
  8867. movs/z ###,%ecx (or %cx or %rcx)
  8868. ...
  8869. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8870. (dealloc %ecx)
  8871. Change to:
  8872. mov ###,%cl (if ### = %cl, then remove completely)
  8873. ...
  8874. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8875. }
  8876. if (getsupreg(ThisReg) = RS_ECX) and
  8877. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8878. (hp1.typ = ait_instruction) and
  8879. (
  8880. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8881. instruction that doesn't actually contain ECX }
  8882. (cs_opt_level3 in current_settings.optimizerswitches) or
  8883. RegInInstruction(NR_ECX, hp1) or
  8884. (
  8885. { It's common for the shift/rotate's read/write register to be
  8886. initialised in between, so under -O2 and under, search ahead
  8887. one more instruction
  8888. }
  8889. GetNextInstruction(hp1, hp1) and
  8890. (hp1.typ = ait_instruction) and
  8891. RegInInstruction(NR_ECX, hp1)
  8892. )
  8893. ) and
  8894. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8895. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8896. begin
  8897. TransferUsedRegs(TmpUsedRegs);
  8898. hp2 := p;
  8899. repeat
  8900. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8901. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8902. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8903. begin
  8904. case taicpu(p).opsize of
  8905. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8906. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8907. begin
  8908. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8909. RemoveCurrentP(p);
  8910. end
  8911. else
  8912. begin
  8913. taicpu(p).opcode := A_MOV;
  8914. taicpu(p).opsize := S_B;
  8915. taicpu(p).oper[1]^.reg := NR_CL;
  8916. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8917. end;
  8918. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8919. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8920. begin
  8921. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8922. RemoveCurrentP(p);
  8923. end
  8924. else
  8925. begin
  8926. taicpu(p).opcode := A_MOV;
  8927. taicpu(p).opsize := S_W;
  8928. taicpu(p).oper[1]^.reg := NR_CX;
  8929. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8930. end;
  8931. {$ifdef x86_64}
  8932. S_LQ:
  8933. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8934. begin
  8935. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8936. RemoveCurrentP(p);
  8937. end
  8938. else
  8939. begin
  8940. taicpu(p).opcode := A_MOV;
  8941. taicpu(p).opsize := S_L;
  8942. taicpu(p).oper[1]^.reg := NR_ECX;
  8943. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8944. end;
  8945. {$endif x86_64}
  8946. else
  8947. InternalError(2021120401);
  8948. end;
  8949. Result := True;
  8950. Exit;
  8951. end;
  8952. end;
  8953. { This is anything but quick! }
  8954. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8955. Exit;
  8956. SetLength(InstrList, 0);
  8957. InstrMax := -1;
  8958. case taicpu(p).opsize of
  8959. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8960. begin
  8961. {$if defined(i386) or defined(i8086)}
  8962. { If the target size is 8-bit, make sure we can actually encode it }
  8963. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8964. Exit;
  8965. {$endif i386 or i8086}
  8966. LowerLimit := $FF;
  8967. SignedLowerLimit := $7F;
  8968. SignedLowerLimitBottom := -128;
  8969. MinSize := S_B;
  8970. if taicpu(p).opsize = S_BW then
  8971. begin
  8972. MaxSize := S_W;
  8973. UpperLimit := $FFFF;
  8974. SignedUpperLimit := $7FFF;
  8975. SignedUpperLimitBottom := -32768;
  8976. end
  8977. else
  8978. begin
  8979. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8980. MaxSize := S_L;
  8981. UpperLimit := $FFFFFFFF;
  8982. SignedUpperLimit := $7FFFFFFF;
  8983. SignedUpperLimitBottom := -2147483648;
  8984. end;
  8985. end;
  8986. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8987. begin
  8988. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8989. LowerLimit := $FFFF;
  8990. SignedLowerLimit := $7FFF;
  8991. SignedLowerLimitBottom := -32768;
  8992. UpperLimit := $FFFFFFFF;
  8993. SignedUpperLimit := $7FFFFFFF;
  8994. SignedUpperLimitBottom := -2147483648;
  8995. MinSize := S_W;
  8996. MaxSize := S_L;
  8997. end;
  8998. {$ifdef x86_64}
  8999. S_LQ:
  9000. begin
  9001. { Both the lower and upper limits are set to 32-bit. If a limit
  9002. is breached, then optimisation is impossible }
  9003. LowerLimit := $FFFFFFFF;
  9004. SignedLowerLimit := $7FFFFFFF;
  9005. SignedLowerLimitBottom := -2147483648;
  9006. UpperLimit := $FFFFFFFF;
  9007. SignedUpperLimit := $7FFFFFFF;
  9008. SignedUpperLimitBottom := -2147483648;
  9009. MinSize := S_L;
  9010. MaxSize := S_L;
  9011. end;
  9012. {$endif x86_64}
  9013. else
  9014. InternalError(2020112301);
  9015. end;
  9016. TestValMin := 0;
  9017. TestValMax := LowerLimit;
  9018. TestValSignedMax := SignedLowerLimit;
  9019. TryShiftDownLimit := LowerLimit;
  9020. TryShiftDown := S_NO;
  9021. ShiftDownOverflow := False;
  9022. RegChanged := False;
  9023. BitwiseOnly := True;
  9024. OrXorUsed := False;
  9025. UpperSignedOverflow := False;
  9026. LowerSignedOverflow := False;
  9027. UpperUnsignedOverflow := False;
  9028. LowerUnsignedOverflow := False;
  9029. hp1 := p;
  9030. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9031. (hp1.typ = ait_instruction) and
  9032. (
  9033. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9034. instruction that doesn't actually contain ThisReg }
  9035. (cs_opt_level3 in current_settings.optimizerswitches) or
  9036. { This allows this Movx optimisation to work through the SETcc instructions
  9037. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9038. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9039. skip over these SETcc instructions). }
  9040. (taicpu(hp1).opcode = A_SETcc) or
  9041. RegInInstruction(ThisReg, hp1)
  9042. ) do
  9043. begin
  9044. case taicpu(hp1).opcode of
  9045. A_INC,A_DEC:
  9046. begin
  9047. { Has to be an exact match on the register }
  9048. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9049. Break;
  9050. if taicpu(hp1).opcode = A_INC then
  9051. begin
  9052. Inc(TestValMin);
  9053. Inc(TestValMax);
  9054. Inc(TestValSignedMax);
  9055. end
  9056. else
  9057. begin
  9058. Dec(TestValMin);
  9059. Dec(TestValMax);
  9060. Dec(TestValSignedMax);
  9061. end;
  9062. end;
  9063. A_TEST, A_CMP:
  9064. begin
  9065. if (
  9066. { Too high a risk of non-linear behaviour that breaks DFA
  9067. here, unless it's cmp $0,%reg, which is equivalent to
  9068. test %reg,%reg }
  9069. OrXorUsed and
  9070. (taicpu(hp1).opcode = A_CMP) and
  9071. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9072. ) or
  9073. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9074. { Has to be an exact match on the register }
  9075. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9076. (
  9077. { Permit "test %reg,%reg" }
  9078. (taicpu(hp1).opcode = A_TEST) and
  9079. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9080. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9081. ) or
  9082. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9083. { Make sure the comparison value is not smaller than the
  9084. smallest allowed signed value for the minimum size (e.g.
  9085. -128 for 8-bit) }
  9086. not (
  9087. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9088. { Is it in the negative range? }
  9089. (
  9090. (taicpu(hp1).oper[0]^.val < 0) and
  9091. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9092. )
  9093. ) then
  9094. Break;
  9095. { Check to see if the active register is used afterwards }
  9096. TransferUsedRegs(TmpUsedRegs);
  9097. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9098. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9099. begin
  9100. { Make sure the comparison or any previous instructions
  9101. hasn't pushed the test values outside of the range of
  9102. MinSize }
  9103. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9104. begin
  9105. { Exceeded lower bound but not upper bound }
  9106. Exit;
  9107. end
  9108. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9109. begin
  9110. { Size didn't exceed lower bound }
  9111. TargetSize := MinSize;
  9112. end
  9113. else
  9114. Break;
  9115. case TargetSize of
  9116. S_B:
  9117. TargetSubReg := R_SUBL;
  9118. S_W:
  9119. TargetSubReg := R_SUBW;
  9120. S_L:
  9121. TargetSubReg := R_SUBD;
  9122. else
  9123. InternalError(2021051002);
  9124. end;
  9125. if TargetSize <> MaxSize then
  9126. begin
  9127. { Update the register to its new size }
  9128. setsubreg(ThisReg, TargetSubReg);
  9129. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9130. taicpu(hp1).oper[1]^.reg := ThisReg;
  9131. taicpu(hp1).opsize := TargetSize;
  9132. { Convert the input MOVZX to a MOV if necessary }
  9133. AdjustInitialLoadAndSize;
  9134. if (InstrMax >= 0) then
  9135. begin
  9136. for Index := 0 to InstrMax do
  9137. begin
  9138. { If p_removed is true, then the original MOV/Z was removed
  9139. and removing the AND instruction may not be safe if it
  9140. appears first }
  9141. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9142. InternalError(2020112311);
  9143. if InstrList[Index].oper[0]^.typ = top_reg then
  9144. InstrList[Index].oper[0]^.reg := ThisReg;
  9145. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9146. InstrList[Index].opsize := MinSize;
  9147. end;
  9148. end;
  9149. Result := True;
  9150. end;
  9151. Exit;
  9152. end;
  9153. end;
  9154. A_SETcc:
  9155. begin
  9156. { This allows this Movx optimisation to work through the SETcc instructions
  9157. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9158. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9159. skip over these SETcc instructions). }
  9160. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9161. { Of course, break out if the current register is used }
  9162. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9163. Break
  9164. else
  9165. { We must use Continue so the instruction doesn't get added
  9166. to InstrList }
  9167. Continue;
  9168. end;
  9169. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9170. begin
  9171. if
  9172. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9173. { Has to be an exact match on the register }
  9174. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9175. (
  9176. (
  9177. (taicpu(hp1).oper[0]^.typ = top_const) and
  9178. (
  9179. (
  9180. (taicpu(hp1).opcode = A_SHL) and
  9181. (
  9182. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9183. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9184. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9185. )
  9186. ) or (
  9187. (taicpu(hp1).opcode <> A_SHL) and
  9188. (
  9189. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9190. { Is it in the negative range? }
  9191. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9192. )
  9193. )
  9194. )
  9195. ) or (
  9196. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9197. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9198. )
  9199. ) then
  9200. Break;
  9201. { Only process OR and XOR if there are only bitwise operations,
  9202. since otherwise they can too easily fool the data flow
  9203. analysis (they can cause non-linear behaviour) }
  9204. case taicpu(hp1).opcode of
  9205. A_ADD:
  9206. begin
  9207. if OrXorUsed then
  9208. { Too high a risk of non-linear behaviour that breaks DFA here }
  9209. Break
  9210. else
  9211. BitwiseOnly := False;
  9212. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9213. begin
  9214. TestValMin := TestValMin * 2;
  9215. TestValMax := TestValMax * 2;
  9216. TestValSignedMax := TestValSignedMax * 2;
  9217. end
  9218. else
  9219. begin
  9220. WorkingValue := taicpu(hp1).oper[0]^.val;
  9221. TestValMin := TestValMin + WorkingValue;
  9222. TestValMax := TestValMax + WorkingValue;
  9223. TestValSignedMax := TestValSignedMax + WorkingValue;
  9224. end;
  9225. end;
  9226. A_SUB:
  9227. begin
  9228. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9229. begin
  9230. TestValMin := 0;
  9231. TestValMax := 0;
  9232. TestValSignedMax := 0;
  9233. end
  9234. else
  9235. begin
  9236. if OrXorUsed then
  9237. { Too high a risk of non-linear behaviour that breaks DFA here }
  9238. Break
  9239. else
  9240. BitwiseOnly := False;
  9241. WorkingValue := taicpu(hp1).oper[0]^.val;
  9242. TestValMin := TestValMin - WorkingValue;
  9243. TestValMax := TestValMax - WorkingValue;
  9244. TestValSignedMax := TestValSignedMax - WorkingValue;
  9245. end;
  9246. end;
  9247. A_AND:
  9248. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9249. begin
  9250. { we might be able to go smaller if AND appears first }
  9251. if InstrMax = -1 then
  9252. case MinSize of
  9253. S_B:
  9254. ;
  9255. S_W:
  9256. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9257. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9258. begin
  9259. TryShiftDown := S_B;
  9260. TryShiftDownLimit := $FF;
  9261. end;
  9262. S_L:
  9263. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9264. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9265. begin
  9266. TryShiftDown := S_B;
  9267. TryShiftDownLimit := $FF;
  9268. end
  9269. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9270. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9271. begin
  9272. TryShiftDown := S_W;
  9273. TryShiftDownLimit := $FFFF;
  9274. end;
  9275. else
  9276. InternalError(2020112320);
  9277. end;
  9278. WorkingValue := taicpu(hp1).oper[0]^.val;
  9279. TestValMin := TestValMin and WorkingValue;
  9280. TestValMax := TestValMax and WorkingValue;
  9281. TestValSignedMax := TestValSignedMax and WorkingValue;
  9282. end;
  9283. A_OR:
  9284. begin
  9285. if not BitwiseOnly then
  9286. Break;
  9287. OrXorUsed := True;
  9288. WorkingValue := taicpu(hp1).oper[0]^.val;
  9289. TestValMin := TestValMin or WorkingValue;
  9290. TestValMax := TestValMax or WorkingValue;
  9291. TestValSignedMax := TestValSignedMax or WorkingValue;
  9292. end;
  9293. A_XOR:
  9294. begin
  9295. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9296. begin
  9297. TestValMin := 0;
  9298. TestValMax := 0;
  9299. TestValSignedMax := 0;
  9300. end
  9301. else
  9302. begin
  9303. if not BitwiseOnly then
  9304. Break;
  9305. OrXorUsed := True;
  9306. WorkingValue := taicpu(hp1).oper[0]^.val;
  9307. TestValMin := TestValMin xor WorkingValue;
  9308. TestValMax := TestValMax xor WorkingValue;
  9309. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9310. end;
  9311. end;
  9312. A_SHL:
  9313. begin
  9314. BitwiseOnly := False;
  9315. WorkingValue := taicpu(hp1).oper[0]^.val;
  9316. TestValMin := TestValMin shl WorkingValue;
  9317. TestValMax := TestValMax shl WorkingValue;
  9318. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9319. end;
  9320. A_SHR,
  9321. { The first instruction was MOVZX, so the value won't be negative }
  9322. A_SAR:
  9323. begin
  9324. if InstrMax <> -1 then
  9325. BitwiseOnly := False
  9326. else
  9327. { we might be able to go smaller if SHR appears first }
  9328. case MinSize of
  9329. S_B:
  9330. ;
  9331. S_W:
  9332. if (taicpu(hp1).oper[0]^.val >= 8) then
  9333. begin
  9334. TryShiftDown := S_B;
  9335. TryShiftDownLimit := $FF;
  9336. TryShiftDownSignedLimit := $7F;
  9337. TryShiftDownSignedLimitLower := -128;
  9338. end;
  9339. S_L:
  9340. if (taicpu(hp1).oper[0]^.val >= 24) then
  9341. begin
  9342. TryShiftDown := S_B;
  9343. TryShiftDownLimit := $FF;
  9344. TryShiftDownSignedLimit := $7F;
  9345. TryShiftDownSignedLimitLower := -128;
  9346. end
  9347. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9348. begin
  9349. TryShiftDown := S_W;
  9350. TryShiftDownLimit := $FFFF;
  9351. TryShiftDownSignedLimit := $7FFF;
  9352. TryShiftDownSignedLimitLower := -32768;
  9353. end;
  9354. else
  9355. InternalError(2020112321);
  9356. end;
  9357. WorkingValue := taicpu(hp1).oper[0]^.val;
  9358. if taicpu(hp1).opcode = A_SAR then
  9359. begin
  9360. TestValMin := SarInt64(TestValMin, WorkingValue);
  9361. TestValMax := SarInt64(TestValMax, WorkingValue);
  9362. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9363. end
  9364. else
  9365. begin
  9366. TestValMin := TestValMin shr WorkingValue;
  9367. TestValMax := TestValMax shr WorkingValue;
  9368. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9369. end;
  9370. end;
  9371. else
  9372. InternalError(2020112303);
  9373. end;
  9374. end;
  9375. (*
  9376. A_IMUL:
  9377. case taicpu(hp1).ops of
  9378. 2:
  9379. begin
  9380. if not MatchOpType(hp1, top_reg, top_reg) or
  9381. { Has to be an exact match on the register }
  9382. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9383. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9384. Break;
  9385. TestValMin := TestValMin * TestValMin;
  9386. TestValMax := TestValMax * TestValMax;
  9387. TestValSignedMax := TestValSignedMax * TestValMax;
  9388. end;
  9389. 3:
  9390. begin
  9391. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9392. { Has to be an exact match on the register }
  9393. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9394. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9395. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9396. { Is it in the negative range? }
  9397. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9398. Break;
  9399. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9400. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9401. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9402. end;
  9403. else
  9404. Break;
  9405. end;
  9406. A_IDIV:
  9407. case taicpu(hp1).ops of
  9408. 3:
  9409. begin
  9410. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9411. { Has to be an exact match on the register }
  9412. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9413. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9414. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9415. { Is it in the negative range? }
  9416. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9417. Break;
  9418. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9419. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9420. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9421. end;
  9422. else
  9423. Break;
  9424. end;
  9425. *)
  9426. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9427. begin
  9428. { If there are no instructions in between, then we might be able to make a saving }
  9429. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9430. Break;
  9431. { We have something like:
  9432. movzbw %dl,%dx
  9433. ...
  9434. movswl %dx,%edx
  9435. Change the latter to a zero-extension then enter the
  9436. A_MOVZX case branch.
  9437. }
  9438. {$ifdef x86_64}
  9439. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9440. begin
  9441. { this becomes a zero extension from 32-bit to 64-bit, but
  9442. the upper 32 bits are already zero, so just delete the
  9443. instruction }
  9444. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9445. RemoveInstruction(hp1);
  9446. Result := True;
  9447. Exit;
  9448. end
  9449. else
  9450. {$endif x86_64}
  9451. begin
  9452. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9453. taicpu(hp1).opcode := A_MOVZX;
  9454. {$ifdef x86_64}
  9455. case taicpu(hp1).opsize of
  9456. S_BQ:
  9457. begin
  9458. taicpu(hp1).opsize := S_BL;
  9459. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9460. end;
  9461. S_WQ:
  9462. begin
  9463. taicpu(hp1).opsize := S_WL;
  9464. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9465. end;
  9466. S_LQ:
  9467. begin
  9468. taicpu(hp1).opcode := A_MOV;
  9469. taicpu(hp1).opsize := S_L;
  9470. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9471. { In this instance, we need to break out because the
  9472. instruction is no longer MOVZX or MOVSXD }
  9473. Result := True;
  9474. Exit;
  9475. end;
  9476. else
  9477. ;
  9478. end;
  9479. {$endif x86_64}
  9480. Result := CompressInstructions;
  9481. Exit;
  9482. end;
  9483. end;
  9484. A_MOVZX:
  9485. begin
  9486. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9487. Break;
  9488. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9489. begin
  9490. if (InstrMax = -1) and
  9491. { Will return false if the second parameter isn't ThisReg
  9492. (can happen on -O2 and under) }
  9493. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9494. begin
  9495. { The two MOVZX instructions are adjacent, so remove the first one }
  9496. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9497. RemoveCurrentP(p);
  9498. Result := True;
  9499. Exit;
  9500. end;
  9501. Break;
  9502. end;
  9503. Result := CompressInstructions;
  9504. Exit;
  9505. end;
  9506. else
  9507. { This includes ADC, SBB and IDIV }
  9508. Break;
  9509. end;
  9510. if not CheckOverflowConditions then
  9511. Break;
  9512. { Contains highest index (so instruction count - 1) }
  9513. Inc(InstrMax);
  9514. if InstrMax > High(InstrList) then
  9515. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9516. InstrList[InstrMax] := taicpu(hp1);
  9517. end;
  9518. end;
  9519. {$pop}
  9520. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9521. var
  9522. hp1 : tai;
  9523. begin
  9524. Result:=false;
  9525. if (taicpu(p).ops >= 2) and
  9526. ((taicpu(p).oper[0]^.typ = top_const) or
  9527. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9528. (taicpu(p).oper[1]^.typ = top_reg) and
  9529. ((taicpu(p).ops = 2) or
  9530. ((taicpu(p).oper[2]^.typ = top_reg) and
  9531. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9532. GetLastInstruction(p,hp1) and
  9533. MatchInstruction(hp1,A_MOV,[]) and
  9534. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9535. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9536. begin
  9537. TransferUsedRegs(TmpUsedRegs);
  9538. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9539. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9540. { change
  9541. mov reg1,reg2
  9542. imul y,reg2 to imul y,reg1,reg2 }
  9543. begin
  9544. taicpu(p).ops := 3;
  9545. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9546. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9547. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9548. RemoveInstruction(hp1);
  9549. result:=true;
  9550. end;
  9551. end;
  9552. end;
  9553. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9554. var
  9555. ThisLabel: TAsmLabel;
  9556. begin
  9557. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9558. ThisLabel.decrefs;
  9559. taicpu(p).condition := C_None;
  9560. taicpu(p).opcode := A_RET;
  9561. taicpu(p).is_jmp := false;
  9562. taicpu(p).ops := taicpu(ret_p).ops;
  9563. case taicpu(ret_p).ops of
  9564. 0:
  9565. taicpu(p).clearop(0);
  9566. 1:
  9567. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9568. else
  9569. internalerror(2016041301);
  9570. end;
  9571. { If the original label is now dead, it might turn out that the label
  9572. immediately follows p. As a result, everything beyond it, which will
  9573. be just some final register configuration and a RET instruction, is
  9574. now dead code. [Kit] }
  9575. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9576. running RemoveDeadCodeAfterJump for each RET instruction, because
  9577. this optimisation rarely happens and most RETs appear at the end of
  9578. routines where there is nothing that can be stripped. [Kit] }
  9579. if not ThisLabel.is_used then
  9580. RemoveDeadCodeAfterJump(p);
  9581. end;
  9582. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9583. var
  9584. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9585. Unconditional, PotentialModified: Boolean;
  9586. OperPtr: POper;
  9587. NewRef: TReference;
  9588. InstrList: array of taicpu;
  9589. InstrMax, Index: Integer;
  9590. const
  9591. {$ifdef DEBUG_AOPTCPU}
  9592. SNoFlags: shortstring = ' so the flags aren''t modified';
  9593. {$else DEBUG_AOPTCPU}
  9594. SNoFlags = '';
  9595. {$endif DEBUG_AOPTCPU}
  9596. begin
  9597. Result:=false;
  9598. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9599. begin
  9600. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9601. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9602. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9603. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9604. GetNextInstruction(hp1, hp2) and
  9605. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9606. { Change from: To:
  9607. set(C) %reg j(~C) label
  9608. test %reg,%reg/cmp $0,%reg
  9609. je label
  9610. set(C) %reg j(C) label
  9611. test %reg,%reg/cmp $0,%reg
  9612. jne label
  9613. (Also do something similar with sete/setne instead of je/jne)
  9614. }
  9615. begin
  9616. { Before we do anything else, we need to check the instructions
  9617. in between SETcc and TEST to make sure they don't modify the
  9618. FLAGS register - if -O2 or under, there won't be any
  9619. instructions between SET and TEST }
  9620. TransferUsedRegs(TmpUsedRegs);
  9621. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9622. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9623. begin
  9624. next := p;
  9625. SetLength(InstrList, 0);
  9626. InstrMax := -1;
  9627. PotentialModified := False;
  9628. { Make a note of every instruction that modifies the FLAGS
  9629. register }
  9630. while GetNextInstruction(next, next) and (next <> hp1) do
  9631. begin
  9632. if next.typ <> ait_instruction then
  9633. { GetNextInstructionUsingReg should have returned False }
  9634. InternalError(2021051701);
  9635. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9636. begin
  9637. case taicpu(next).opcode of
  9638. A_SETcc,
  9639. A_CMOVcc,
  9640. A_Jcc:
  9641. begin
  9642. if PotentialModified then
  9643. { Not safe because the flags were modified earlier }
  9644. Exit
  9645. else
  9646. { Condition is the same as the initial SETcc, so this is safe
  9647. (don't add to instruction list though) }
  9648. Continue;
  9649. end;
  9650. A_ADD:
  9651. begin
  9652. if (taicpu(next).opsize = S_B) or
  9653. { LEA doesn't support 8-bit operands }
  9654. (taicpu(next).oper[1]^.typ <> top_reg) or
  9655. { Must write to a register }
  9656. (taicpu(next).oper[0]^.typ = top_ref) then
  9657. { Require a constant or a register }
  9658. Exit;
  9659. PotentialModified := True;
  9660. end;
  9661. A_SUB:
  9662. begin
  9663. if (taicpu(next).opsize = S_B) or
  9664. { LEA doesn't support 8-bit operands }
  9665. (taicpu(next).oper[1]^.typ <> top_reg) or
  9666. { Must write to a register }
  9667. (taicpu(next).oper[0]^.typ <> top_const) or
  9668. (taicpu(next).oper[0]^.val = $80000000) then
  9669. { Can't subtract a register with LEA - also
  9670. check that the value isn't -2^31, as this
  9671. can't be negated }
  9672. Exit;
  9673. PotentialModified := True;
  9674. end;
  9675. A_SAL,
  9676. A_SHL:
  9677. begin
  9678. if (taicpu(next).opsize = S_B) or
  9679. { LEA doesn't support 8-bit operands }
  9680. (taicpu(next).oper[1]^.typ <> top_reg) or
  9681. { Must write to a register }
  9682. (taicpu(next).oper[0]^.typ <> top_const) or
  9683. (taicpu(next).oper[0]^.val < 0) or
  9684. (taicpu(next).oper[0]^.val > 3) then
  9685. Exit;
  9686. PotentialModified := True;
  9687. end;
  9688. A_IMUL:
  9689. begin
  9690. if (taicpu(next).ops <> 3) or
  9691. (taicpu(next).oper[1]^.typ <> top_reg) or
  9692. { Must write to a register }
  9693. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9694. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9695. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9696. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9697. Exit
  9698. else
  9699. PotentialModified := True;
  9700. end;
  9701. else
  9702. { Don't know how to change this, so abort }
  9703. Exit;
  9704. end;
  9705. { Contains highest index (so instruction count - 1) }
  9706. Inc(InstrMax);
  9707. if InstrMax > High(InstrList) then
  9708. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9709. InstrList[InstrMax] := taicpu(next);
  9710. end;
  9711. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9712. end;
  9713. if not Assigned(next) or (next <> hp1) then
  9714. { It should be equal to hp1 }
  9715. InternalError(2021051702);
  9716. { Cycle through each instruction and check to see if we can
  9717. change them to versions that don't modify the flags }
  9718. if (InstrMax >= 0) then
  9719. begin
  9720. for Index := 0 to InstrMax do
  9721. case InstrList[Index].opcode of
  9722. A_ADD:
  9723. begin
  9724. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9725. InstrList[Index].opcode := A_LEA;
  9726. reference_reset(NewRef, 1, []);
  9727. NewRef.base := InstrList[Index].oper[1]^.reg;
  9728. if InstrList[Index].oper[0]^.typ = top_reg then
  9729. begin
  9730. NewRef.index := InstrList[Index].oper[0]^.reg;
  9731. NewRef.scalefactor := 1;
  9732. end
  9733. else
  9734. NewRef.offset := InstrList[Index].oper[0]^.val;
  9735. InstrList[Index].loadref(0, NewRef);
  9736. end;
  9737. A_SUB:
  9738. begin
  9739. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9740. InstrList[Index].opcode := A_LEA;
  9741. reference_reset(NewRef, 1, []);
  9742. NewRef.base := InstrList[Index].oper[1]^.reg;
  9743. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9744. InstrList[Index].loadref(0, NewRef);
  9745. end;
  9746. A_SHL,
  9747. A_SAL:
  9748. begin
  9749. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9750. InstrList[Index].opcode := A_LEA;
  9751. reference_reset(NewRef, 1, []);
  9752. NewRef.index := InstrList[Index].oper[1]^.reg;
  9753. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9754. InstrList[Index].loadref(0, NewRef);
  9755. end;
  9756. A_IMUL:
  9757. begin
  9758. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9759. InstrList[Index].opcode := A_LEA;
  9760. reference_reset(NewRef, 1, []);
  9761. NewRef.index := InstrList[Index].oper[1]^.reg;
  9762. case InstrList[Index].oper[0]^.val of
  9763. 2, 4, 8:
  9764. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9765. else {3, 5 and 9}
  9766. begin
  9767. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9768. NewRef.base := InstrList[Index].oper[1]^.reg;
  9769. end;
  9770. end;
  9771. InstrList[Index].loadref(0, NewRef);
  9772. end;
  9773. else
  9774. InternalError(2021051710);
  9775. end;
  9776. end;
  9777. { Mark the FLAGS register as used across this whole block }
  9778. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9779. end;
  9780. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9781. JumpC := taicpu(hp2).condition;
  9782. Unconditional := False;
  9783. if conditions_equal(JumpC, C_E) then
  9784. SetC := inverse_cond(taicpu(p).condition)
  9785. else if conditions_equal(JumpC, C_NE) then
  9786. SetC := taicpu(p).condition
  9787. else
  9788. { We've got something weird here (and inefficent) }
  9789. begin
  9790. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9791. SetC := C_NONE;
  9792. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9793. if condition_in(C_AE, JumpC) then
  9794. Unconditional := True
  9795. else
  9796. { Not sure what to do with this jump - drop out }
  9797. Exit;
  9798. end;
  9799. RemoveInstruction(hp1);
  9800. if Unconditional then
  9801. MakeUnconditional(taicpu(hp2))
  9802. else
  9803. begin
  9804. if SetC = C_NONE then
  9805. InternalError(2018061402);
  9806. taicpu(hp2).SetCondition(SetC);
  9807. end;
  9808. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9809. TmpUsedRegs }
  9810. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9811. begin
  9812. RemoveCurrentp(p, hp2);
  9813. if taicpu(hp2).opcode = A_SETcc then
  9814. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9815. else
  9816. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9817. end
  9818. else
  9819. if taicpu(hp2).opcode = A_SETcc then
  9820. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9821. else
  9822. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9823. Result := True;
  9824. end
  9825. else if
  9826. { Make sure the instructions are adjacent }
  9827. (
  9828. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9829. GetNextInstruction(p, hp1)
  9830. ) and
  9831. MatchInstruction(hp1, A_MOV, [S_B]) and
  9832. { Writing to memory is allowed }
  9833. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9834. begin
  9835. {
  9836. Watch out for sequences such as:
  9837. set(c)b %regb
  9838. movb %regb,(ref)
  9839. movb $0,1(ref)
  9840. movb $0,2(ref)
  9841. movb $0,3(ref)
  9842. Much more efficient to turn it into:
  9843. movl $0,%regl
  9844. set(c)b %regb
  9845. movl %regl,(ref)
  9846. Or:
  9847. set(c)b %regb
  9848. movzbl %regb,%regl
  9849. movl %regl,(ref)
  9850. }
  9851. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9852. GetNextInstruction(hp1, hp2) and
  9853. MatchInstruction(hp2, A_MOV, [S_B]) and
  9854. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9855. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9856. begin
  9857. { Don't do anything else except set Result to True }
  9858. end
  9859. else
  9860. begin
  9861. if taicpu(p).oper[0]^.typ = top_reg then
  9862. begin
  9863. TransferUsedRegs(TmpUsedRegs);
  9864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9865. end;
  9866. { If it's not a register, it's a memory address }
  9867. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9868. begin
  9869. { Even if the register is still in use, we can minimise the
  9870. pipeline stall by changing the MOV into another SETcc. }
  9871. taicpu(hp1).opcode := A_SETcc;
  9872. taicpu(hp1).condition := taicpu(p).condition;
  9873. if taicpu(hp1).oper[1]^.typ = top_ref then
  9874. begin
  9875. { Swapping the operand pointers like this is probably a
  9876. bit naughty, but it is far faster than using loadoper
  9877. to transfer the reference from oper[1] to oper[0] if
  9878. you take into account the extra procedure calls and
  9879. the memory allocation and deallocation required }
  9880. OperPtr := taicpu(hp1).oper[1];
  9881. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9882. taicpu(hp1).oper[0] := OperPtr;
  9883. end
  9884. else
  9885. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9886. taicpu(hp1).clearop(1);
  9887. taicpu(hp1).ops := 1;
  9888. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9889. end
  9890. else
  9891. begin
  9892. if taicpu(hp1).oper[1]^.typ = top_reg then
  9893. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9894. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9895. RemoveInstruction(hp1);
  9896. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9897. end
  9898. end;
  9899. Result := True;
  9900. end;
  9901. end;
  9902. end;
  9903. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9904. var
  9905. hp1: tai;
  9906. Count: Integer;
  9907. OrigLabel: TAsmLabel;
  9908. begin
  9909. result := False;
  9910. { Sometimes, the optimisations below can permit this }
  9911. RemoveDeadCodeAfterJump(p);
  9912. 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
  9913. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9914. begin
  9915. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9916. { Also a side-effect of optimisations }
  9917. if CollapseZeroDistJump(p, OrigLabel) then
  9918. begin
  9919. Result := True;
  9920. Exit;
  9921. end;
  9922. hp1 := GetLabelWithSym(OrigLabel);
  9923. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9924. begin
  9925. if taicpu(hp1).opcode = A_RET then
  9926. begin
  9927. {
  9928. change
  9929. jmp .L1
  9930. ...
  9931. .L1:
  9932. ret
  9933. into
  9934. ret
  9935. }
  9936. begin
  9937. ConvertJumpToRET(p, hp1);
  9938. result:=true;
  9939. end;
  9940. end
  9941. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9942. not (cs_opt_size in current_settings.optimizerswitches) and
  9943. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9944. begin
  9945. Result := True;
  9946. Exit;
  9947. end;
  9948. end;
  9949. end;
  9950. end;
  9951. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9952. begin
  9953. CanBeCMOV:=assigned(p) and
  9954. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9955. { we can't use cmov ref,reg because
  9956. ref could be nil and cmov still throws an exception
  9957. if ref=nil but the mov isn't done (FK)
  9958. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9959. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9960. }
  9961. (taicpu(p).oper[1]^.typ = top_reg) and
  9962. (
  9963. (taicpu(p).oper[0]^.typ = top_reg) or
  9964. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9965. it is not expected that this can cause a seg. violation }
  9966. (
  9967. (taicpu(p).oper[0]^.typ = top_ref) and
  9968. IsRefSafe(taicpu(p).oper[0]^.ref)
  9969. )
  9970. );
  9971. end;
  9972. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9973. var
  9974. hp1,hp2: tai;
  9975. {$ifndef i8086}
  9976. hp3,hp4,hpmov2, hp5: tai;
  9977. l : Longint;
  9978. condition : TAsmCond;
  9979. {$endif i8086}
  9980. carryadd_opcode : TAsmOp;
  9981. symbol: TAsmSymbol;
  9982. increg, tmpreg: TRegister;
  9983. begin
  9984. result:=false;
  9985. if GetNextInstruction(p,hp1) then
  9986. begin
  9987. if (hp1.typ=ait_label) then
  9988. begin
  9989. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9990. Exit;
  9991. end
  9992. else if (hp1.typ<>ait_instruction) then
  9993. Exit;
  9994. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9995. if (
  9996. (
  9997. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9998. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9999. (Taicpu(hp1).oper[0]^.val=1)
  10000. ) or
  10001. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10002. ) and
  10003. GetNextInstruction(hp1,hp2) and
  10004. SkipAligns(hp2, hp2) and
  10005. (hp2.typ = ait_label) and
  10006. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10007. { jb @@1 cmc
  10008. inc/dec operand --> adc/sbb operand,0
  10009. @@1:
  10010. ... and ...
  10011. jnb @@1
  10012. inc/dec operand --> adc/sbb operand,0
  10013. @@1: }
  10014. begin
  10015. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10016. begin
  10017. case taicpu(hp1).opcode of
  10018. A_INC,
  10019. A_ADD:
  10020. carryadd_opcode:=A_ADC;
  10021. A_DEC,
  10022. A_SUB:
  10023. carryadd_opcode:=A_SBB;
  10024. else
  10025. InternalError(2021011001);
  10026. end;
  10027. Taicpu(p).clearop(0);
  10028. Taicpu(p).ops:=0;
  10029. Taicpu(p).is_jmp:=false;
  10030. Taicpu(p).opcode:=A_CMC;
  10031. Taicpu(p).condition:=C_NONE;
  10032. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10033. Taicpu(hp1).ops:=2;
  10034. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10035. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10036. else
  10037. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10038. Taicpu(hp1).loadconst(0,0);
  10039. Taicpu(hp1).opcode:=carryadd_opcode;
  10040. result:=true;
  10041. exit;
  10042. end
  10043. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10044. begin
  10045. case taicpu(hp1).opcode of
  10046. A_INC,
  10047. A_ADD:
  10048. carryadd_opcode:=A_ADC;
  10049. A_DEC,
  10050. A_SUB:
  10051. carryadd_opcode:=A_SBB;
  10052. else
  10053. InternalError(2021011002);
  10054. end;
  10055. Taicpu(hp1).ops:=2;
  10056. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10057. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10058. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10059. else
  10060. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10061. Taicpu(hp1).loadconst(0,0);
  10062. Taicpu(hp1).opcode:=carryadd_opcode;
  10063. RemoveCurrentP(p, hp1);
  10064. result:=true;
  10065. exit;
  10066. end
  10067. {
  10068. jcc @@1 setcc tmpreg
  10069. inc/dec/add/sub operand -> (movzx tmpreg)
  10070. @@1: add/sub tmpreg,operand
  10071. While this increases code size slightly, it makes the code much faster if the
  10072. jump is unpredictable
  10073. }
  10074. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10075. begin
  10076. { search for an available register which is volatile }
  10077. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10078. if increg <> NR_NO then
  10079. begin
  10080. { We don't need to check if tmpreg is in hp1 or not, because
  10081. it will be marked as in use at p (if not, this is
  10082. indictive of a compiler bug). }
  10083. TAsmLabel(symbol).decrefs;
  10084. Taicpu(p).clearop(0);
  10085. Taicpu(p).ops:=1;
  10086. Taicpu(p).is_jmp:=false;
  10087. Taicpu(p).opcode:=A_SETcc;
  10088. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10089. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10090. Taicpu(p).loadreg(0,increg);
  10091. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10092. begin
  10093. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10094. R_SUBW:
  10095. begin
  10096. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10097. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10098. end;
  10099. R_SUBD:
  10100. begin
  10101. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10102. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10103. end;
  10104. {$ifdef x86_64}
  10105. R_SUBQ:
  10106. begin
  10107. { MOVZX doesn't have a 64-bit variant, because
  10108. the 32-bit version implicitly zeroes the
  10109. upper 32-bits of the destination register }
  10110. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10111. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10112. setsubreg(tmpreg, R_SUBQ);
  10113. end;
  10114. {$endif x86_64}
  10115. else
  10116. Internalerror(2020030601);
  10117. end;
  10118. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10119. asml.InsertAfter(hp2,p);
  10120. end
  10121. else
  10122. tmpreg := increg;
  10123. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10124. begin
  10125. Taicpu(hp1).ops:=2;
  10126. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10127. end;
  10128. Taicpu(hp1).loadreg(0,tmpreg);
  10129. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10130. Result := True;
  10131. { p is no longer a Jcc instruction, so exit }
  10132. Exit;
  10133. end;
  10134. end;
  10135. end;
  10136. { Detect the following:
  10137. jmp<cond> @Lbl1
  10138. jmp @Lbl2
  10139. ...
  10140. @Lbl1:
  10141. ret
  10142. Change to:
  10143. jmp<inv_cond> @Lbl2
  10144. ret
  10145. }
  10146. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10147. begin
  10148. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10149. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10150. MatchInstruction(hp2,A_RET,[S_NO]) then
  10151. begin
  10152. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10153. { Change label address to that of the unconditional jump }
  10154. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10155. TAsmLabel(symbol).DecRefs;
  10156. taicpu(hp1).opcode := A_RET;
  10157. taicpu(hp1).is_jmp := false;
  10158. taicpu(hp1).ops := taicpu(hp2).ops;
  10159. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10160. case taicpu(hp2).ops of
  10161. 0:
  10162. taicpu(hp1).clearop(0);
  10163. 1:
  10164. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10165. else
  10166. internalerror(2016041302);
  10167. end;
  10168. end;
  10169. {$ifndef i8086}
  10170. end
  10171. {
  10172. convert
  10173. j<c> .L1
  10174. mov 1,reg
  10175. jmp .L2
  10176. .L1
  10177. mov 0,reg
  10178. .L2
  10179. into
  10180. mov 0,reg
  10181. set<not(c)> reg
  10182. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10183. would destroy the flag contents
  10184. }
  10185. else if MatchInstruction(hp1,A_MOV,[]) and
  10186. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10187. {$ifdef i386}
  10188. (
  10189. { Under i386, ESI, EDI, EBP and ESP
  10190. don't have an 8-bit representation }
  10191. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10192. ) and
  10193. {$endif i386}
  10194. (taicpu(hp1).oper[0]^.val=1) and
  10195. GetNextInstruction(hp1,hp2) and
  10196. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10197. GetNextInstruction(hp2,hp3) and
  10198. { skip align }
  10199. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10200. (hp3.typ=ait_label) and
  10201. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10202. (tai_label(hp3).labsym.getrefs=1) and
  10203. GetNextInstruction(hp3,hp4) and
  10204. MatchInstruction(hp4,A_MOV,[]) and
  10205. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10206. (taicpu(hp4).oper[0]^.val=0) and
  10207. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10208. GetNextInstruction(hp4,hp5) and
  10209. (hp5.typ=ait_label) and
  10210. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10211. (tai_label(hp5).labsym.getrefs=1) then
  10212. begin
  10213. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10214. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10215. { remove last label }
  10216. RemoveInstruction(hp5);
  10217. { remove second label }
  10218. RemoveInstruction(hp3);
  10219. { if align is present remove it }
  10220. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10221. RemoveInstruction(hp3);
  10222. { remove jmp }
  10223. RemoveInstruction(hp2);
  10224. if taicpu(hp1).opsize=S_B then
  10225. RemoveInstruction(hp1)
  10226. else
  10227. taicpu(hp1).loadconst(0,0);
  10228. taicpu(hp4).opcode:=A_SETcc;
  10229. taicpu(hp4).opsize:=S_B;
  10230. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10231. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10232. taicpu(hp4).opercnt:=1;
  10233. taicpu(hp4).ops:=1;
  10234. taicpu(hp4).freeop(1);
  10235. RemoveCurrentP(p);
  10236. Result:=true;
  10237. exit;
  10238. end
  10239. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10240. begin
  10241. { check for
  10242. jCC xxx
  10243. <several movs>
  10244. xxx:
  10245. Also spot:
  10246. Jcc xxx
  10247. <several movs>
  10248. jmp xxx
  10249. Change to:
  10250. <several cmovs with inverted condition>
  10251. jmp xxx
  10252. }
  10253. l:=0;
  10254. while assigned(hp1) and
  10255. CanBeCMOV(hp1) and
  10256. { stop on labels }
  10257. not(hp1.typ=ait_label) do
  10258. begin
  10259. inc(l);
  10260. hp5 := hp1;
  10261. GetNextInstruction(hp1,hp1);
  10262. end;
  10263. if assigned(hp1) then
  10264. begin
  10265. TransferUsedRegs(TmpUsedRegs);
  10266. if (
  10267. MatchInstruction(hp1, A_JMP, []) and
  10268. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10269. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10270. ) or
  10271. FindLabel(tasmlabel(symbol),hp1) then
  10272. begin
  10273. if (l<=4) and (l>0) then
  10274. begin
  10275. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10276. condition:=inverse_cond(taicpu(p).condition);
  10277. UpdateUsedRegs(tai(p.next));
  10278. GetNextInstruction(p,hp1);
  10279. repeat
  10280. if not Assigned(hp1) then
  10281. InternalError(2018062900);
  10282. taicpu(hp1).opcode:=A_CMOVcc;
  10283. taicpu(hp1).condition:=condition;
  10284. UpdateUsedRegs(tai(hp1.next));
  10285. GetNextInstruction(hp1,hp1);
  10286. until not(CanBeCMOV(hp1));
  10287. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10288. hp2 := hp1;
  10289. repeat
  10290. if not Assigned(hp2) then
  10291. InternalError(2018062910);
  10292. case hp2.typ of
  10293. ait_label:
  10294. { What we expected - break out of the loop (it won't be a dead label at the top of
  10295. a cluster because that was optimised at an earlier stage) }
  10296. Break;
  10297. ait_align:
  10298. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10299. begin
  10300. hp2 := tai(hp2.Next);
  10301. Continue;
  10302. end;
  10303. ait_instruction:
  10304. begin
  10305. if taicpu(hp2).opcode<>A_JMP then
  10306. InternalError(2018062912);
  10307. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10308. Break;
  10309. end
  10310. else
  10311. begin
  10312. { Might be a comment or temporary allocation entry }
  10313. if not (hp2.typ in SkipInstr) then
  10314. InternalError(2018062911);
  10315. hp2 := tai(hp2.Next);
  10316. Continue;
  10317. end;
  10318. end;
  10319. until False;
  10320. { Now we can safely decrement the reference count }
  10321. tasmlabel(symbol).decrefs;
  10322. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10323. { Remove the original jump }
  10324. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10325. if hp2.typ=ait_instruction then
  10326. begin
  10327. p:=hp2;
  10328. Result:=True;
  10329. end
  10330. else
  10331. begin
  10332. UpdateUsedRegs(tai(hp2.next));
  10333. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10334. { Remove the label if this is its final reference }
  10335. if (tasmlabel(symbol).getrefs=0) then
  10336. StripLabelFast(hp1);
  10337. end;
  10338. exit;
  10339. end;
  10340. end
  10341. else
  10342. begin
  10343. { check further for
  10344. jCC xxx
  10345. <several movs 1>
  10346. jmp yyy
  10347. xxx:
  10348. <several movs 2>
  10349. yyy:
  10350. }
  10351. { hp2 points to jmp yyy }
  10352. hp2:=hp1;
  10353. { skip hp1 to xxx (or an align right before it) }
  10354. GetNextInstruction(hp1, hp1);
  10355. if assigned(hp2) and
  10356. assigned(hp1) and
  10357. (l<=3) and
  10358. (hp2.typ=ait_instruction) and
  10359. (taicpu(hp2).is_jmp) and
  10360. (taicpu(hp2).condition=C_None) and
  10361. { real label and jump, no further references to the
  10362. label are allowed }
  10363. (tasmlabel(symbol).getrefs=1) and
  10364. FindLabel(tasmlabel(symbol),hp1) then
  10365. begin
  10366. l:=0;
  10367. { skip hp1 to <several moves 2> }
  10368. if (hp1.typ = ait_align) then
  10369. GetNextInstruction(hp1, hp1);
  10370. GetNextInstruction(hp1, hpmov2);
  10371. hp1 := hpmov2;
  10372. while assigned(hp1) and
  10373. CanBeCMOV(hp1) do
  10374. begin
  10375. inc(l);
  10376. hp5 := hp1;
  10377. GetNextInstruction(hp1, hp1);
  10378. end;
  10379. { hp1 points to yyy (or an align right before it) }
  10380. hp3 := hp1;
  10381. if assigned(hp1) and
  10382. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10383. begin
  10384. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10385. condition:=inverse_cond(taicpu(p).condition);
  10386. UpdateUsedRegs(tai(p.next));
  10387. GetNextInstruction(p,hp1);
  10388. repeat
  10389. taicpu(hp1).opcode:=A_CMOVcc;
  10390. taicpu(hp1).condition:=condition;
  10391. UpdateUsedRegs(tai(hp1.next));
  10392. GetNextInstruction(hp1,hp1);
  10393. until not(assigned(hp1)) or
  10394. not(CanBeCMOV(hp1));
  10395. condition:=inverse_cond(condition);
  10396. if GetLastInstruction(hpmov2,hp1) then
  10397. UpdateUsedRegs(tai(hp1.next));
  10398. hp1 := hpmov2;
  10399. { hp1 is now at <several movs 2> }
  10400. while Assigned(hp1) and CanBeCMOV(hp1) do
  10401. begin
  10402. taicpu(hp1).opcode:=A_CMOVcc;
  10403. taicpu(hp1).condition:=condition;
  10404. UpdateUsedRegs(tai(hp1.next));
  10405. GetNextInstruction(hp1,hp1);
  10406. end;
  10407. hp1 := p;
  10408. { Get first instruction after label }
  10409. UpdateUsedRegs(tai(hp3.next));
  10410. GetNextInstruction(hp3, p);
  10411. if assigned(p) and (hp3.typ = ait_align) then
  10412. GetNextInstruction(p, p);
  10413. { Don't dereference yet, as doing so will cause
  10414. GetNextInstruction to skip the label and
  10415. optional align marker. [Kit] }
  10416. GetNextInstruction(hp2, hp4);
  10417. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10418. { remove jCC }
  10419. RemoveInstruction(hp1);
  10420. { Now we can safely decrement it }
  10421. tasmlabel(symbol).decrefs;
  10422. { Remove label xxx (it will have a ref of zero due to the initial check }
  10423. StripLabelFast(hp4);
  10424. { remove jmp }
  10425. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10426. RemoveInstruction(hp2);
  10427. { As before, now we can safely decrement it }
  10428. tasmlabel(symbol).decrefs;
  10429. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10430. if tasmlabel(symbol).getrefs = 0 then
  10431. StripLabelFast(hp3);
  10432. if Assigned(p) then
  10433. result:=true;
  10434. exit;
  10435. end;
  10436. end;
  10437. end;
  10438. end;
  10439. {$endif i8086}
  10440. end;
  10441. end;
  10442. end;
  10443. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10444. var
  10445. hp1,hp2,hp3: tai;
  10446. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10447. NewSize: TOpSize;
  10448. NewRegSize: TSubRegister;
  10449. Limit: TCgInt;
  10450. SwapOper: POper;
  10451. begin
  10452. result:=false;
  10453. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10454. GetNextInstruction(p,hp1) and
  10455. (hp1.typ = ait_instruction);
  10456. if reg_and_hp1_is_instr and
  10457. (
  10458. (taicpu(hp1).opcode <> A_LEA) or
  10459. { If the LEA instruction can be converted into an arithmetic instruction,
  10460. it may be possible to then fold it. }
  10461. (
  10462. { If the flags register is in use, don't change the instruction
  10463. to an ADD otherwise this will scramble the flags. [Kit] }
  10464. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10465. ConvertLEA(taicpu(hp1))
  10466. )
  10467. ) and
  10468. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10469. GetNextInstruction(hp1,hp2) and
  10470. MatchInstruction(hp2,A_MOV,[]) and
  10471. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10472. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10473. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10474. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10475. {$ifdef i386}
  10476. { not all registers have byte size sub registers on i386 }
  10477. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10478. {$endif i386}
  10479. (((taicpu(hp1).ops=2) and
  10480. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10481. ((taicpu(hp1).ops=1) and
  10482. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10483. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10484. begin
  10485. { change movsX/movzX reg/ref, reg2
  10486. add/sub/or/... reg3/$const, reg2
  10487. mov reg2 reg/ref
  10488. to add/sub/or/... reg3/$const, reg/ref }
  10489. { by example:
  10490. movswl %si,%eax movswl %si,%eax p
  10491. decl %eax addl %edx,%eax hp1
  10492. movw %ax,%si movw %ax,%si hp2
  10493. ->
  10494. movswl %si,%eax movswl %si,%eax p
  10495. decw %eax addw %edx,%eax hp1
  10496. movw %ax,%si movw %ax,%si hp2
  10497. }
  10498. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10499. {
  10500. ->
  10501. movswl %si,%eax movswl %si,%eax p
  10502. decw %si addw %dx,%si hp1
  10503. movw %ax,%si movw %ax,%si hp2
  10504. }
  10505. case taicpu(hp1).ops of
  10506. 1:
  10507. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10508. 2:
  10509. begin
  10510. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10511. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10512. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10513. end;
  10514. else
  10515. internalerror(2008042702);
  10516. end;
  10517. {
  10518. ->
  10519. decw %si addw %dx,%si p
  10520. }
  10521. DebugMsg(SPeepholeOptimization + 'var3',p);
  10522. RemoveCurrentP(p, hp1);
  10523. RemoveInstruction(hp2);
  10524. Result := True;
  10525. Exit;
  10526. end;
  10527. if reg_and_hp1_is_instr and
  10528. (taicpu(hp1).opcode = A_MOV) and
  10529. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10530. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10531. {$ifdef x86_64}
  10532. { check for implicit extension to 64 bit }
  10533. or
  10534. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10535. (taicpu(hp1).opsize=S_Q) and
  10536. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10537. )
  10538. {$endif x86_64}
  10539. )
  10540. then
  10541. begin
  10542. { change
  10543. movx %reg1,%reg2
  10544. mov %reg2,%reg3
  10545. dealloc %reg2
  10546. into
  10547. movx %reg,%reg3
  10548. }
  10549. TransferUsedRegs(TmpUsedRegs);
  10550. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10551. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10552. begin
  10553. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10554. {$ifdef x86_64}
  10555. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10556. (taicpu(hp1).opsize=S_Q) then
  10557. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10558. else
  10559. {$endif x86_64}
  10560. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10561. RemoveInstruction(hp1);
  10562. Result := True;
  10563. Exit;
  10564. end;
  10565. end;
  10566. if reg_and_hp1_is_instr and
  10567. ((taicpu(hp1).opcode=A_MOV) or
  10568. (taicpu(hp1).opcode=A_ADD) or
  10569. (taicpu(hp1).opcode=A_SUB) or
  10570. (taicpu(hp1).opcode=A_CMP) or
  10571. (taicpu(hp1).opcode=A_OR) or
  10572. (taicpu(hp1).opcode=A_XOR) or
  10573. (taicpu(hp1).opcode=A_AND)
  10574. ) and
  10575. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10576. begin
  10577. AndTest := (taicpu(hp1).opcode=A_AND) and
  10578. GetNextInstruction(hp1, hp2) and
  10579. (hp2.typ = ait_instruction) and
  10580. (
  10581. (
  10582. (taicpu(hp2).opcode=A_TEST) and
  10583. (
  10584. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10585. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10586. (
  10587. { If the AND and TEST instructions share a constant, this is also valid }
  10588. (taicpu(hp1).oper[0]^.typ = top_const) and
  10589. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10590. )
  10591. ) and
  10592. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10593. ) or
  10594. (
  10595. (taicpu(hp2).opcode=A_CMP) and
  10596. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10597. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10598. )
  10599. );
  10600. { change
  10601. movx (oper),%reg2
  10602. and $x,%reg2
  10603. test %reg2,%reg2
  10604. dealloc %reg2
  10605. into
  10606. op %reg1,%reg3
  10607. if the second op accesses only the bits stored in reg1
  10608. }
  10609. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10610. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10611. (taicpu(hp1).oper[0]^.typ = top_const) and
  10612. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10613. AndTest then
  10614. begin
  10615. { Check if the AND constant is in range }
  10616. case taicpu(p).opsize of
  10617. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10618. begin
  10619. NewSize := S_B;
  10620. Limit := $FF;
  10621. end;
  10622. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10623. begin
  10624. NewSize := S_W;
  10625. Limit := $FFFF;
  10626. end;
  10627. {$ifdef x86_64}
  10628. S_LQ:
  10629. begin
  10630. NewSize := S_L;
  10631. Limit := $FFFFFFFF;
  10632. end;
  10633. {$endif x86_64}
  10634. else
  10635. InternalError(2021120303);
  10636. end;
  10637. if (
  10638. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10639. { Check for negative operands }
  10640. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10641. ) and
  10642. GetNextInstruction(hp2,hp3) and
  10643. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10644. (taicpu(hp3).condition in [C_E,C_NE]) then
  10645. begin
  10646. TransferUsedRegs(TmpUsedRegs);
  10647. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10648. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10649. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10650. begin
  10651. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10652. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10653. taicpu(hp1).opcode := A_TEST;
  10654. taicpu(hp1).opsize := NewSize;
  10655. RemoveInstruction(hp2);
  10656. RemoveCurrentP(p, hp1);
  10657. Result:=true;
  10658. exit;
  10659. end;
  10660. end;
  10661. end;
  10662. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10663. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10664. (taicpu(hp1).opsize=S_B)) or
  10665. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10666. (taicpu(hp1).opsize=S_W))
  10667. {$ifdef x86_64}
  10668. or ((taicpu(p).opsize=S_LQ) and
  10669. (taicpu(hp1).opsize=S_L))
  10670. {$endif x86_64}
  10671. ) and
  10672. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10673. begin
  10674. { change
  10675. movx %reg1,%reg2
  10676. op %reg2,%reg3
  10677. dealloc %reg2
  10678. into
  10679. op %reg1,%reg3
  10680. if the second op accesses only the bits stored in reg1
  10681. }
  10682. TransferUsedRegs(TmpUsedRegs);
  10683. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10684. if AndTest then
  10685. begin
  10686. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10687. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10688. end
  10689. else
  10690. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10691. if not RegUsed then
  10692. begin
  10693. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10694. if taicpu(p).oper[0]^.typ=top_reg then
  10695. begin
  10696. case taicpu(hp1).opsize of
  10697. S_B:
  10698. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10699. S_W:
  10700. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10701. S_L:
  10702. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10703. else
  10704. Internalerror(2020102301);
  10705. end;
  10706. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10707. end
  10708. else
  10709. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10710. RemoveCurrentP(p);
  10711. if AndTest then
  10712. RemoveInstruction(hp2);
  10713. result:=true;
  10714. exit;
  10715. end;
  10716. end
  10717. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10718. (
  10719. { Bitwise operations only }
  10720. (taicpu(hp1).opcode=A_AND) or
  10721. (taicpu(hp1).opcode=A_TEST) or
  10722. (
  10723. (taicpu(hp1).oper[0]^.typ = top_const) and
  10724. (
  10725. (taicpu(hp1).opcode=A_OR) or
  10726. (taicpu(hp1).opcode=A_XOR)
  10727. )
  10728. )
  10729. ) and
  10730. (
  10731. (taicpu(hp1).oper[0]^.typ = top_const) or
  10732. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10733. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10734. ) then
  10735. begin
  10736. { change
  10737. movx %reg2,%reg2
  10738. op const,%reg2
  10739. into
  10740. op const,%reg2 (smaller version)
  10741. movx %reg2,%reg2
  10742. also change
  10743. movx %reg1,%reg2
  10744. and/test (oper),%reg2
  10745. dealloc %reg2
  10746. into
  10747. and/test (oper),%reg1
  10748. }
  10749. case taicpu(p).opsize of
  10750. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10751. begin
  10752. NewSize := S_B;
  10753. NewRegSize := R_SUBL;
  10754. Limit := $FF;
  10755. end;
  10756. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10757. begin
  10758. NewSize := S_W;
  10759. NewRegSize := R_SUBW;
  10760. Limit := $FFFF;
  10761. end;
  10762. {$ifdef x86_64}
  10763. S_LQ:
  10764. begin
  10765. NewSize := S_L;
  10766. NewRegSize := R_SUBD;
  10767. Limit := $FFFFFFFF;
  10768. end;
  10769. {$endif x86_64}
  10770. else
  10771. Internalerror(2021120302);
  10772. end;
  10773. TransferUsedRegs(TmpUsedRegs);
  10774. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10775. if AndTest then
  10776. begin
  10777. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10778. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10779. end
  10780. else
  10781. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10782. if
  10783. (
  10784. (taicpu(p).opcode = A_MOVZX) and
  10785. (
  10786. (taicpu(hp1).opcode=A_AND) or
  10787. (taicpu(hp1).opcode=A_TEST)
  10788. ) and
  10789. not (
  10790. { If both are references, then the final instruction will have
  10791. both operands as references, which is not allowed }
  10792. (taicpu(p).oper[0]^.typ = top_ref) and
  10793. (taicpu(hp1).oper[0]^.typ = top_ref)
  10794. ) and
  10795. not RegUsed
  10796. ) or
  10797. (
  10798. (
  10799. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10800. not RegUsed
  10801. ) and
  10802. (taicpu(p).oper[0]^.typ = top_reg) and
  10803. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10804. (taicpu(hp1).oper[0]^.typ = top_const) and
  10805. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10806. ) then
  10807. begin
  10808. {$if defined(i386) or defined(i8086)}
  10809. { If the target size is 8-bit, make sure we can actually encode it }
  10810. 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
  10811. Exit;
  10812. {$endif i386 or i8086}
  10813. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10814. taicpu(hp1).opsize := NewSize;
  10815. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10816. if AndTest then
  10817. begin
  10818. RemoveInstruction(hp2);
  10819. if not RegUsed then
  10820. begin
  10821. taicpu(hp1).opcode := A_TEST;
  10822. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10823. begin
  10824. { Make sure the reference is the second operand }
  10825. SwapOper := taicpu(hp1).oper[0];
  10826. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10827. taicpu(hp1).oper[1] := SwapOper;
  10828. end;
  10829. end;
  10830. end;
  10831. case taicpu(hp1).oper[0]^.typ of
  10832. top_reg:
  10833. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10834. top_const:
  10835. { For the AND/TEST case }
  10836. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10837. else
  10838. ;
  10839. end;
  10840. if RegUsed then
  10841. begin
  10842. AsmL.Remove(p);
  10843. AsmL.InsertAfter(p, hp1);
  10844. p := hp1;
  10845. end
  10846. else
  10847. RemoveCurrentP(p, hp1);
  10848. result:=true;
  10849. exit;
  10850. end;
  10851. end;
  10852. end;
  10853. if reg_and_hp1_is_instr and
  10854. (taicpu(p).oper[0]^.typ = top_reg) and
  10855. (
  10856. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10857. ) and
  10858. (taicpu(hp1).oper[0]^.typ = top_const) and
  10859. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10860. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10861. { Minimum shift value allowed is the bit difference between the sizes }
  10862. (taicpu(hp1).oper[0]^.val >=
  10863. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10864. 8 * (
  10865. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10866. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10867. )
  10868. ) then
  10869. begin
  10870. { For:
  10871. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10872. shl/sal ##, %reg1
  10873. Remove the movsx/movzx instruction if the shift overwrites the
  10874. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10875. }
  10876. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10877. RemoveCurrentP(p, hp1);
  10878. Result := True;
  10879. Exit;
  10880. end
  10881. else if reg_and_hp1_is_instr and
  10882. (taicpu(p).oper[0]^.typ = top_reg) and
  10883. (
  10884. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10885. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10886. ) and
  10887. (taicpu(hp1).oper[0]^.typ = top_const) and
  10888. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10889. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10890. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10891. (taicpu(hp1).oper[0]^.val <
  10892. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10893. 8 * (
  10894. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10895. )
  10896. ) then
  10897. begin
  10898. { For:
  10899. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10900. sar ##, %reg1 shr ##, %reg1
  10901. Move the shift to before the movx instruction if the shift value
  10902. is not too large.
  10903. }
  10904. asml.Remove(hp1);
  10905. asml.InsertBefore(hp1, p);
  10906. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10907. case taicpu(p).opsize of
  10908. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10909. taicpu(hp1).opsize := S_B;
  10910. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10911. taicpu(hp1).opsize := S_W;
  10912. {$ifdef x86_64}
  10913. S_LQ:
  10914. taicpu(hp1).opsize := S_L;
  10915. {$endif}
  10916. else
  10917. InternalError(2020112401);
  10918. end;
  10919. if (taicpu(hp1).opcode = A_SHR) then
  10920. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10921. else
  10922. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10923. Result := True;
  10924. end;
  10925. if reg_and_hp1_is_instr and
  10926. (taicpu(p).oper[0]^.typ = top_reg) and
  10927. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10928. (
  10929. (taicpu(hp1).opcode = taicpu(p).opcode)
  10930. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10931. {$ifdef x86_64}
  10932. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10933. {$endif x86_64}
  10934. ) then
  10935. begin
  10936. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10937. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10938. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10939. begin
  10940. {
  10941. For example:
  10942. movzbw %al,%ax
  10943. movzwl %ax,%eax
  10944. Compress into:
  10945. movzbl %al,%eax
  10946. }
  10947. RegUsed := False;
  10948. case taicpu(p).opsize of
  10949. S_BW:
  10950. case taicpu(hp1).opsize of
  10951. S_WL:
  10952. begin
  10953. taicpu(p).opsize := S_BL;
  10954. RegUsed := True;
  10955. end;
  10956. {$ifdef x86_64}
  10957. S_WQ:
  10958. begin
  10959. if taicpu(p).opcode = A_MOVZX then
  10960. begin
  10961. taicpu(p).opsize := S_BL;
  10962. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10963. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10964. end
  10965. else
  10966. taicpu(p).opsize := S_BQ;
  10967. RegUsed := True;
  10968. end;
  10969. {$endif x86_64}
  10970. else
  10971. ;
  10972. end;
  10973. {$ifdef x86_64}
  10974. S_BL:
  10975. case taicpu(hp1).opsize of
  10976. S_LQ:
  10977. begin
  10978. if taicpu(p).opcode = A_MOVZX then
  10979. begin
  10980. taicpu(p).opsize := S_BL;
  10981. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10982. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10983. end
  10984. else
  10985. taicpu(p).opsize := S_BQ;
  10986. RegUsed := True;
  10987. end;
  10988. else
  10989. ;
  10990. end;
  10991. S_WL:
  10992. case taicpu(hp1).opsize of
  10993. S_LQ:
  10994. begin
  10995. if taicpu(p).opcode = A_MOVZX then
  10996. begin
  10997. taicpu(p).opsize := S_WL;
  10998. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10999. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11000. end
  11001. else
  11002. taicpu(p).opsize := S_WQ;
  11003. RegUsed := True;
  11004. end;
  11005. else
  11006. ;
  11007. end;
  11008. {$endif x86_64}
  11009. else
  11010. ;
  11011. end;
  11012. if RegUsed then
  11013. begin
  11014. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11015. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11016. RemoveInstruction(hp1);
  11017. Result := True;
  11018. Exit;
  11019. end;
  11020. end;
  11021. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11022. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11023. GetNextInstruction(hp1, hp2) and
  11024. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11025. (
  11026. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11027. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11028. {$ifdef x86_64}
  11029. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11030. {$endif x86_64}
  11031. ) and
  11032. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11033. (
  11034. (
  11035. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11036. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11037. ) or
  11038. (
  11039. { Only allow the operands in reverse order for TEST instructions }
  11040. (taicpu(hp2).opcode = A_TEST) and
  11041. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11042. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11043. )
  11044. ) then
  11045. begin
  11046. {
  11047. For example:
  11048. movzbl %al,%eax
  11049. movzbl (ref),%edx
  11050. andl %edx,%eax
  11051. (%edx deallocated)
  11052. Change to:
  11053. andb (ref),%al
  11054. movzbl %al,%eax
  11055. Rules are:
  11056. - First two instructions have the same opcode and opsize
  11057. - First instruction's operands are the same super-register
  11058. - Second instruction operates on a different register
  11059. - Third instruction is AND, OR, XOR or TEST
  11060. - Third instruction's operands are the destination registers of the first two instructions
  11061. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11062. - Second instruction's destination register is deallocated afterwards
  11063. }
  11064. TransferUsedRegs(TmpUsedRegs);
  11065. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11066. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11067. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11068. begin
  11069. case taicpu(p).opsize of
  11070. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11071. NewSize := S_B;
  11072. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11073. NewSize := S_W;
  11074. {$ifdef x86_64}
  11075. S_LQ:
  11076. NewSize := S_L;
  11077. {$endif x86_64}
  11078. else
  11079. InternalError(2021120301);
  11080. end;
  11081. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11082. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11083. taicpu(hp2).opsize := NewSize;
  11084. RemoveInstruction(hp1);
  11085. { With TEST, it's best to keep the MOVX instruction at the top }
  11086. if (taicpu(hp2).opcode <> A_TEST) then
  11087. begin
  11088. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11089. asml.Remove(p);
  11090. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11091. asml.InsertAfter(p, hp2);
  11092. p := hp2;
  11093. end
  11094. else
  11095. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11096. Result := True;
  11097. Exit;
  11098. end;
  11099. end;
  11100. end;
  11101. if taicpu(p).opcode=A_MOVZX then
  11102. begin
  11103. { removes superfluous And's after movzx's }
  11104. if reg_and_hp1_is_instr and
  11105. (taicpu(hp1).opcode = A_AND) and
  11106. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11107. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11108. {$ifdef x86_64}
  11109. { check for implicit extension to 64 bit }
  11110. or
  11111. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11112. (taicpu(hp1).opsize=S_Q) and
  11113. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11114. )
  11115. {$endif x86_64}
  11116. )
  11117. then
  11118. begin
  11119. case taicpu(p).opsize Of
  11120. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11121. if (taicpu(hp1).oper[0]^.val = $ff) then
  11122. begin
  11123. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11124. RemoveInstruction(hp1);
  11125. Result:=true;
  11126. exit;
  11127. end;
  11128. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11129. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11130. begin
  11131. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11132. RemoveInstruction(hp1);
  11133. Result:=true;
  11134. exit;
  11135. end;
  11136. {$ifdef x86_64}
  11137. S_LQ:
  11138. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11139. begin
  11140. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11141. RemoveInstruction(hp1);
  11142. Result:=true;
  11143. exit;
  11144. end;
  11145. {$endif x86_64}
  11146. else
  11147. ;
  11148. end;
  11149. { we cannot get rid of the and, but can we get rid of the movz ?}
  11150. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11151. begin
  11152. case taicpu(p).opsize Of
  11153. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11154. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11155. begin
  11156. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11157. RemoveCurrentP(p,hp1);
  11158. Result:=true;
  11159. exit;
  11160. end;
  11161. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11162. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11163. begin
  11164. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11165. RemoveCurrentP(p,hp1);
  11166. Result:=true;
  11167. exit;
  11168. end;
  11169. {$ifdef x86_64}
  11170. S_LQ:
  11171. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11172. begin
  11173. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11174. RemoveCurrentP(p,hp1);
  11175. Result:=true;
  11176. exit;
  11177. end;
  11178. {$endif x86_64}
  11179. else
  11180. ;
  11181. end;
  11182. end;
  11183. end;
  11184. { changes some movzx constructs to faster synonyms (all examples
  11185. are given with eax/ax, but are also valid for other registers)}
  11186. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11187. begin
  11188. case taicpu(p).opsize of
  11189. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11190. (the machine code is equivalent to movzbl %al,%eax), but the
  11191. code generator still generates that assembler instruction and
  11192. it is silently converted. This should probably be checked.
  11193. [Kit] }
  11194. S_BW:
  11195. begin
  11196. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11197. (
  11198. not IsMOVZXAcceptable
  11199. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11200. or (
  11201. (cs_opt_size in current_settings.optimizerswitches) and
  11202. (taicpu(p).oper[1]^.reg = NR_AX)
  11203. )
  11204. ) then
  11205. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11206. begin
  11207. DebugMsg(SPeepholeOptimization + 'var7',p);
  11208. taicpu(p).opcode := A_AND;
  11209. taicpu(p).changeopsize(S_W);
  11210. taicpu(p).loadConst(0,$ff);
  11211. Result := True;
  11212. end
  11213. else if not IsMOVZXAcceptable and
  11214. GetNextInstruction(p, hp1) and
  11215. (tai(hp1).typ = ait_instruction) and
  11216. (taicpu(hp1).opcode = A_AND) and
  11217. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11218. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11219. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11220. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11221. begin
  11222. DebugMsg(SPeepholeOptimization + 'var8',p);
  11223. taicpu(p).opcode := A_MOV;
  11224. taicpu(p).changeopsize(S_W);
  11225. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11226. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11227. Result := True;
  11228. end;
  11229. end;
  11230. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11231. S_BL:
  11232. if not IsMOVZXAcceptable then
  11233. begin
  11234. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11235. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11236. begin
  11237. DebugMsg(SPeepholeOptimization + 'var9',p);
  11238. taicpu(p).opcode := A_AND;
  11239. taicpu(p).changeopsize(S_L);
  11240. taicpu(p).loadConst(0,$ff);
  11241. Result := True;
  11242. end
  11243. else if GetNextInstruction(p, hp1) and
  11244. (tai(hp1).typ = ait_instruction) and
  11245. (taicpu(hp1).opcode = A_AND) and
  11246. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11247. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11248. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11249. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11250. begin
  11251. DebugMsg(SPeepholeOptimization + 'var10',p);
  11252. taicpu(p).opcode := A_MOV;
  11253. taicpu(p).changeopsize(S_L);
  11254. { do not use R_SUBWHOLE
  11255. as movl %rdx,%eax
  11256. is invalid in assembler PM }
  11257. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11258. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11259. Result := True;
  11260. end;
  11261. end;
  11262. {$endif i8086}
  11263. S_WL:
  11264. if not IsMOVZXAcceptable then
  11265. begin
  11266. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11267. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11268. begin
  11269. DebugMsg(SPeepholeOptimization + 'var11',p);
  11270. taicpu(p).opcode := A_AND;
  11271. taicpu(p).changeopsize(S_L);
  11272. taicpu(p).loadConst(0,$ffff);
  11273. Result := True;
  11274. end
  11275. else if GetNextInstruction(p, hp1) and
  11276. (tai(hp1).typ = ait_instruction) and
  11277. (taicpu(hp1).opcode = A_AND) and
  11278. (taicpu(hp1).oper[0]^.typ = top_const) and
  11279. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11280. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11281. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11282. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11283. begin
  11284. DebugMsg(SPeepholeOptimization + 'var12',p);
  11285. taicpu(p).opcode := A_MOV;
  11286. taicpu(p).changeopsize(S_L);
  11287. { do not use R_SUBWHOLE
  11288. as movl %rdx,%eax
  11289. is invalid in assembler PM }
  11290. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11291. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11292. Result := True;
  11293. end;
  11294. end;
  11295. else
  11296. InternalError(2017050705);
  11297. end;
  11298. end
  11299. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11300. begin
  11301. if GetNextInstruction(p, hp1) and
  11302. (tai(hp1).typ = ait_instruction) and
  11303. (taicpu(hp1).opcode = A_AND) and
  11304. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11305. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11306. begin
  11307. //taicpu(p).opcode := A_MOV;
  11308. case taicpu(p).opsize Of
  11309. S_BL:
  11310. begin
  11311. DebugMsg(SPeepholeOptimization + 'var13',p);
  11312. taicpu(hp1).changeopsize(S_L);
  11313. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11314. end;
  11315. S_WL:
  11316. begin
  11317. DebugMsg(SPeepholeOptimization + 'var14',p);
  11318. taicpu(hp1).changeopsize(S_L);
  11319. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11320. end;
  11321. S_BW:
  11322. begin
  11323. DebugMsg(SPeepholeOptimization + 'var15',p);
  11324. taicpu(hp1).changeopsize(S_W);
  11325. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11326. end;
  11327. else
  11328. Internalerror(2017050704)
  11329. end;
  11330. Result := True;
  11331. end;
  11332. end;
  11333. end;
  11334. end;
  11335. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11336. var
  11337. hp1, hp2 : tai;
  11338. MaskLength : Cardinal;
  11339. MaskedBits : TCgInt;
  11340. ActiveReg : TRegister;
  11341. begin
  11342. Result:=false;
  11343. { There are no optimisations for reference targets }
  11344. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11345. Exit;
  11346. while GetNextInstruction(p, hp1) and
  11347. (hp1.typ = ait_instruction) do
  11348. begin
  11349. if (taicpu(p).oper[0]^.typ = top_const) then
  11350. begin
  11351. case taicpu(hp1).opcode of
  11352. A_AND:
  11353. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11354. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11355. { the second register must contain the first one, so compare their subreg types }
  11356. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11357. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11358. { change
  11359. and const1, reg
  11360. and const2, reg
  11361. to
  11362. and (const1 and const2), reg
  11363. }
  11364. begin
  11365. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11366. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11367. RemoveCurrentP(p, hp1);
  11368. Result:=true;
  11369. exit;
  11370. end;
  11371. A_CMP:
  11372. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11373. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11374. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11375. { Just check that the condition on the next instruction is compatible }
  11376. GetNextInstruction(hp1, hp2) and
  11377. (hp2.typ = ait_instruction) and
  11378. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11379. then
  11380. { change
  11381. and 2^n, reg
  11382. cmp 2^n, reg
  11383. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11384. to
  11385. and 2^n, reg
  11386. test reg, reg
  11387. j(~c) / set(~c) / cmov(~c)
  11388. }
  11389. begin
  11390. { Keep TEST instruction in, rather than remove it, because
  11391. it may trigger other optimisations such as MovAndTest2Test }
  11392. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11393. taicpu(hp1).opcode := A_TEST;
  11394. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11395. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11396. Result := True;
  11397. Exit;
  11398. end;
  11399. A_MOVZX:
  11400. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11401. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11402. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11403. (
  11404. (
  11405. (taicpu(p).opsize=S_W) and
  11406. (taicpu(hp1).opsize=S_BW)
  11407. ) or
  11408. (
  11409. (taicpu(p).opsize=S_L) and
  11410. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11411. )
  11412. {$ifdef x86_64}
  11413. or
  11414. (
  11415. (taicpu(p).opsize=S_Q) and
  11416. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11417. )
  11418. {$endif x86_64}
  11419. ) then
  11420. begin
  11421. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11422. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11423. ) or
  11424. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11425. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11426. then
  11427. begin
  11428. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11429. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11430. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11431. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11432. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11433. }
  11434. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11435. RemoveInstruction(hp1);
  11436. { See if there are other optimisations possible }
  11437. Continue;
  11438. end;
  11439. end;
  11440. A_SHL:
  11441. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11442. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11443. begin
  11444. {$ifopt R+}
  11445. {$define RANGE_WAS_ON}
  11446. {$R-}
  11447. {$endif}
  11448. { get length of potential and mask }
  11449. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11450. { really a mask? }
  11451. {$ifdef RANGE_WAS_ON}
  11452. {$R+}
  11453. {$endif}
  11454. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11455. { unmasked part shifted out? }
  11456. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11457. begin
  11458. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11459. RemoveCurrentP(p, hp1);
  11460. Result:=true;
  11461. exit;
  11462. end;
  11463. end;
  11464. A_SHR:
  11465. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11466. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11467. (taicpu(hp1).oper[0]^.val <= 63) then
  11468. begin
  11469. { Does SHR combined with the AND cover all the bits?
  11470. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11471. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11472. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11473. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11474. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11475. begin
  11476. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11477. RemoveCurrentP(p, hp1);
  11478. Result := True;
  11479. Exit;
  11480. end;
  11481. end;
  11482. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11483. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11484. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11485. begin
  11486. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11487. (
  11488. (
  11489. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11490. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11491. ) or (
  11492. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11493. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11494. {$ifdef x86_64}
  11495. ) or (
  11496. (taicpu(hp1).opsize = S_LQ) and
  11497. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11498. {$endif x86_64}
  11499. )
  11500. ) then
  11501. begin
  11502. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11503. begin
  11504. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11505. RemoveInstruction(hp1);
  11506. { See if there are other optimisations possible }
  11507. Continue;
  11508. end;
  11509. { The super-registers are the same though.
  11510. Note that this change by itself doesn't improve
  11511. code speed, but it opens up other optimisations. }
  11512. {$ifdef x86_64}
  11513. { Convert 64-bit register to 32-bit }
  11514. case taicpu(hp1).opsize of
  11515. S_BQ:
  11516. begin
  11517. taicpu(hp1).opsize := S_BL;
  11518. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11519. end;
  11520. S_WQ:
  11521. begin
  11522. taicpu(hp1).opsize := S_WL;
  11523. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11524. end
  11525. else
  11526. ;
  11527. end;
  11528. {$endif x86_64}
  11529. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11530. taicpu(hp1).opcode := A_MOVZX;
  11531. { See if there are other optimisations possible }
  11532. Continue;
  11533. end;
  11534. end;
  11535. else
  11536. ;
  11537. end;
  11538. end
  11539. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11540. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11541. begin
  11542. {$ifdef x86_64}
  11543. if (taicpu(p).opsize = S_Q) then
  11544. begin
  11545. { Never necessary }
  11546. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11547. RemoveCurrentP(p, hp1);
  11548. Result := True;
  11549. Exit;
  11550. end;
  11551. {$endif x86_64}
  11552. { Forward check to determine necessity of and %reg,%reg }
  11553. TransferUsedRegs(TmpUsedRegs);
  11554. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11555. { Saves on a bunch of dereferences }
  11556. ActiveReg := taicpu(p).oper[1]^.reg;
  11557. case taicpu(hp1).opcode of
  11558. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11559. if (
  11560. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11561. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11562. ) and
  11563. (
  11564. (taicpu(hp1).opcode <> A_MOV) or
  11565. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11566. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11567. ) and
  11568. not (
  11569. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11570. (taicpu(hp1).opcode = A_MOV) and
  11571. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11572. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11573. ) and
  11574. (
  11575. (
  11576. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11577. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11578. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11579. ) or
  11580. (
  11581. {$ifdef x86_64}
  11582. (
  11583. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11584. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11585. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11586. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11587. ) and
  11588. {$endif x86_64}
  11589. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11590. )
  11591. ) then
  11592. begin
  11593. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11594. RemoveCurrentP(p, hp1);
  11595. Result := True;
  11596. Exit;
  11597. end;
  11598. A_ADD,
  11599. A_AND,
  11600. A_BSF,
  11601. A_BSR,
  11602. A_BTC,
  11603. A_BTR,
  11604. A_BTS,
  11605. A_OR,
  11606. A_SUB,
  11607. A_XOR:
  11608. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11609. if (
  11610. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11611. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11612. ) and
  11613. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11614. begin
  11615. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11616. RemoveCurrentP(p, hp1);
  11617. Result := True;
  11618. Exit;
  11619. end;
  11620. A_CMP,
  11621. A_TEST:
  11622. if (
  11623. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11624. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11625. ) and
  11626. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11627. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11628. begin
  11629. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11630. RemoveCurrentP(p, hp1);
  11631. Result := True;
  11632. Exit;
  11633. end;
  11634. A_BSWAP,
  11635. A_NEG,
  11636. A_NOT:
  11637. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11638. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11639. begin
  11640. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11641. RemoveCurrentP(p, hp1);
  11642. Result := True;
  11643. Exit;
  11644. end;
  11645. else
  11646. ;
  11647. end;
  11648. end;
  11649. if (taicpu(hp1).is_jmp) and
  11650. (taicpu(hp1).opcode<>A_JMP) and
  11651. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11652. begin
  11653. { change
  11654. and x, reg
  11655. jxx
  11656. to
  11657. test x, reg
  11658. jxx
  11659. if reg is deallocated before the
  11660. jump, but only if it's a conditional jump (PFV)
  11661. }
  11662. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  11663. taicpu(p).opcode := A_TEST;
  11664. Exit;
  11665. end;
  11666. Break;
  11667. end;
  11668. { Lone AND tests }
  11669. if (taicpu(p).oper[0]^.typ = top_const) then
  11670. begin
  11671. {
  11672. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11673. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11674. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11675. }
  11676. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11677. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11678. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11679. begin
  11680. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11681. if taicpu(p).opsize = S_L then
  11682. begin
  11683. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11684. Result := True;
  11685. end;
  11686. end;
  11687. end;
  11688. { Backward check to determine necessity of and %reg,%reg }
  11689. if (taicpu(p).oper[0]^.typ = top_reg) and
  11690. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11691. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11692. GetLastInstruction(p, hp2) and
  11693. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11694. { Check size of adjacent instruction to determine if the AND is
  11695. effectively a null operation }
  11696. (
  11697. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11698. { Note: Don't include S_Q }
  11699. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11700. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11701. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11702. ) then
  11703. begin
  11704. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11705. { If GetNextInstruction returned False, hp1 will be nil }
  11706. RemoveCurrentP(p, hp1);
  11707. Result := True;
  11708. Exit;
  11709. end;
  11710. end;
  11711. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11712. var
  11713. hp1, hp2: tai;
  11714. NewRef: TReference;
  11715. Distance: Cardinal;
  11716. TempTracking: TAllUsedRegs;
  11717. { This entire nested function is used in an if-statement below, but we
  11718. want to avoid all the used reg transfers and GetNextInstruction calls
  11719. until we really have to check }
  11720. function MemRegisterNotUsedLater: Boolean; inline;
  11721. var
  11722. hp2: tai;
  11723. begin
  11724. TransferUsedRegs(TmpUsedRegs);
  11725. hp2 := p;
  11726. repeat
  11727. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11728. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11729. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11730. end;
  11731. begin
  11732. Result := False;
  11733. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11734. (taicpu(p).oper[1]^.typ = top_reg) then
  11735. begin
  11736. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11737. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11738. (hp1.typ <> ait_instruction) or
  11739. not
  11740. (
  11741. (cs_opt_level3 in current_settings.optimizerswitches) or
  11742. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11743. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11744. ) then
  11745. Exit;
  11746. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11747. addq $x, %rax
  11748. movq %rax, %rdx
  11749. sarq $63, %rdx
  11750. (%rax still in use)
  11751. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11752. leaq $x(%rax),%rdx
  11753. addq $x, %rax
  11754. sarq $63, %rdx
  11755. ...which is okay since it breaks the dependency chain between
  11756. addq and movq, but if OptPass2MOV is called first:
  11757. addq $x, %rax
  11758. cqto
  11759. ...which is better in all ways, taking only 2 cycles to execute
  11760. and much smaller in code size.
  11761. }
  11762. { The extra register tracking is quite strenuous }
  11763. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11764. MatchInstruction(hp1, A_MOV, []) then
  11765. begin
  11766. { Update the register tracking to the MOV instruction }
  11767. CopyUsedRegs(TempTracking);
  11768. hp2 := p;
  11769. repeat
  11770. UpdateUsedRegs(tai(hp2.Next));
  11771. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11772. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11773. OptPass2ADD get called again }
  11774. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11775. begin
  11776. { Reset the tracking to the current instruction }
  11777. RestoreUsedRegs(TempTracking);
  11778. ReleaseUsedRegs(TempTracking);
  11779. Result := True;
  11780. Exit;
  11781. end;
  11782. { Reset the tracking to the current instruction }
  11783. RestoreUsedRegs(TempTracking);
  11784. ReleaseUsedRegs(TempTracking);
  11785. { If OptPass2MOV returned True, we don't need to set Result to
  11786. True if hp1 didn't change because the ADD instruction didn't
  11787. get modified and we'll be evaluating hp1 again when the
  11788. peephole optimizer reaches it }
  11789. end;
  11790. { Change:
  11791. add %reg2,%reg1
  11792. (%reg2 not modified in between)
  11793. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11794. To:
  11795. mov/s/z #(%reg1,%reg2),%reg1
  11796. }
  11797. if (taicpu(p).oper[0]^.typ = top_reg) and
  11798. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11799. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11800. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11801. (
  11802. (
  11803. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11804. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11805. { r/esp cannot be an index }
  11806. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11807. ) or (
  11808. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11809. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11810. )
  11811. ) and (
  11812. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11813. (
  11814. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11815. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11816. MemRegisterNotUsedLater
  11817. )
  11818. ) then
  11819. begin
  11820. if (
  11821. { Instructions are guaranteed to be adjacent on -O2 and under }
  11822. (cs_opt_level3 in current_settings.optimizerswitches) and
  11823. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  11824. ) then
  11825. begin
  11826. { If the other register is used in between, move the MOV
  11827. instruction to right after the ADD instruction so a
  11828. saving can still be made }
  11829. Asml.Remove(hp1);
  11830. Asml.InsertAfter(hp1, p);
  11831. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11832. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11833. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  11834. RemoveCurrentp(p, hp1);
  11835. end
  11836. else
  11837. begin
  11838. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11839. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11840. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11841. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11842. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11843. { hp1 may not be the immediate next instruction under -O3 }
  11844. RemoveCurrentp(p)
  11845. else
  11846. RemoveCurrentp(p, hp1);
  11847. end;
  11848. Result := True;
  11849. Exit;
  11850. end;
  11851. { Change:
  11852. addl/q $x,%reg1
  11853. movl/q %reg1,%reg2
  11854. To:
  11855. leal/q $x(%reg1),%reg2
  11856. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11857. Breaks the dependency chain.
  11858. }
  11859. if (taicpu(p).oper[0]^.typ = top_const) and
  11860. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11861. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11862. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11863. (
  11864. { Instructions are guaranteed to be adjacent on -O2 and under }
  11865. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11866. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11867. ) then
  11868. begin
  11869. TransferUsedRegs(TmpUsedRegs);
  11870. hp2 := p;
  11871. repeat
  11872. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11873. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11874. if (
  11875. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11876. not (cs_opt_size in current_settings.optimizerswitches) or
  11877. (
  11878. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11879. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11880. )
  11881. ) then
  11882. begin
  11883. { Change the MOV instruction to a LEA instruction, and update the
  11884. first operand }
  11885. reference_reset(NewRef, 1, []);
  11886. NewRef.base := taicpu(p).oper[1]^.reg;
  11887. NewRef.scalefactor := 1;
  11888. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11889. taicpu(hp1).opcode := A_LEA;
  11890. taicpu(hp1).loadref(0, NewRef);
  11891. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11892. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11893. begin
  11894. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11895. { Move what is now the LEA instruction to before the ADD instruction }
  11896. Asml.Remove(hp1);
  11897. Asml.InsertBefore(hp1, p);
  11898. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11899. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11900. p := hp1;
  11901. end
  11902. else
  11903. begin
  11904. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11905. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  11906. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11907. { hp1 may not be the immediate next instruction under -O3 }
  11908. RemoveCurrentp(p)
  11909. else
  11910. RemoveCurrentp(p, hp1);
  11911. end;
  11912. Result := True;
  11913. end;
  11914. end;
  11915. end;
  11916. end;
  11917. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11918. var
  11919. SubReg: TSubRegister;
  11920. begin
  11921. Result:=false;
  11922. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11923. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11924. with taicpu(p).oper[0]^.ref^ do
  11925. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11926. begin
  11927. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11928. begin
  11929. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11930. taicpu(p).opcode := A_ADD;
  11931. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11932. Result := True;
  11933. end
  11934. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11935. begin
  11936. if (base <> NR_NO) then
  11937. begin
  11938. if (scalefactor <= 1) then
  11939. begin
  11940. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11941. taicpu(p).opcode := A_ADD;
  11942. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11943. Result := True;
  11944. end;
  11945. end
  11946. else
  11947. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11948. if (scalefactor in [2, 4, 8]) then
  11949. begin
  11950. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11951. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11952. taicpu(p).opcode := A_SHL;
  11953. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11954. Result := True;
  11955. end;
  11956. end;
  11957. end;
  11958. end;
  11959. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11960. var
  11961. hp1, hp2: tai;
  11962. NewRef: TReference;
  11963. Distance: Cardinal;
  11964. TempTracking: TAllUsedRegs;
  11965. begin
  11966. Result := False;
  11967. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11968. MatchOpType(taicpu(p),top_const,top_reg) then
  11969. begin
  11970. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11971. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11972. (hp1.typ <> ait_instruction) or
  11973. not
  11974. (
  11975. (cs_opt_level3 in current_settings.optimizerswitches) or
  11976. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11977. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11978. ) then
  11979. Exit;
  11980. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11981. subq $x, %rax
  11982. movq %rax, %rdx
  11983. sarq $63, %rdx
  11984. (%rax still in use)
  11985. ...letting OptPass2SUB run its course (and without -Os) will produce:
  11986. leaq $-x(%rax),%rdx
  11987. movq $x, %rax
  11988. sarq $63, %rdx
  11989. ...which is okay since it breaks the dependency chain between
  11990. subq and movq, but if OptPass2MOV is called first:
  11991. subq $x, %rax
  11992. cqto
  11993. ...which is better in all ways, taking only 2 cycles to execute
  11994. and much smaller in code size.
  11995. }
  11996. { The extra register tracking is quite strenuous }
  11997. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11998. MatchInstruction(hp1, A_MOV, []) then
  11999. begin
  12000. { Update the register tracking to the MOV instruction }
  12001. CopyUsedRegs(TempTracking);
  12002. hp2 := p;
  12003. repeat
  12004. UpdateUsedRegs(tai(hp2.Next));
  12005. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12006. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12007. OptPass2SUB get called again }
  12008. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12009. begin
  12010. { Reset the tracking to the current instruction }
  12011. RestoreUsedRegs(TempTracking);
  12012. ReleaseUsedRegs(TempTracking);
  12013. Result := True;
  12014. Exit;
  12015. end;
  12016. { Reset the tracking to the current instruction }
  12017. RestoreUsedRegs(TempTracking);
  12018. ReleaseUsedRegs(TempTracking);
  12019. { If OptPass2MOV returned True, we don't need to set Result to
  12020. True if hp1 didn't change because the SUB instruction didn't
  12021. get modified and we'll be evaluating hp1 again when the
  12022. peephole optimizer reaches it }
  12023. end;
  12024. { Change:
  12025. subl/q $x,%reg1
  12026. movl/q %reg1,%reg2
  12027. To:
  12028. leal/q $-x(%reg1),%reg2
  12029. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12030. Breaks the dependency chain and potentially permits the removal of
  12031. a CMP instruction if one follows.
  12032. }
  12033. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12034. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12035. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12036. (
  12037. { Instructions are guaranteed to be adjacent on -O2 and under }
  12038. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12039. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12040. ) then
  12041. begin
  12042. TransferUsedRegs(TmpUsedRegs);
  12043. hp2 := p;
  12044. repeat
  12045. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12046. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12047. if (
  12048. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12049. not (cs_opt_size in current_settings.optimizerswitches) or
  12050. (
  12051. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12052. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12053. )
  12054. ) then
  12055. begin
  12056. { Change the MOV instruction to a LEA instruction, and update the
  12057. first operand }
  12058. reference_reset(NewRef, 1, []);
  12059. NewRef.base := taicpu(p).oper[1]^.reg;
  12060. NewRef.scalefactor := 1;
  12061. NewRef.offset := -taicpu(p).oper[0]^.val;
  12062. taicpu(hp1).opcode := A_LEA;
  12063. taicpu(hp1).loadref(0, NewRef);
  12064. TransferUsedRegs(TmpUsedRegs);
  12065. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12066. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12067. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12068. begin
  12069. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12070. { Move what is now the LEA instruction to before the SUB instruction }
  12071. Asml.Remove(hp1);
  12072. Asml.InsertBefore(hp1, p);
  12073. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12074. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12075. p := hp1;
  12076. end
  12077. else
  12078. begin
  12079. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12080. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12081. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12082. { hp1 may not be the immediate next instruction under -O3 }
  12083. RemoveCurrentp(p)
  12084. else
  12085. RemoveCurrentp(p, hp1);
  12086. end;
  12087. Result := True;
  12088. end;
  12089. end;
  12090. end;
  12091. end;
  12092. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12093. begin
  12094. { we can skip all instructions not messing with the stack pointer }
  12095. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12096. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12097. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12098. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12099. ({(taicpu(hp1).ops=0) or }
  12100. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12101. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12102. ) and }
  12103. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12104. )
  12105. ) do
  12106. GetNextInstruction(hp1,hp1);
  12107. Result:=assigned(hp1);
  12108. end;
  12109. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12110. var
  12111. hp1, hp2, hp3, hp4, hp5: tai;
  12112. begin
  12113. Result:=false;
  12114. hp5:=nil;
  12115. { replace
  12116. leal(q) x(<stackpointer>),<stackpointer>
  12117. call procname
  12118. leal(q) -x(<stackpointer>),<stackpointer>
  12119. ret
  12120. by
  12121. jmp procname
  12122. but do it only on level 4 because it destroys stack back traces
  12123. }
  12124. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12125. MatchOpType(taicpu(p),top_ref,top_reg) and
  12126. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12127. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12128. { the -8 or -24 are not required, but bail out early if possible,
  12129. higher values are unlikely }
  12130. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12131. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12132. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12133. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12134. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12135. GetNextInstruction(p, hp1) and
  12136. { Take a copy of hp1 }
  12137. SetAndTest(hp1, hp4) and
  12138. { trick to skip label }
  12139. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12140. SkipSimpleInstructions(hp1) and
  12141. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12142. GetNextInstruction(hp1, hp2) and
  12143. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12144. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12145. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12146. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12147. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12148. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12149. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12150. { Segment register will be NR_NO }
  12151. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12152. GetNextInstruction(hp2, hp3) and
  12153. { trick to skip label }
  12154. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12155. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12156. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12157. SetAndTest(hp3,hp5) and
  12158. GetNextInstruction(hp3,hp3) and
  12159. MatchInstruction(hp3,A_RET,[S_NO])
  12160. )
  12161. ) and
  12162. (taicpu(hp3).ops=0) then
  12163. begin
  12164. taicpu(hp1).opcode := A_JMP;
  12165. taicpu(hp1).is_jmp := true;
  12166. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12167. RemoveCurrentP(p, hp4);
  12168. RemoveInstruction(hp2);
  12169. RemoveInstruction(hp3);
  12170. if Assigned(hp5) then
  12171. begin
  12172. AsmL.Remove(hp5);
  12173. ASmL.InsertBefore(hp5,hp1)
  12174. end;
  12175. Result:=true;
  12176. end;
  12177. end;
  12178. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12179. {$ifdef x86_64}
  12180. var
  12181. hp1, hp2, hp3, hp4, hp5: tai;
  12182. {$endif x86_64}
  12183. begin
  12184. Result:=false;
  12185. {$ifdef x86_64}
  12186. hp5:=nil;
  12187. { replace
  12188. push %rax
  12189. call procname
  12190. pop %rcx
  12191. ret
  12192. by
  12193. jmp procname
  12194. but do it only on level 4 because it destroys stack back traces
  12195. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12196. for all supported calling conventions
  12197. }
  12198. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12199. MatchOpType(taicpu(p),top_reg) and
  12200. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12201. GetNextInstruction(p, hp1) and
  12202. { Take a copy of hp1 }
  12203. SetAndTest(hp1, hp4) and
  12204. { trick to skip label }
  12205. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12206. SkipSimpleInstructions(hp1) and
  12207. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12208. GetNextInstruction(hp1, hp2) and
  12209. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12210. MatchOpType(taicpu(hp2),top_reg) and
  12211. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12212. GetNextInstruction(hp2, hp3) and
  12213. { trick to skip label }
  12214. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12215. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12216. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12217. SetAndTest(hp3,hp5) and
  12218. GetNextInstruction(hp3,hp3) and
  12219. MatchInstruction(hp3,A_RET,[S_NO])
  12220. )
  12221. ) and
  12222. (taicpu(hp3).ops=0) then
  12223. begin
  12224. taicpu(hp1).opcode := A_JMP;
  12225. taicpu(hp1).is_jmp := true;
  12226. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12227. RemoveCurrentP(p, hp4);
  12228. RemoveInstruction(hp2);
  12229. RemoveInstruction(hp3);
  12230. if Assigned(hp5) then
  12231. begin
  12232. AsmL.Remove(hp5);
  12233. ASmL.InsertBefore(hp5,hp1)
  12234. end;
  12235. Result:=true;
  12236. end;
  12237. {$endif x86_64}
  12238. end;
  12239. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12240. var
  12241. Value, RegName: string;
  12242. begin
  12243. Result:=false;
  12244. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12245. begin
  12246. case taicpu(p).oper[0]^.val of
  12247. 0:
  12248. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12249. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12250. begin
  12251. { change "mov $0,%reg" into "xor %reg,%reg" }
  12252. taicpu(p).opcode := A_XOR;
  12253. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12254. Result := True;
  12255. {$ifdef x86_64}
  12256. end
  12257. else if (taicpu(p).opsize = S_Q) then
  12258. begin
  12259. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12260. { The actual optimization }
  12261. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12262. taicpu(p).changeopsize(S_L);
  12263. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12264. Result := True;
  12265. end;
  12266. $1..$FFFFFFFF:
  12267. begin
  12268. { Code size reduction by J. Gareth "Kit" Moreton }
  12269. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12270. case taicpu(p).opsize of
  12271. S_Q:
  12272. begin
  12273. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12274. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12275. { The actual optimization }
  12276. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12277. taicpu(p).changeopsize(S_L);
  12278. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12279. Result := True;
  12280. end;
  12281. else
  12282. { Do nothing };
  12283. end;
  12284. {$endif x86_64}
  12285. end;
  12286. -1:
  12287. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12288. if (cs_opt_size in current_settings.optimizerswitches) and
  12289. (taicpu(p).opsize <> S_B) and
  12290. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12291. begin
  12292. { change "mov $-1,%reg" into "or $-1,%reg" }
  12293. { NOTES:
  12294. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12295. - This operation creates a false dependency on the register, so only do it when optimising for size
  12296. - 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
  12297. }
  12298. taicpu(p).opcode := A_OR;
  12299. Result := True;
  12300. end;
  12301. else
  12302. { Do nothing };
  12303. end;
  12304. end;
  12305. end;
  12306. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  12307. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  12308. begin
  12309. Result := False;
  12310. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  12311. Exit;
  12312. { For sizes less than S_L, the byte size is equal or larger with BTx,
  12313. so don't bother optimising }
  12314. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12315. Exit;
  12316. if (taicpu(p).oper[0]^.typ <> top_const) or
  12317. { If the value can fit into an 8-bit signed integer, a smaller
  12318. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  12319. falls within this range }
  12320. (
  12321. (taicpu(p).oper[0]^.val > -128) and
  12322. (taicpu(p).oper[0]^.val <= 127)
  12323. ) then
  12324. Exit;
  12325. { If we're optimising for size, this is acceptable }
  12326. if (cs_opt_size in current_settings.optimizerswitches) then
  12327. Exit(True);
  12328. if (taicpu(p).oper[1]^.typ = top_reg) and
  12329. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12330. Exit(True);
  12331. if (taicpu(p).oper[1]^.typ <> top_reg) and
  12332. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  12333. Exit(True);
  12334. end;
  12335. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12336. var
  12337. hp1: tai;
  12338. Value: TCGInt;
  12339. begin
  12340. Result := False;
  12341. if MatchOpType(taicpu(p), top_const, top_reg) then
  12342. begin
  12343. { Detect:
  12344. andw x, %ax (0 <= x < $8000)
  12345. ...
  12346. movzwl %ax,%eax
  12347. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12348. }
  12349. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12350. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12351. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12352. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12353. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12354. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12355. begin
  12356. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12357. taicpu(hp1).opcode := A_CWDE;
  12358. taicpu(hp1).clearop(0);
  12359. taicpu(hp1).clearop(1);
  12360. taicpu(hp1).ops := 0;
  12361. { A change was made, but not with p, so move forward 1 }
  12362. p := tai(p.Next);
  12363. Result := True;
  12364. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  12365. end;
  12366. end;
  12367. { If "not x" is a power of 2 (popcnt = 1), change:
  12368. and $x, %reg/ref
  12369. To:
  12370. btr lb(x), %reg/ref
  12371. }
  12372. if IsBTXAcceptable(p) and
  12373. (
  12374. { Make sure a TEST doesn't follow that plays with the register }
  12375. not GetNextInstruction(p, hp1) or
  12376. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  12377. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  12378. ) then
  12379. begin
  12380. {$push}{$R-}{$Q-}
  12381. { Value is a sign-extended 32-bit integer - just correct it
  12382. if it's represented as an unsigned value. Also, IsBTXAcceptable
  12383. checks to see if this operand is an immediate. }
  12384. Value := not taicpu(p).oper[0]^.val;
  12385. {$pop}
  12386. {$ifdef x86_64}
  12387. if taicpu(p).opsize = S_L then
  12388. {$endif x86_64}
  12389. Value := Value and $FFFFFFFF;
  12390. if (PopCnt(QWord(Value)) = 1) then
  12391. begin
  12392. 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);
  12393. taicpu(p).opcode := A_BTR;
  12394. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  12395. Result := True;
  12396. Exit;
  12397. end;
  12398. end;
  12399. end;
  12400. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12401. begin
  12402. Result := False;
  12403. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12404. Exit;
  12405. { Convert:
  12406. movswl %ax,%eax -> cwtl
  12407. movslq %eax,%rax -> cdqe
  12408. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12409. refer to the same opcode and depends only on the assembler's
  12410. current operand-size attribute. [Kit]
  12411. }
  12412. with taicpu(p) do
  12413. case opsize of
  12414. S_WL:
  12415. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12416. begin
  12417. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12418. opcode := A_CWDE;
  12419. clearop(0);
  12420. clearop(1);
  12421. ops := 0;
  12422. Result := True;
  12423. end;
  12424. {$ifdef x86_64}
  12425. S_LQ:
  12426. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12427. begin
  12428. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12429. opcode := A_CDQE;
  12430. clearop(0);
  12431. clearop(1);
  12432. ops := 0;
  12433. Result := True;
  12434. end;
  12435. {$endif x86_64}
  12436. else
  12437. ;
  12438. end;
  12439. end;
  12440. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12441. var
  12442. hp1, hp2: tai;
  12443. IdentityMask, Shift: TCGInt;
  12444. LimitSize: Topsize;
  12445. DoNotMerge: Boolean;
  12446. begin
  12447. Result := False;
  12448. { All these optimisations work on "shr const,%reg" }
  12449. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12450. Exit;
  12451. DoNotMerge := False;
  12452. Shift := taicpu(p).oper[0]^.val;
  12453. LimitSize := taicpu(p).opsize;
  12454. hp1 := p;
  12455. repeat
  12456. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12457. Break;
  12458. { Detect:
  12459. shr x, %reg
  12460. and y, %reg
  12461. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12462. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12463. }
  12464. case taicpu(hp1).opcode of
  12465. A_AND:
  12466. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12467. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12468. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12469. begin
  12470. { Make sure the FLAGS register isn't in use }
  12471. TransferUsedRegs(TmpUsedRegs);
  12472. hp2 := p;
  12473. repeat
  12474. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12475. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12476. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12477. begin
  12478. { Generate the identity mask }
  12479. case taicpu(p).opsize of
  12480. S_B:
  12481. IdentityMask := $FF shr Shift;
  12482. S_W:
  12483. IdentityMask := $FFFF shr Shift;
  12484. S_L:
  12485. IdentityMask := $FFFFFFFF shr Shift;
  12486. {$ifdef x86_64}
  12487. S_Q:
  12488. { We need to force the operands to be unsigned 64-bit
  12489. integers otherwise the wrong value is generated }
  12490. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12491. {$endif x86_64}
  12492. else
  12493. InternalError(2022081501);
  12494. end;
  12495. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12496. begin
  12497. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12498. { All the possible 1 bits are covered, so we can remove the AND }
  12499. hp2 := tai(hp1.Previous);
  12500. RemoveInstruction(hp1);
  12501. { p wasn't actually changed, so don't set Result to True,
  12502. but a change was nonetheless made elsewhere }
  12503. Include(OptsToCheck, aoc_ForceNewIteration);
  12504. { Do another pass in case other AND or MOVZX instructions
  12505. follow }
  12506. hp1 := hp2;
  12507. Continue;
  12508. end;
  12509. end;
  12510. end;
  12511. A_TEST, A_CMP, A_Jcc:
  12512. { Skip over conditional jumps and relevant comparisons }
  12513. Continue;
  12514. A_MOVZX:
  12515. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12516. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12517. begin
  12518. { Since the original register is being read as is, subsequent
  12519. SHRs must not be merged at this point }
  12520. DoNotMerge := True;
  12521. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12522. begin
  12523. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12524. begin
  12525. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12526. { All the possible 1 bits are covered, so we can remove the AND }
  12527. hp2 := tai(hp1.Previous);
  12528. RemoveInstruction(hp1);
  12529. hp1 := hp2;
  12530. end
  12531. else { Different register target }
  12532. begin
  12533. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12534. taicpu(hp1).opcode := A_MOV;
  12535. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12536. case taicpu(hp1).opsize of
  12537. S_BW:
  12538. taicpu(hp1).opsize := S_W;
  12539. S_BL, S_WL:
  12540. taicpu(hp1).opsize := S_L;
  12541. else
  12542. InternalError(2022081503);
  12543. end;
  12544. end;
  12545. end
  12546. else if (Shift > 0) and
  12547. (taicpu(p).opsize = S_W) and
  12548. (taicpu(hp1).opsize = S_WL) and
  12549. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12550. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12551. begin
  12552. { Detect:
  12553. shr x, %ax (x > 0)
  12554. ...
  12555. movzwl %ax,%eax
  12556. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12557. }
  12558. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12559. taicpu(hp1).opcode := A_CWDE;
  12560. taicpu(hp1).clearop(0);
  12561. taicpu(hp1).clearop(1);
  12562. taicpu(hp1).ops := 0;
  12563. end;
  12564. { Move onto the next instruction }
  12565. Continue;
  12566. end;
  12567. A_SHL, A_SAL, A_SHR:
  12568. if (taicpu(hp1).opsize <= LimitSize) and
  12569. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12570. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12571. begin
  12572. { Make sure the sizes don't exceed the register size limit
  12573. (measured by the shift value falling below the limit) }
  12574. if taicpu(hp1).opsize < LimitSize then
  12575. LimitSize := taicpu(hp1).opsize;
  12576. if taicpu(hp1).opcode = A_SHR then
  12577. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12578. else
  12579. begin
  12580. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12581. DoNotMerge := True;
  12582. end;
  12583. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12584. Break;
  12585. { Since we've established that the combined shift is within
  12586. limits, we can actually combine the adjacent SHR
  12587. instructions even if they're different sizes }
  12588. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12589. begin
  12590. hp2 := tai(hp1.Previous);
  12591. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12592. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12593. RemoveInstruction(hp1);
  12594. hp1 := hp2;
  12595. end;
  12596. { Move onto the next instruction }
  12597. Continue;
  12598. end;
  12599. else
  12600. ;
  12601. end;
  12602. Break;
  12603. until False;
  12604. { Detect the following (looking backwards):
  12605. shr %cl,%reg
  12606. shr x, %reg
  12607. Swap the two SHR instructions to minimise a pipeline stall.
  12608. }
  12609. if GetLastInstruction(p, hp1) and
  12610. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12611. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12612. { First operand will be %cl }
  12613. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12614. { Just to be sure }
  12615. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12616. begin
  12617. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12618. { Moving the entries this way ensures the register tracking remains correct }
  12619. Asml.Remove(p);
  12620. Asml.InsertBefore(p, hp1);
  12621. p := hp1;
  12622. { Don't set Result to True because the current instruction is now
  12623. "shr %cl,%reg" and there's nothing more we can do with it }
  12624. end;
  12625. end;
  12626. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12627. var
  12628. hp1, hp2: tai;
  12629. Opposite, SecondOpposite: TAsmOp;
  12630. NewCond: TAsmCond;
  12631. begin
  12632. Result := False;
  12633. { Change:
  12634. add/sub 128,(dest)
  12635. To:
  12636. sub/add -128,(dest)
  12637. This generaally takes fewer bytes to encode because -128 can be stored
  12638. in a signed byte, whereas +128 cannot.
  12639. }
  12640. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12641. begin
  12642. if taicpu(p).opcode = A_ADD then
  12643. Opposite := A_SUB
  12644. else
  12645. Opposite := A_ADD;
  12646. { Be careful if the flags are in use, because the CF flag inverts
  12647. when changing from ADD to SUB and vice versa }
  12648. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12649. GetNextInstruction(p, hp1) then
  12650. begin
  12651. TransferUsedRegs(TmpUsedRegs);
  12652. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12653. hp2 := hp1;
  12654. { Scan ahead to check if everything's safe }
  12655. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12656. begin
  12657. if (hp1.typ <> ait_instruction) then
  12658. { Probably unsafe since the flags are still in use }
  12659. Exit;
  12660. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12661. { Stop searching at an unconditional jump }
  12662. Break;
  12663. if not
  12664. (
  12665. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12666. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12667. ) and
  12668. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12669. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12670. Exit;
  12671. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12672. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12673. { Move to the next instruction }
  12674. GetNextInstruction(hp1, hp1);
  12675. end;
  12676. while Assigned(hp2) and (hp2 <> hp1) do
  12677. begin
  12678. NewCond := C_None;
  12679. case taicpu(hp2).condition of
  12680. C_A, C_NBE:
  12681. NewCond := C_BE;
  12682. C_B, C_C, C_NAE:
  12683. NewCond := C_AE;
  12684. C_AE, C_NB, C_NC:
  12685. NewCond := C_B;
  12686. C_BE, C_NA:
  12687. NewCond := C_A;
  12688. else
  12689. { No change needed };
  12690. end;
  12691. if NewCond <> C_None then
  12692. begin
  12693. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12694. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12695. taicpu(hp2).condition := NewCond;
  12696. end
  12697. else
  12698. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12699. begin
  12700. { Because of the flipping of the carry bit, to ensure
  12701. the operation remains equivalent, ADC becomes SBB
  12702. and vice versa, and the constant is not-inverted.
  12703. If multiple ADCs or SBBs appear in a row, each one
  12704. changed causes the carry bit to invert, so they all
  12705. need to be flipped }
  12706. if taicpu(hp2).opcode = A_ADC then
  12707. SecondOpposite := A_SBB
  12708. else
  12709. SecondOpposite := A_ADC;
  12710. if taicpu(hp2).oper[0]^.typ <> top_const then
  12711. { Should have broken out of this optimisation already }
  12712. InternalError(2021112901);
  12713. 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]^) + ' -> ' +
  12714. 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);
  12715. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12716. taicpu(hp2).opcode := SecondOpposite;
  12717. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12718. end;
  12719. { Move to the next instruction }
  12720. GetNextInstruction(hp2, hp2);
  12721. end;
  12722. if (hp2 <> hp1) then
  12723. InternalError(2021111501);
  12724. end;
  12725. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12726. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12727. taicpu(p).opcode := Opposite;
  12728. taicpu(p).oper[0]^.val := -128;
  12729. { No further optimisations can be made on this instruction, so move
  12730. onto the next one to save time }
  12731. p := tai(p.Next);
  12732. UpdateUsedRegs(p);
  12733. Result := True;
  12734. Exit;
  12735. end;
  12736. { Detect:
  12737. add/sub %reg2,(dest)
  12738. add/sub x, (dest)
  12739. (dest can be a register or a reference)
  12740. Swap the instructions to minimise a pipeline stall. This reverses the
  12741. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12742. optimisations could be made.
  12743. }
  12744. if (taicpu(p).oper[0]^.typ = top_reg) and
  12745. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12746. (
  12747. (
  12748. (taicpu(p).oper[1]^.typ = top_reg) and
  12749. { We can try searching further ahead if we're writing to a register }
  12750. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12751. ) or
  12752. (
  12753. (taicpu(p).oper[1]^.typ = top_ref) and
  12754. GetNextInstruction(p, hp1)
  12755. )
  12756. ) and
  12757. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12758. (taicpu(hp1).oper[0]^.typ = top_const) and
  12759. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12760. begin
  12761. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12762. TransferUsedRegs(TmpUsedRegs);
  12763. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12764. hp2 := p;
  12765. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12766. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12767. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12768. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12769. begin
  12770. asml.remove(hp1);
  12771. asml.InsertBefore(hp1, p);
  12772. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12773. Result := True;
  12774. end;
  12775. end;
  12776. end;
  12777. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12778. begin
  12779. Result:=false;
  12780. { change "cmp $0, %reg" to "test %reg, %reg" }
  12781. if MatchOpType(taicpu(p),top_const,top_reg) and
  12782. (taicpu(p).oper[0]^.val = 0) then
  12783. begin
  12784. taicpu(p).opcode := A_TEST;
  12785. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12786. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  12787. Result:=true;
  12788. end;
  12789. end;
  12790. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12791. var
  12792. IsTestConstX, IsValid : Boolean;
  12793. hp1,hp2 : tai;
  12794. begin
  12795. Result:=false;
  12796. { If x is a power of 2 (popcnt = 1), change:
  12797. or $x, %reg/ref
  12798. To:
  12799. bts lb(x), %reg/ref
  12800. }
  12801. if (taicpu(p).opcode = A_OR) and
  12802. IsBTXAcceptable(p) and
  12803. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  12804. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12805. (
  12806. { Don't optimise if a test instruction follows }
  12807. not GetNextInstruction(p, hp1) or
  12808. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  12809. ) then
  12810. begin
  12811. 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);
  12812. taicpu(p).opcode := A_BTS;
  12813. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12814. Result := True;
  12815. Exit;
  12816. end;
  12817. { If x is a power of 2 (popcnt = 1), change:
  12818. test $x, %reg/ref
  12819. je / sete / cmove (or jne / setne)
  12820. To:
  12821. bt lb(x), %reg/ref
  12822. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  12823. }
  12824. if (taicpu(p).opcode = A_TEST) and
  12825. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  12826. (taicpu(p).oper[0]^.typ = top_const) and
  12827. (
  12828. (cs_opt_size in current_settings.optimizerswitches) or
  12829. (
  12830. (taicpu(p).oper[1]^.typ = top_reg) and
  12831. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  12832. ) or
  12833. (
  12834. (taicpu(p).oper[1]^.typ <> top_reg) and
  12835. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  12836. )
  12837. ) and
  12838. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  12839. { For sizes less than S_L, the byte size is equal or larger with BT,
  12840. so don't bother optimising }
  12841. (taicpu(p).opsize >= S_L) then
  12842. begin
  12843. IsValid := True;
  12844. { Check the next set of instructions, watching the FLAGS register
  12845. and the conditions used }
  12846. TransferUsedRegs(TmpUsedRegs);
  12847. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12848. hp1 := p;
  12849. hp2 := nil;
  12850. while GetNextInstruction(hp1, hp1) do
  12851. begin
  12852. if not Assigned(hp2) then
  12853. { The first instruction after TEST }
  12854. hp2 := hp1;
  12855. if (hp1.typ <> ait_instruction) then
  12856. begin
  12857. { If the flags are no longer in use, everything is fine }
  12858. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12859. IsValid := False;
  12860. Break;
  12861. end;
  12862. case taicpu(hp1).condition of
  12863. C_None:
  12864. begin
  12865. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12866. { Something is not quite normal, so play safe and don't change }
  12867. IsValid := False;
  12868. Break;
  12869. end;
  12870. C_E, C_Z, C_NE, C_NZ:
  12871. { This is fine };
  12872. else
  12873. begin
  12874. { Unsupported condition }
  12875. IsValid := False;
  12876. Break;
  12877. end;
  12878. end;
  12879. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12880. end;
  12881. if IsValid then
  12882. begin
  12883. while hp2 <> hp1 do
  12884. begin
  12885. case taicpu(hp2).condition of
  12886. C_Z, C_E:
  12887. taicpu(hp2).condition := C_NC;
  12888. C_NZ, C_NE:
  12889. taicpu(hp2).condition := C_C;
  12890. else
  12891. { Should not get this by this point }
  12892. InternalError(2022110701);
  12893. end;
  12894. GetNextInstruction(hp2, hp2);
  12895. end;
  12896. 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);
  12897. taicpu(p).opcode := A_BT;
  12898. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  12899. Result := True;
  12900. Exit;
  12901. end;
  12902. end;
  12903. { removes the line marked with (x) from the sequence
  12904. and/or/xor/add/sub/... $x, %y
  12905. test/or %y, %y | test $-1, %y (x)
  12906. j(n)z _Label
  12907. as the first instruction already adjusts the ZF
  12908. %y operand may also be a reference }
  12909. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  12910. MatchOperand(taicpu(p).oper[0]^,-1);
  12911. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  12912. GetLastInstruction(p, hp1) and
  12913. (tai(hp1).typ = ait_instruction) and
  12914. GetNextInstruction(p,hp2) and
  12915. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12916. case taicpu(hp1).opcode Of
  12917. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12918. { These two instructions set the zero flag if the result is zero }
  12919. A_POPCNT, A_LZCNT:
  12920. begin
  12921. if (
  12922. { With POPCNT, an input of zero will set the zero flag
  12923. because the population count of zero is zero }
  12924. (taicpu(hp1).opcode = A_POPCNT) and
  12925. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12926. (
  12927. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12928. { Faster than going through the second half of the 'or'
  12929. condition below }
  12930. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12931. )
  12932. ) or (
  12933. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12934. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12935. { and in case of carry for A(E)/B(E)/C/NC }
  12936. (
  12937. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12938. (
  12939. (taicpu(hp1).opcode <> A_ADD) and
  12940. (taicpu(hp1).opcode <> A_SUB) and
  12941. (taicpu(hp1).opcode <> A_LZCNT)
  12942. )
  12943. )
  12944. ) then
  12945. begin
  12946. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  12947. RemoveCurrentP(p, hp2);
  12948. Result:=true;
  12949. Exit;
  12950. end;
  12951. end;
  12952. A_SHL, A_SAL, A_SHR, A_SAR:
  12953. begin
  12954. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12955. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12956. { therefore, it's only safe to do this optimization for }
  12957. { shifts by a (nonzero) constant }
  12958. (taicpu(hp1).oper[0]^.typ = top_const) and
  12959. (taicpu(hp1).oper[0]^.val <> 0) and
  12960. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12961. { and in case of carry for A(E)/B(E)/C/NC }
  12962. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12963. begin
  12964. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  12965. RemoveCurrentP(p, hp2);
  12966. Result:=true;
  12967. Exit;
  12968. end;
  12969. end;
  12970. A_DEC, A_INC, A_NEG:
  12971. begin
  12972. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12973. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12974. { and in case of carry for A(E)/B(E)/C/NC }
  12975. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12976. begin
  12977. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  12978. RemoveCurrentP(p, hp2);
  12979. Result:=true;
  12980. Exit;
  12981. end;
  12982. end;
  12983. A_ANDN, A_BZHI:
  12984. begin
  12985. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  12986. { Only the zero and sign flags are consistent with what the result is }
  12987. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  12988. begin
  12989. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  12990. RemoveCurrentP(p, hp2);
  12991. Result:=true;
  12992. Exit;
  12993. end;
  12994. end;
  12995. A_BEXTR:
  12996. begin
  12997. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  12998. { Only the zero flag is set }
  12999. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13000. begin
  13001. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13002. RemoveCurrentP(p, hp2);
  13003. Result:=true;
  13004. Exit;
  13005. end;
  13006. end;
  13007. else
  13008. ;
  13009. end; { case }
  13010. { change "test $-1,%reg" into "test %reg,%reg" }
  13011. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13012. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13013. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13014. if MatchInstruction(p, A_OR, []) and
  13015. { Can only match if they're both registers }
  13016. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13017. begin
  13018. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13019. taicpu(p).opcode := A_TEST;
  13020. { No need to set Result to True, as we've done all the optimisations we can }
  13021. end;
  13022. end;
  13023. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13024. var
  13025. hp1,hp3 : tai;
  13026. {$ifndef x86_64}
  13027. hp2 : taicpu;
  13028. {$endif x86_64}
  13029. begin
  13030. Result:=false;
  13031. hp3:=nil;
  13032. {$ifndef x86_64}
  13033. { don't do this on modern CPUs, this really hurts them due to
  13034. broken call/ret pairing }
  13035. if (current_settings.optimizecputype < cpu_Pentium2) and
  13036. not(cs_create_pic in current_settings.moduleswitches) and
  13037. GetNextInstruction(p, hp1) and
  13038. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13039. MatchOpType(taicpu(hp1),top_ref) and
  13040. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13041. begin
  13042. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  13043. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  13044. InsertLLItem(p.previous, p, hp2);
  13045. taicpu(p).opcode := A_JMP;
  13046. taicpu(p).is_jmp := true;
  13047. RemoveInstruction(hp1);
  13048. Result:=true;
  13049. end
  13050. else
  13051. {$endif x86_64}
  13052. { replace
  13053. call procname
  13054. ret
  13055. by
  13056. jmp procname
  13057. but do it only on level 4 because it destroys stack back traces
  13058. else if the subroutine is marked as no return, remove the ret
  13059. }
  13060. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  13061. (po_noreturn in current_procinfo.procdef.procoptions)) and
  13062. GetNextInstruction(p, hp1) and
  13063. (MatchInstruction(hp1,A_RET,[S_NO]) or
  13064. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  13065. SetAndTest(hp1,hp3) and
  13066. GetNextInstruction(hp1,hp1) and
  13067. MatchInstruction(hp1,A_RET,[S_NO])
  13068. )
  13069. ) and
  13070. (taicpu(hp1).ops=0) then
  13071. begin
  13072. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13073. { we might destroy stack alignment here if we do not do a call }
  13074. (target_info.stackalign<=sizeof(SizeUInt)) then
  13075. begin
  13076. taicpu(p).opcode := A_JMP;
  13077. taicpu(p).is_jmp := true;
  13078. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  13079. end
  13080. else
  13081. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  13082. RemoveInstruction(hp1);
  13083. if Assigned(hp3) then
  13084. begin
  13085. AsmL.Remove(hp3);
  13086. AsmL.InsertBefore(hp3,p)
  13087. end;
  13088. Result:=true;
  13089. end;
  13090. end;
  13091. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  13092. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  13093. begin
  13094. case OpSize of
  13095. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13096. Result := (Val <= $FF) and (Val >= -128);
  13097. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13098. Result := (Val <= $FFFF) and (Val >= -32768);
  13099. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  13100. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  13101. else
  13102. Result := True;
  13103. end;
  13104. end;
  13105. var
  13106. hp1, hp2 : tai;
  13107. SizeChange: Boolean;
  13108. PreMessage: string;
  13109. begin
  13110. Result := False;
  13111. if (taicpu(p).oper[0]^.typ = top_reg) and
  13112. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13113. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  13114. begin
  13115. { Change (using movzbl %al,%eax as an example):
  13116. movzbl %al, %eax movzbl %al, %eax
  13117. cmpl x, %eax testl %eax,%eax
  13118. To:
  13119. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  13120. movzbl %al, %eax movzbl %al, %eax
  13121. Smaller instruction and minimises pipeline stall as the CPU
  13122. doesn't have to wait for the register to get zero-extended. [Kit]
  13123. Also allow if the smaller of the two registers is being checked,
  13124. as this still removes the false dependency.
  13125. }
  13126. if
  13127. (
  13128. (
  13129. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  13130. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  13131. ) or (
  13132. { If MatchOperand returns True, they must both be registers }
  13133. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  13134. )
  13135. ) and
  13136. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  13137. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  13138. begin
  13139. 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);
  13140. asml.Remove(hp1);
  13141. asml.InsertBefore(hp1, p);
  13142. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  13143. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  13144. begin
  13145. taicpu(hp1).opcode := A_TEST;
  13146. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  13147. end;
  13148. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13149. case taicpu(p).opsize of
  13150. S_BW, S_BL:
  13151. begin
  13152. SizeChange := taicpu(hp1).opsize <> S_B;
  13153. taicpu(hp1).changeopsize(S_B);
  13154. end;
  13155. S_WL:
  13156. begin
  13157. SizeChange := taicpu(hp1).opsize <> S_W;
  13158. taicpu(hp1).changeopsize(S_W);
  13159. end
  13160. else
  13161. InternalError(2020112701);
  13162. end;
  13163. UpdateUsedRegs(tai(p.Next));
  13164. { Check if the register is used aferwards - if not, we can
  13165. remove the movzx instruction completely }
  13166. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  13167. begin
  13168. { Hp1 is a better position than p for debugging purposes }
  13169. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13170. RemoveCurrentp(p, hp1);
  13171. Result := True;
  13172. end;
  13173. if SizeChange then
  13174. DebugMsg(SPeepholeOptimization + PreMessage +
  13175. 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)
  13176. else
  13177. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13178. Exit;
  13179. end;
  13180. { Change (using movzwl %ax,%eax as an example):
  13181. movzwl %ax, %eax
  13182. movb %al, (dest) (Register is smaller than read register in movz)
  13183. To:
  13184. movb %al, (dest) (Move one back to avoid a false dependency)
  13185. movzwl %ax, %eax
  13186. }
  13187. if (taicpu(hp1).opcode = A_MOV) and
  13188. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13189. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13190. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13191. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13192. begin
  13193. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13194. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13195. asml.Remove(hp1);
  13196. asml.InsertBefore(hp1, p);
  13197. if taicpu(hp1).oper[1]^.typ = top_reg then
  13198. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13199. { Check if the register is used aferwards - if not, we can
  13200. remove the movzx instruction completely }
  13201. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13202. begin
  13203. { Hp1 is a better position than p for debugging purposes }
  13204. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13205. RemoveCurrentp(p, hp1);
  13206. Result := True;
  13207. end;
  13208. Exit;
  13209. end;
  13210. end;
  13211. end;
  13212. {$ifdef x86_64}
  13213. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13214. var
  13215. PreMessage, RegName: string;
  13216. begin
  13217. { Code size reduction by J. Gareth "Kit" Moreton }
  13218. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13219. as this removes the REX prefix }
  13220. Result := False;
  13221. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13222. Exit;
  13223. if taicpu(p).oper[0]^.typ <> top_reg then
  13224. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13225. InternalError(2018011500);
  13226. case taicpu(p).opsize of
  13227. S_Q:
  13228. begin
  13229. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13230. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13231. { The actual optimization }
  13232. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13233. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13234. taicpu(p).changeopsize(S_L);
  13235. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13236. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13237. end;
  13238. else
  13239. ;
  13240. end;
  13241. end;
  13242. {$endif}
  13243. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13244. var
  13245. XReg: TRegister;
  13246. begin
  13247. Result := False;
  13248. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  13249. Smaller encoding and slightly faster on some platforms (also works for
  13250. ZMM-sized registers) }
  13251. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  13252. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  13253. begin
  13254. XReg := taicpu(p).oper[0]^.reg;
  13255. if (taicpu(p).oper[1]^.reg = XReg) then
  13256. begin
  13257. taicpu(p).changeopsize(S_XMM);
  13258. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  13259. if (cs_opt_size in current_settings.optimizerswitches) then
  13260. begin
  13261. { Change input registers to %xmm0 to reduce size. Note that
  13262. there's a risk of a false dependency doing this, so only
  13263. optimise for size here }
  13264. XReg := NR_XMM0;
  13265. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  13266. end
  13267. else
  13268. begin
  13269. setsubreg(XReg, R_SUBMMX);
  13270. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  13271. end;
  13272. taicpu(p).oper[0]^.reg := XReg;
  13273. taicpu(p).oper[1]^.reg := XReg;
  13274. Result := True;
  13275. end;
  13276. end;
  13277. end;
  13278. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  13279. var
  13280. OperIdx: Integer;
  13281. begin
  13282. for OperIdx := 0 to p.ops - 1 do
  13283. if p.oper[OperIdx]^.typ = top_ref then
  13284. optimize_ref(p.oper[OperIdx]^.ref^, False);
  13285. end;
  13286. end.