aoptx86.pas 564 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. { Note that Result is set to True if the references COULD overlap but the
  176. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  177. might still overlap because %reg2 could be equal to %reg1-4 }
  178. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  179. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  180. { returns true, if ref is a reference using only the registers passed as base and index
  181. and having an offset }
  182. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  183. implementation
  184. uses
  185. cutils,verbose,
  186. systems,
  187. globals,
  188. cpuinfo,
  189. procinfo,
  190. paramgr,
  191. aasmbase,
  192. aoptbase,aoptutils,
  193. symconst,symsym,
  194. cgx86,
  195. itcpugas;
  196. {$ifdef DEBUG_AOPTCPU}
  197. const
  198. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  199. {$else DEBUG_AOPTCPU}
  200. { Empty strings help the optimizer to remove string concatenations that won't
  201. ever appear to the user on release builds. [Kit] }
  202. const
  203. SPeepholeOptimization = '';
  204. {$endif DEBUG_AOPTCPU}
  205. LIST_STEP_SIZE = 4;
  206. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  207. begin
  208. result :=
  209. (instr.typ = ait_instruction) and
  210. (taicpu(instr).opcode = op) and
  211. ((opsize = []) or (taicpu(instr).opsize in opsize));
  212. end;
  213. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  214. begin
  215. result :=
  216. (instr.typ = ait_instruction) and
  217. ((taicpu(instr).opcode = op1) or
  218. (taicpu(instr).opcode = op2)
  219. ) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize));
  221. end;
  222. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  223. begin
  224. result :=
  225. (instr.typ = ait_instruction) and
  226. ((taicpu(instr).opcode = op1) or
  227. (taicpu(instr).opcode = op2) or
  228. (taicpu(instr).opcode = op3)
  229. ) and
  230. ((opsize = []) or (taicpu(instr).opsize in opsize));
  231. end;
  232. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  233. const opsize : topsizes) : boolean;
  234. var
  235. op : TAsmOp;
  236. begin
  237. result:=false;
  238. if (instr.typ <> ait_instruction) or
  239. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  240. exit;
  241. for op in ops do
  242. begin
  243. if taicpu(instr).opcode = op then
  244. begin
  245. result:=true;
  246. exit;
  247. end;
  248. end;
  249. end;
  250. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  251. begin
  252. result := (oper.typ = top_reg) and (oper.reg = reg);
  253. end;
  254. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  255. begin
  256. result := (oper.typ = top_const) and (oper.val = a);
  257. end;
  258. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  259. begin
  260. result := oper1.typ = oper2.typ;
  261. if result then
  262. case oper1.typ of
  263. top_const:
  264. Result:=oper1.val = oper2.val;
  265. top_reg:
  266. Result:=oper1.reg = oper2.reg;
  267. top_ref:
  268. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  269. else
  270. internalerror(2013102801);
  271. end
  272. end;
  273. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  274. begin
  275. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  276. if result then
  277. case oper1.typ of
  278. top_const:
  279. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  280. top_reg:
  281. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  282. top_ref:
  283. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  284. else
  285. internalerror(2020052401);
  286. end
  287. end;
  288. function RefsEqual(const r1, r2: treference): boolean;
  289. begin
  290. RefsEqual :=
  291. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  292. (r1.relsymbol = r2.relsymbol) and
  293. (r1.segment = r2.segment) and (r1.base = r2.base) and
  294. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  295. (r1.offset = r2.offset) and
  296. (r1.volatility + r2.volatility = []);
  297. end;
  298. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  299. begin
  300. if (r1.symbol<>r2.symbol) then
  301. { If the index registers are different, there's a chance one could
  302. be set so it equals the other symbol }
  303. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  304. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  305. (r1.relsymbol = r2.relsymbol) and
  306. (r1.segment = r2.segment) and (r1.base = r2.base) and
  307. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  308. (r1.volatility + r2.volatility = []) then
  309. { In this case, it all depends on the offsets }
  310. Exit(abs(r1.offset - r2.offset) < Range);
  311. { There's a chance things MIGHT overlap, so take no chances }
  312. Result := True;
  313. end;
  314. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  315. begin
  316. Result:=(ref.offset=0) and
  317. (ref.scalefactor in [0,1]) and
  318. (ref.segment=NR_NO) and
  319. (ref.symbol=nil) and
  320. (ref.relsymbol=nil) and
  321. ((base=NR_INVALID) or
  322. (ref.base=base)) and
  323. ((index=NR_INVALID) or
  324. (ref.index=index)) and
  325. (ref.volatility=[]);
  326. end;
  327. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  328. begin
  329. Result:=(ref.scalefactor in [0,1]) and
  330. (ref.segment=NR_NO) and
  331. (ref.symbol=nil) and
  332. (ref.relsymbol=nil) and
  333. ((base=NR_INVALID) or
  334. (ref.base=base)) and
  335. ((index=NR_INVALID) or
  336. (ref.index=index)) and
  337. (ref.volatility=[]);
  338. end;
  339. function InstrReadsFlags(p: tai): boolean;
  340. begin
  341. InstrReadsFlags := true;
  342. case p.typ of
  343. ait_instruction:
  344. if InsProp[taicpu(p).opcode].Ch*
  345. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  346. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  347. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  348. exit;
  349. ait_label:
  350. exit;
  351. else
  352. ;
  353. end;
  354. InstrReadsFlags := false;
  355. end;
  356. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  357. begin
  358. Next:=Current;
  359. repeat
  360. Result:=GetNextInstruction(Next,Next);
  361. until not (Result) or
  362. not(cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ<>ait_instruction) or
  364. RegInInstruction(reg,Next) or
  365. is_calljmp(taicpu(Next).opcode);
  366. end;
  367. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  368. begin
  369. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  370. Next := Current;
  371. repeat
  372. Result := GetNextInstruction(Next,Next);
  373. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  374. if is_calljmpuncondret(taicpu(Next).opcode) then
  375. begin
  376. Result := False;
  377. Exit;
  378. end
  379. else
  380. CrossJump := True;
  381. until not Result or
  382. not (cs_opt_level3 in current_settings.optimizerswitches) or
  383. (Next.typ <> ait_instruction) or
  384. RegInInstruction(reg,Next);
  385. end;
  386. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  387. begin
  388. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  389. begin
  390. Result:=GetNextInstruction(Current,Next);
  391. exit;
  392. end;
  393. Next:=tai(Current.Next);
  394. Result:=false;
  395. while assigned(Next) do
  396. begin
  397. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  398. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  399. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  400. exit
  401. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  402. begin
  403. Result:=true;
  404. exit;
  405. end;
  406. Next:=tai(Next.Next);
  407. end;
  408. end;
  409. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  410. begin
  411. Result:=RegReadByInstruction(reg,hp);
  412. end;
  413. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  414. var
  415. p: taicpu;
  416. opcount: longint;
  417. begin
  418. RegReadByInstruction := false;
  419. if hp.typ <> ait_instruction then
  420. exit;
  421. p := taicpu(hp);
  422. case p.opcode of
  423. A_CALL:
  424. regreadbyinstruction := true;
  425. A_IMUL:
  426. case p.ops of
  427. 1:
  428. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  429. (
  430. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  431. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  432. );
  433. 2,3:
  434. regReadByInstruction :=
  435. reginop(reg,p.oper[0]^) or
  436. reginop(reg,p.oper[1]^);
  437. else
  438. InternalError(2019112801);
  439. end;
  440. A_MUL:
  441. begin
  442. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  443. (
  444. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  445. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  446. );
  447. end;
  448. A_IDIV,A_DIV:
  449. begin
  450. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  451. (
  452. (getregtype(reg)=R_INTREGISTER) and
  453. (
  454. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  455. )
  456. );
  457. end;
  458. else
  459. begin
  460. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  461. begin
  462. RegReadByInstruction := false;
  463. exit;
  464. end;
  465. for opcount := 0 to p.ops-1 do
  466. if (p.oper[opCount]^.typ = top_ref) and
  467. RegInRef(reg,p.oper[opcount]^.ref^) then
  468. begin
  469. RegReadByInstruction := true;
  470. exit
  471. end;
  472. { special handling for SSE MOVSD }
  473. if (p.opcode=A_MOVSD) and (p.ops>0) then
  474. begin
  475. if p.ops<>2 then
  476. internalerror(2017042702);
  477. regReadByInstruction := reginop(reg,p.oper[0]^) or
  478. (
  479. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  480. );
  481. exit;
  482. end;
  483. with insprop[p.opcode] do
  484. begin
  485. case getregtype(reg) of
  486. R_INTREGISTER:
  487. begin
  488. case getsupreg(reg) of
  489. RS_EAX:
  490. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  491. begin
  492. RegReadByInstruction := true;
  493. exit
  494. end;
  495. RS_ECX:
  496. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  497. begin
  498. RegReadByInstruction := true;
  499. exit
  500. end;
  501. RS_EDX:
  502. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  503. begin
  504. RegReadByInstruction := true;
  505. exit
  506. end;
  507. RS_EBX:
  508. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  509. begin
  510. RegReadByInstruction := true;
  511. exit
  512. end;
  513. RS_ESP:
  514. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  515. begin
  516. RegReadByInstruction := true;
  517. exit
  518. end;
  519. RS_EBP:
  520. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  521. begin
  522. RegReadByInstruction := true;
  523. exit
  524. end;
  525. RS_ESI:
  526. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  527. begin
  528. RegReadByInstruction := true;
  529. exit
  530. end;
  531. RS_EDI:
  532. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  533. begin
  534. RegReadByInstruction := true;
  535. exit
  536. end;
  537. end;
  538. end;
  539. R_MMREGISTER:
  540. begin
  541. case getsupreg(reg) of
  542. RS_XMM0:
  543. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  544. begin
  545. RegReadByInstruction := true;
  546. exit
  547. end;
  548. end;
  549. end;
  550. else
  551. ;
  552. end;
  553. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  554. begin
  555. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  556. begin
  557. case p.condition of
  558. C_A,C_NBE, { CF=0 and ZF=0 }
  559. C_BE,C_NA: { CF=1 or ZF=1 }
  560. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  561. C_AE,C_NB,C_NC, { CF=0 }
  562. C_B,C_NAE,C_C: { CF=1 }
  563. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  564. C_NE,C_NZ, { ZF=0 }
  565. C_E,C_Z: { ZF=1 }
  566. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  567. C_G,C_NLE, { ZF=0 and SF=OF }
  568. C_LE,C_NG: { ZF=1 or SF<>OF }
  569. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  570. C_GE,C_NL, { SF=OF }
  571. C_L,C_NGE: { SF<>OF }
  572. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  573. C_NO, { OF=0 }
  574. C_O: { OF=1 }
  575. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  576. C_NP,C_PO, { PF=0 }
  577. C_P,C_PE: { PF=1 }
  578. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  579. C_NS, { SF=0 }
  580. C_S: { SF=1 }
  581. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  582. else
  583. internalerror(2017042701);
  584. end;
  585. if RegReadByInstruction then
  586. exit;
  587. end;
  588. case getsubreg(reg) of
  589. R_SUBW,R_SUBD,R_SUBQ:
  590. RegReadByInstruction :=
  591. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  592. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  593. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  594. R_SUBFLAGCARRY:
  595. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  596. R_SUBFLAGPARITY:
  597. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  598. R_SUBFLAGAUXILIARY:
  599. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  600. R_SUBFLAGZERO:
  601. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  602. R_SUBFLAGSIGN:
  603. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  604. R_SUBFLAGOVERFLOW:
  605. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  606. R_SUBFLAGINTERRUPT:
  607. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  608. R_SUBFLAGDIRECTION:
  609. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  610. else
  611. internalerror(2017042601);
  612. end;
  613. exit;
  614. end;
  615. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  616. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  617. (p.oper[0]^.reg=p.oper[1]^.reg) then
  618. exit;
  619. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  620. begin
  621. RegReadByInstruction := true;
  622. exit
  623. end;
  624. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  625. begin
  626. RegReadByInstruction := true;
  627. exit
  628. end;
  629. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  630. begin
  631. RegReadByInstruction := true;
  632. exit
  633. end;
  634. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  635. begin
  636. RegReadByInstruction := true;
  637. exit
  638. end;
  639. end;
  640. end;
  641. end;
  642. end;
  643. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  644. begin
  645. result:=false;
  646. if p1.typ<>ait_instruction then
  647. exit;
  648. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  649. exit(true);
  650. if (getregtype(reg)=R_INTREGISTER) and
  651. { change information for xmm movsd are not correct }
  652. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  653. begin
  654. case getsupreg(reg) of
  655. { RS_EAX = RS_RAX on x86-64 }
  656. RS_EAX:
  657. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  658. RS_ECX:
  659. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  660. RS_EDX:
  661. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  662. RS_EBX:
  663. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  664. RS_ESP:
  665. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  666. RS_EBP:
  667. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  668. RS_ESI:
  669. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  670. RS_EDI:
  671. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  672. else
  673. ;
  674. end;
  675. if result then
  676. exit;
  677. end
  678. else if getregtype(reg)=R_MMREGISTER then
  679. begin
  680. case getsupreg(reg) of
  681. RS_XMM0:
  682. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. else
  684. ;
  685. end;
  686. if result then
  687. exit;
  688. end
  689. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  690. begin
  691. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  692. exit(true);
  693. case getsubreg(reg) of
  694. R_SUBFLAGCARRY:
  695. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  696. R_SUBFLAGPARITY:
  697. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  698. R_SUBFLAGAUXILIARY:
  699. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. R_SUBFLAGZERO:
  701. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  702. R_SUBFLAGSIGN:
  703. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  704. R_SUBFLAGOVERFLOW:
  705. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  706. R_SUBFLAGINTERRUPT:
  707. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  708. R_SUBFLAGDIRECTION:
  709. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  710. R_SUBW,R_SUBD,R_SUBQ:
  711. { Everything except the direction bits }
  712. Result:=
  713. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  714. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  715. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  716. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  717. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  718. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  719. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  720. else
  721. ;
  722. end;
  723. if result then
  724. exit;
  725. end
  726. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  727. exit(true);
  728. Result:=inherited RegInInstruction(Reg, p1);
  729. end;
  730. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  731. const
  732. WriteOps: array[0..3] of set of TInsChange =
  733. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  734. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  735. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  736. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  737. var
  738. OperIdx: Integer;
  739. begin
  740. Result := False;
  741. if p1.typ <> ait_instruction then
  742. exit;
  743. with insprop[taicpu(p1).opcode] do
  744. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  745. begin
  746. case getsubreg(reg) of
  747. R_SUBW,R_SUBD,R_SUBQ:
  748. Result :=
  749. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  750. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  751. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  752. R_SUBFLAGCARRY:
  753. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  754. R_SUBFLAGPARITY:
  755. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  756. R_SUBFLAGAUXILIARY:
  757. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  758. R_SUBFLAGZERO:
  759. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  760. R_SUBFLAGSIGN:
  761. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  762. R_SUBFLAGOVERFLOW:
  763. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  764. R_SUBFLAGINTERRUPT:
  765. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  766. R_SUBFLAGDIRECTION:
  767. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  768. else
  769. internalerror(2017042602);
  770. end;
  771. exit;
  772. end;
  773. case taicpu(p1).opcode of
  774. A_CALL:
  775. { We could potentially set Result to False if the register in
  776. question is non-volatile for the subroutine's calling convention,
  777. but this would require detecting the calling convention in use and
  778. also assuming that the routine doesn't contain malformed assembly
  779. language, for example... so it could only be done under -O4 as it
  780. would be considered a side-effect. [Kit] }
  781. Result := True;
  782. A_MOVSD:
  783. { special handling for SSE MOVSD }
  784. if (taicpu(p1).ops>0) then
  785. begin
  786. if taicpu(p1).ops<>2 then
  787. internalerror(2017042703);
  788. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  789. end;
  790. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  791. so fix it here (FK)
  792. }
  793. A_VMOVSS,
  794. A_VMOVSD:
  795. begin
  796. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  797. exit;
  798. end;
  799. A_IMUL:
  800. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  801. else
  802. ;
  803. end;
  804. if Result then
  805. exit;
  806. with insprop[taicpu(p1).opcode] do
  807. begin
  808. if getregtype(reg)=R_INTREGISTER then
  809. begin
  810. case getsupreg(reg) of
  811. RS_EAX:
  812. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  813. begin
  814. Result := True;
  815. exit
  816. end;
  817. RS_ECX:
  818. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  819. begin
  820. Result := True;
  821. exit
  822. end;
  823. RS_EDX:
  824. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  825. begin
  826. Result := True;
  827. exit
  828. end;
  829. RS_EBX:
  830. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  831. begin
  832. Result := True;
  833. exit
  834. end;
  835. RS_ESP:
  836. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  837. begin
  838. Result := True;
  839. exit
  840. end;
  841. RS_EBP:
  842. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  843. begin
  844. Result := True;
  845. exit
  846. end;
  847. RS_ESI:
  848. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  849. begin
  850. Result := True;
  851. exit
  852. end;
  853. RS_EDI:
  854. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  855. begin
  856. Result := True;
  857. exit
  858. end;
  859. end;
  860. end;
  861. for OperIdx := 0 to taicpu(p1).ops - 1 do
  862. if (WriteOps[OperIdx]*Ch<>[]) and
  863. { The register doesn't get modified inside a reference }
  864. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  865. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  866. begin
  867. Result := true;
  868. exit
  869. end;
  870. end;
  871. end;
  872. {$ifdef DEBUG_AOPTCPU}
  873. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  874. begin
  875. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  876. end;
  877. function debug_tostr(i: tcgint): string; inline;
  878. begin
  879. Result := tostr(i);
  880. end;
  881. function debug_regname(r: TRegister): string; inline;
  882. begin
  883. Result := '%' + std_regname(r);
  884. end;
  885. { Debug output function - creates a string representation of an operator }
  886. function debug_operstr(oper: TOper): string;
  887. begin
  888. case oper.typ of
  889. top_const:
  890. Result := '$' + debug_tostr(oper.val);
  891. top_reg:
  892. Result := debug_regname(oper.reg);
  893. top_ref:
  894. begin
  895. if oper.ref^.offset <> 0 then
  896. Result := debug_tostr(oper.ref^.offset) + '('
  897. else
  898. Result := '(';
  899. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  900. begin
  901. Result := Result + debug_regname(oper.ref^.base);
  902. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  903. Result := Result + ',' + debug_regname(oper.ref^.index);
  904. end
  905. else
  906. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  907. Result := Result + debug_regname(oper.ref^.index);
  908. if (oper.ref^.scalefactor > 1) then
  909. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  910. else
  911. Result := Result + ')';
  912. end;
  913. else
  914. Result := '[UNKNOWN]';
  915. end;
  916. end;
  917. function debug_op2str(opcode: tasmop): string; inline;
  918. begin
  919. Result := std_op2str[opcode];
  920. end;
  921. function debug_opsize2str(opsize: topsize): string; inline;
  922. begin
  923. Result := gas_opsize2str[opsize];
  924. end;
  925. {$else DEBUG_AOPTCPU}
  926. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  927. begin
  928. end;
  929. function debug_tostr(i: tcgint): string; inline;
  930. begin
  931. Result := '';
  932. end;
  933. function debug_regname(r: TRegister): string; inline;
  934. begin
  935. Result := '';
  936. end;
  937. function debug_operstr(oper: TOper): string; inline;
  938. begin
  939. Result := '';
  940. end;
  941. function debug_op2str(opcode: tasmop): string; inline;
  942. begin
  943. Result := '';
  944. end;
  945. function debug_opsize2str(opsize: topsize): string; inline;
  946. begin
  947. Result := '';
  948. end;
  949. {$endif DEBUG_AOPTCPU}
  950. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  951. begin
  952. {$ifdef x86_64}
  953. { Always fine on x86-64 }
  954. Result := True;
  955. {$else x86_64}
  956. Result :=
  957. {$ifdef i8086}
  958. (current_settings.cputype >= cpu_386) and
  959. {$endif i8086}
  960. (
  961. { Always accept if optimising for size }
  962. (cs_opt_size in current_settings.optimizerswitches) or
  963. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  964. (current_settings.optimizecputype >= cpu_Pentium2)
  965. );
  966. {$endif x86_64}
  967. end;
  968. { Attempts to allocate a volatile integer register for use between p and hp,
  969. using AUsedRegs for the current register usage information. Returns NR_NO
  970. if no free register could be found }
  971. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  972. var
  973. RegSet: TCPURegisterSet;
  974. CurrentSuperReg: Integer;
  975. CurrentReg: TRegister;
  976. Currentp: tai;
  977. Breakout: Boolean;
  978. begin
  979. Result := NR_NO;
  980. RegSet :=
  981. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  982. current_procinfo.saved_regs_int;
  983. for CurrentSuperReg in RegSet do
  984. begin
  985. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  986. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  987. {$if defined(i386) or defined(i8086)}
  988. { If the target size is 8-bit, make sure we can actually encode it }
  989. and (
  990. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  991. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  992. )
  993. {$endif i386 or i8086}
  994. then
  995. begin
  996. Currentp := p;
  997. Breakout := False;
  998. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  999. begin
  1000. case Currentp.typ of
  1001. ait_instruction:
  1002. begin
  1003. if RegInInstruction(CurrentReg, Currentp) then
  1004. begin
  1005. Breakout := True;
  1006. Break;
  1007. end;
  1008. { Cannot allocate across an unconditional jump }
  1009. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1010. Exit;
  1011. end;
  1012. ait_marker:
  1013. { Don't try anything more if a marker is hit }
  1014. Exit;
  1015. ait_regalloc:
  1016. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1017. begin
  1018. Breakout := True;
  1019. Break;
  1020. end;
  1021. else
  1022. ;
  1023. end;
  1024. end;
  1025. if Breakout then
  1026. { Try the next register }
  1027. Continue;
  1028. { We have a free register available }
  1029. Result := CurrentReg;
  1030. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1031. Exit;
  1032. end;
  1033. end;
  1034. end;
  1035. { Attempts to allocate a volatile MM register for use between p and hp,
  1036. using AUsedRegs for the current register usage information. Returns NR_NO
  1037. if no free register could be found }
  1038. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1039. var
  1040. RegSet: TCPURegisterSet;
  1041. CurrentSuperReg: Integer;
  1042. CurrentReg: TRegister;
  1043. Currentp: tai;
  1044. Breakout: Boolean;
  1045. begin
  1046. Result := NR_NO;
  1047. RegSet :=
  1048. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1049. current_procinfo.saved_regs_mm;
  1050. for CurrentSuperReg in RegSet do
  1051. begin
  1052. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1053. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1054. begin
  1055. Currentp := p;
  1056. Breakout := False;
  1057. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1058. begin
  1059. case Currentp.typ of
  1060. ait_instruction:
  1061. begin
  1062. if RegInInstruction(CurrentReg, Currentp) then
  1063. begin
  1064. Breakout := True;
  1065. Break;
  1066. end;
  1067. { Cannot allocate across an unconditional jump }
  1068. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1069. Exit;
  1070. end;
  1071. ait_marker:
  1072. { Don't try anything more if a marker is hit }
  1073. Exit;
  1074. ait_regalloc:
  1075. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1076. begin
  1077. Breakout := True;
  1078. Break;
  1079. end;
  1080. else
  1081. ;
  1082. end;
  1083. end;
  1084. if Breakout then
  1085. { Try the next register }
  1086. Continue;
  1087. { We have a free register available }
  1088. Result := CurrentReg;
  1089. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1090. Exit;
  1091. end;
  1092. end;
  1093. end;
  1094. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1095. begin
  1096. if not SuperRegistersEqual(reg1,reg2) then
  1097. exit(false);
  1098. if getregtype(reg1)<>R_INTREGISTER then
  1099. exit(true); {because SuperRegisterEqual is true}
  1100. case getsubreg(reg1) of
  1101. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1102. higher, it preserves the high bits, so the new value depends on
  1103. reg2's previous value. In other words, it is equivalent to doing:
  1104. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1105. R_SUBL:
  1106. exit(getsubreg(reg2)=R_SUBL);
  1107. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1108. higher, it actually does a:
  1109. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1110. R_SUBH:
  1111. exit(getsubreg(reg2)=R_SUBH);
  1112. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1113. bits of reg2:
  1114. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1115. R_SUBW:
  1116. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1117. { a write to R_SUBD always overwrites every other subregister,
  1118. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1119. R_SUBD,
  1120. R_SUBQ:
  1121. exit(true);
  1122. else
  1123. internalerror(2017042801);
  1124. end;
  1125. end;
  1126. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1127. begin
  1128. if not SuperRegistersEqual(reg1,reg2) then
  1129. exit(false);
  1130. if getregtype(reg1)<>R_INTREGISTER then
  1131. exit(true); {because SuperRegisterEqual is true}
  1132. case getsubreg(reg1) of
  1133. R_SUBL:
  1134. exit(getsubreg(reg2)<>R_SUBH);
  1135. R_SUBH:
  1136. exit(getsubreg(reg2)<>R_SUBL);
  1137. R_SUBW,
  1138. R_SUBD,
  1139. R_SUBQ:
  1140. exit(true);
  1141. else
  1142. internalerror(2017042802);
  1143. end;
  1144. end;
  1145. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1146. var
  1147. hp1 : tai;
  1148. l : TCGInt;
  1149. begin
  1150. result:=false;
  1151. { changes the code sequence
  1152. shr/sar const1, x
  1153. shl const2, x
  1154. to
  1155. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1156. if GetNextInstruction(p, hp1) and
  1157. MatchInstruction(hp1,A_SHL,[]) and
  1158. (taicpu(p).oper[0]^.typ = top_const) and
  1159. (taicpu(hp1).oper[0]^.typ = top_const) and
  1160. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1161. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1162. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1163. begin
  1164. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1165. not(cs_opt_size in current_settings.optimizerswitches) then
  1166. begin
  1167. { shr/sar const1, %reg
  1168. shl const2, %reg
  1169. with const1 > const2 }
  1170. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1171. taicpu(hp1).opcode := A_AND;
  1172. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1173. case taicpu(p).opsize Of
  1174. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1175. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1176. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1177. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1178. else
  1179. Internalerror(2017050703)
  1180. end;
  1181. end
  1182. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1183. not(cs_opt_size in current_settings.optimizerswitches) then
  1184. begin
  1185. { shr/sar const1, %reg
  1186. shl const2, %reg
  1187. with const1 < const2 }
  1188. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1189. taicpu(p).opcode := A_AND;
  1190. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1191. case taicpu(p).opsize Of
  1192. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1193. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1194. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1195. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1196. else
  1197. Internalerror(2017050702)
  1198. end;
  1199. end
  1200. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1201. begin
  1202. { shr/sar const1, %reg
  1203. shl const2, %reg
  1204. with const1 = const2 }
  1205. taicpu(p).opcode := A_AND;
  1206. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1207. case taicpu(p).opsize Of
  1208. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1209. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1210. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1211. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1212. else
  1213. Internalerror(2017050701)
  1214. end;
  1215. RemoveInstruction(hp1);
  1216. end;
  1217. end;
  1218. end;
  1219. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1220. var
  1221. opsize : topsize;
  1222. hp1 : tai;
  1223. tmpref : treference;
  1224. ShiftValue : Cardinal;
  1225. BaseValue : TCGInt;
  1226. begin
  1227. result:=false;
  1228. opsize:=taicpu(p).opsize;
  1229. { changes certain "imul const, %reg"'s to lea sequences }
  1230. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1231. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1232. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1233. if (taicpu(p).oper[0]^.val = 1) then
  1234. if (taicpu(p).ops = 2) then
  1235. { remove "imul $1, reg" }
  1236. begin
  1237. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1238. Result := RemoveCurrentP(p);
  1239. end
  1240. else
  1241. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1242. begin
  1243. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1244. InsertLLItem(p.previous, p.next, hp1);
  1245. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1246. p.free;
  1247. p := hp1;
  1248. end
  1249. else if ((taicpu(p).ops <= 2) or
  1250. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1251. not(cs_opt_size in current_settings.optimizerswitches) and
  1252. (not(GetNextInstruction(p, hp1)) or
  1253. not((tai(hp1).typ = ait_instruction) and
  1254. ((taicpu(hp1).opcode=A_Jcc) and
  1255. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1256. begin
  1257. {
  1258. imul X, reg1, reg2 to
  1259. lea (reg1,reg1,Y), reg2
  1260. shl ZZ,reg2
  1261. imul XX, reg1 to
  1262. lea (reg1,reg1,YY), reg1
  1263. shl ZZ,reg2
  1264. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1265. it does not exist as a separate optimization target in FPC though.
  1266. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1267. at most two zeros
  1268. }
  1269. reference_reset(tmpref,1,[]);
  1270. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1271. begin
  1272. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1273. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1274. TmpRef.base := taicpu(p).oper[1]^.reg;
  1275. TmpRef.index := taicpu(p).oper[1]^.reg;
  1276. if not(BaseValue in [3,5,9]) then
  1277. Internalerror(2018110101);
  1278. TmpRef.ScaleFactor := BaseValue-1;
  1279. if (taicpu(p).ops = 2) then
  1280. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1281. else
  1282. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1283. AsmL.InsertAfter(hp1,p);
  1284. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1285. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1286. RemoveCurrentP(p, hp1);
  1287. if ShiftValue>0 then
  1288. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1289. end;
  1290. end;
  1291. end;
  1292. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1293. begin
  1294. Result := False;
  1295. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1296. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1297. begin
  1298. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1299. taicpu(p).opcode := A_MOV;
  1300. Result := True;
  1301. end;
  1302. end;
  1303. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1304. var
  1305. p: taicpu absolute hp; { Implicit typecast }
  1306. i: Integer;
  1307. begin
  1308. Result := False;
  1309. if not assigned(hp) or
  1310. (hp.typ <> ait_instruction) then
  1311. Exit;
  1312. Prefetch(insprop[p.opcode]);
  1313. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1314. with insprop[p.opcode] do
  1315. begin
  1316. case getsubreg(reg) of
  1317. R_SUBW,R_SUBD,R_SUBQ:
  1318. Result:=
  1319. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1320. uncommon flags are checked first }
  1321. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1322. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1323. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1324. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1325. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1326. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1327. R_SUBFLAGCARRY:
  1328. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1329. R_SUBFLAGPARITY:
  1330. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1331. R_SUBFLAGAUXILIARY:
  1332. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1333. R_SUBFLAGZERO:
  1334. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1335. R_SUBFLAGSIGN:
  1336. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1337. R_SUBFLAGOVERFLOW:
  1338. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1339. R_SUBFLAGINTERRUPT:
  1340. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1341. R_SUBFLAGDIRECTION:
  1342. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1343. else
  1344. internalerror(2017050501);
  1345. end;
  1346. exit;
  1347. end;
  1348. { Handle special cases first }
  1349. case p.opcode of
  1350. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1351. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1352. begin
  1353. Result :=
  1354. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1355. (p.oper[1]^.typ = top_reg) and
  1356. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1357. (
  1358. (p.oper[0]^.typ = top_const) or
  1359. (
  1360. (p.oper[0]^.typ = top_reg) and
  1361. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1362. ) or (
  1363. (p.oper[0]^.typ = top_ref) and
  1364. not RegInRef(reg,p.oper[0]^.ref^)
  1365. )
  1366. );
  1367. end;
  1368. A_MUL, A_IMUL:
  1369. Result :=
  1370. (
  1371. (p.ops=3) and { IMUL only }
  1372. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1373. (
  1374. (
  1375. (p.oper[1]^.typ=top_reg) and
  1376. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1377. ) or (
  1378. (p.oper[1]^.typ=top_ref) and
  1379. not RegInRef(reg,p.oper[1]^.ref^)
  1380. )
  1381. )
  1382. ) or (
  1383. (
  1384. (p.ops=1) and
  1385. (
  1386. (
  1387. (
  1388. (p.oper[0]^.typ=top_reg) and
  1389. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1390. )
  1391. ) or (
  1392. (p.oper[0]^.typ=top_ref) and
  1393. not RegInRef(reg,p.oper[0]^.ref^)
  1394. )
  1395. ) and (
  1396. (
  1397. (p.opsize=S_B) and
  1398. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1399. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1400. ) or (
  1401. (p.opsize=S_W) and
  1402. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1403. ) or (
  1404. (p.opsize=S_L) and
  1405. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1406. {$ifdef x86_64}
  1407. ) or (
  1408. (p.opsize=S_Q) and
  1409. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1410. {$endif x86_64}
  1411. )
  1412. )
  1413. )
  1414. );
  1415. A_CBW:
  1416. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1417. {$ifndef x86_64}
  1418. A_LDS:
  1419. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1420. A_LES:
  1421. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1422. {$endif not x86_64}
  1423. A_LFS:
  1424. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1425. A_LGS:
  1426. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1427. A_LSS:
  1428. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1429. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1430. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1431. A_LODSB:
  1432. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1433. A_LODSW:
  1434. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1435. {$ifdef x86_64}
  1436. A_LODSQ:
  1437. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1438. {$endif x86_64}
  1439. A_LODSD:
  1440. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1441. A_FSTSW, A_FNSTSW:
  1442. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1443. else
  1444. begin
  1445. with insprop[p.opcode] do
  1446. begin
  1447. if (
  1448. { xor %reg,%reg etc. is classed as a new value }
  1449. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1450. MatchOpType(p, top_reg, top_reg) and
  1451. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1452. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1453. ) then
  1454. begin
  1455. Result := True;
  1456. Exit;
  1457. end;
  1458. { Make sure the entire register is overwritten }
  1459. if (getregtype(reg) = R_INTREGISTER) then
  1460. begin
  1461. if (p.ops > 0) then
  1462. begin
  1463. if RegInOp(reg, p.oper[0]^) then
  1464. begin
  1465. if (p.oper[0]^.typ = top_ref) then
  1466. begin
  1467. if RegInRef(reg, p.oper[0]^.ref^) then
  1468. begin
  1469. Result := False;
  1470. Exit;
  1471. end;
  1472. end
  1473. else if (p.oper[0]^.typ = top_reg) then
  1474. begin
  1475. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1476. begin
  1477. Result := False;
  1478. Exit;
  1479. end
  1480. else if ([Ch_WOp1]*Ch<>[]) then
  1481. begin
  1482. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1483. Result := True
  1484. else
  1485. begin
  1486. Result := False;
  1487. Exit;
  1488. end;
  1489. end;
  1490. end;
  1491. end;
  1492. if (p.ops > 1) then
  1493. begin
  1494. if RegInOp(reg, p.oper[1]^) then
  1495. begin
  1496. if (p.oper[1]^.typ = top_ref) then
  1497. begin
  1498. if RegInRef(reg, p.oper[1]^.ref^) then
  1499. begin
  1500. Result := False;
  1501. Exit;
  1502. end;
  1503. end
  1504. else if (p.oper[1]^.typ = top_reg) then
  1505. begin
  1506. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end
  1511. else if ([Ch_WOp2]*Ch<>[]) then
  1512. begin
  1513. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1514. Result := True
  1515. else
  1516. begin
  1517. Result := False;
  1518. Exit;
  1519. end;
  1520. end;
  1521. end;
  1522. end;
  1523. if (p.ops > 2) then
  1524. begin
  1525. if RegInOp(reg, p.oper[2]^) then
  1526. begin
  1527. if (p.oper[2]^.typ = top_ref) then
  1528. begin
  1529. if RegInRef(reg, p.oper[2]^.ref^) then
  1530. begin
  1531. Result := False;
  1532. Exit;
  1533. end;
  1534. end
  1535. else if (p.oper[2]^.typ = top_reg) then
  1536. begin
  1537. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1538. begin
  1539. Result := False;
  1540. Exit;
  1541. end
  1542. else if ([Ch_WOp3]*Ch<>[]) then
  1543. begin
  1544. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1545. Result := True
  1546. else
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end;
  1551. end;
  1552. end;
  1553. end;
  1554. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1555. begin
  1556. if (p.oper[3]^.typ = top_ref) then
  1557. begin
  1558. if RegInRef(reg, p.oper[3]^.ref^) then
  1559. begin
  1560. Result := False;
  1561. Exit;
  1562. end;
  1563. end
  1564. else if (p.oper[3]^.typ = top_reg) then
  1565. begin
  1566. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1567. begin
  1568. Result := False;
  1569. Exit;
  1570. end
  1571. else if ([Ch_WOp4]*Ch<>[]) then
  1572. begin
  1573. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1574. Result := True
  1575. else
  1576. begin
  1577. Result := False;
  1578. Exit;
  1579. end;
  1580. end;
  1581. end;
  1582. end;
  1583. end;
  1584. end;
  1585. end;
  1586. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1587. case getsupreg(reg) of
  1588. RS_EAX:
  1589. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1590. begin
  1591. Result := True;
  1592. Exit;
  1593. end;
  1594. RS_ECX:
  1595. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1596. begin
  1597. Result := True;
  1598. Exit;
  1599. end;
  1600. RS_EDX:
  1601. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1602. begin
  1603. Result := True;
  1604. Exit;
  1605. end;
  1606. RS_EBX:
  1607. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1608. begin
  1609. Result := True;
  1610. Exit;
  1611. end;
  1612. RS_ESP:
  1613. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1614. begin
  1615. Result := True;
  1616. Exit;
  1617. end;
  1618. RS_EBP:
  1619. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1620. begin
  1621. Result := True;
  1622. Exit;
  1623. end;
  1624. RS_ESI:
  1625. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1626. begin
  1627. Result := True;
  1628. Exit;
  1629. end;
  1630. RS_EDI:
  1631. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1632. begin
  1633. Result := True;
  1634. Exit;
  1635. end;
  1636. else
  1637. ;
  1638. end;
  1639. end;
  1640. end;
  1641. end;
  1642. end;
  1643. end;
  1644. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1645. var
  1646. hp2,hp3 : tai;
  1647. begin
  1648. { some x86-64 issue a NOP before the real exit code }
  1649. if MatchInstruction(p,A_NOP,[]) then
  1650. GetNextInstruction(p,p);
  1651. result:=assigned(p) and (p.typ=ait_instruction) and
  1652. ((taicpu(p).opcode = A_RET) or
  1653. ((taicpu(p).opcode=A_LEAVE) and
  1654. GetNextInstruction(p,hp2) and
  1655. MatchInstruction(hp2,A_RET,[S_NO])
  1656. ) or
  1657. (((taicpu(p).opcode=A_LEA) and
  1658. MatchOpType(taicpu(p),top_ref,top_reg) and
  1659. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1660. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1661. ) and
  1662. GetNextInstruction(p,hp2) and
  1663. MatchInstruction(hp2,A_RET,[S_NO])
  1664. ) or
  1665. ((((taicpu(p).opcode=A_MOV) and
  1666. MatchOpType(taicpu(p),top_reg,top_reg) and
  1667. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1668. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1669. ((taicpu(p).opcode=A_LEA) and
  1670. MatchOpType(taicpu(p),top_ref,top_reg) and
  1671. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1672. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1673. )
  1674. ) and
  1675. GetNextInstruction(p,hp2) and
  1676. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1677. MatchOpType(taicpu(hp2),top_reg) and
  1678. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1679. GetNextInstruction(hp2,hp3) and
  1680. MatchInstruction(hp3,A_RET,[S_NO])
  1681. )
  1682. );
  1683. end;
  1684. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1685. begin
  1686. isFoldableArithOp := False;
  1687. case hp1.opcode of
  1688. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1689. isFoldableArithOp :=
  1690. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1691. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1692. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1693. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1694. (taicpu(hp1).oper[1]^.reg = reg);
  1695. A_INC,A_DEC,A_NEG,A_NOT:
  1696. isFoldableArithOp :=
  1697. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1698. (taicpu(hp1).oper[0]^.reg = reg);
  1699. else
  1700. ;
  1701. end;
  1702. end;
  1703. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1704. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1705. var
  1706. hp2: tai;
  1707. begin
  1708. hp2 := p;
  1709. repeat
  1710. hp2 := tai(hp2.previous);
  1711. if assigned(hp2) and
  1712. (hp2.typ = ait_regalloc) and
  1713. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1714. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1715. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1716. begin
  1717. RemoveInstruction(hp2);
  1718. break;
  1719. end;
  1720. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1721. end;
  1722. begin
  1723. case current_procinfo.procdef.returndef.typ of
  1724. arraydef,recorddef,pointerdef,
  1725. stringdef,enumdef,procdef,objectdef,errordef,
  1726. filedef,setdef,procvardef,
  1727. classrefdef,forwarddef:
  1728. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1729. orddef:
  1730. if current_procinfo.procdef.returndef.size <> 0 then
  1731. begin
  1732. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1733. { for int64/qword }
  1734. if current_procinfo.procdef.returndef.size = 8 then
  1735. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1736. end;
  1737. else
  1738. ;
  1739. end;
  1740. end;
  1741. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1742. var
  1743. hp1,hp2 : tai;
  1744. begin
  1745. result:=false;
  1746. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1747. begin
  1748. { vmova* reg1,reg1
  1749. =>
  1750. <nop> }
  1751. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1752. begin
  1753. RemoveCurrentP(p);
  1754. result:=true;
  1755. exit;
  1756. end
  1757. else if GetNextInstruction(p,hp1) then
  1758. begin
  1759. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1760. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1761. begin
  1762. { vmova* reg1,reg2
  1763. vmova* reg2,reg3
  1764. dealloc reg2
  1765. =>
  1766. vmova* reg1,reg3 }
  1767. TransferUsedRegs(TmpUsedRegs);
  1768. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1769. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1770. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1773. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. exit;
  1777. end
  1778. { special case:
  1779. vmova* reg1,<op>
  1780. vmova* <op>,reg1
  1781. =>
  1782. vmova* reg1,<op> }
  1783. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1784. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1785. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1786. ) then
  1787. begin
  1788. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1789. RemoveInstruction(hp1);
  1790. result:=true;
  1791. exit;
  1792. end
  1793. end
  1794. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1795. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1796. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1797. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1798. ) and
  1799. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1800. begin
  1801. { vmova* reg1,reg2
  1802. vmovs* reg2,<op>
  1803. dealloc reg2
  1804. =>
  1805. vmovs* reg1,reg3 }
  1806. TransferUsedRegs(TmpUsedRegs);
  1807. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1808. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1809. begin
  1810. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1811. taicpu(p).opcode:=taicpu(hp1).opcode;
  1812. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1813. RemoveInstruction(hp1);
  1814. result:=true;
  1815. exit;
  1816. end
  1817. end;
  1818. end;
  1819. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1820. begin
  1821. if MatchInstruction(hp1,[A_VFMADDPD,
  1822. A_VFMADD132PD,
  1823. A_VFMADD132PS,
  1824. A_VFMADD132SD,
  1825. A_VFMADD132SS,
  1826. A_VFMADD213PD,
  1827. A_VFMADD213PS,
  1828. A_VFMADD213SD,
  1829. A_VFMADD213SS,
  1830. A_VFMADD231PD,
  1831. A_VFMADD231PS,
  1832. A_VFMADD231SD,
  1833. A_VFMADD231SS,
  1834. A_VFMADDSUB132PD,
  1835. A_VFMADDSUB132PS,
  1836. A_VFMADDSUB213PD,
  1837. A_VFMADDSUB213PS,
  1838. A_VFMADDSUB231PD,
  1839. A_VFMADDSUB231PS,
  1840. A_VFMSUB132PD,
  1841. A_VFMSUB132PS,
  1842. A_VFMSUB132SD,
  1843. A_VFMSUB132SS,
  1844. A_VFMSUB213PD,
  1845. A_VFMSUB213PS,
  1846. A_VFMSUB213SD,
  1847. A_VFMSUB213SS,
  1848. A_VFMSUB231PD,
  1849. A_VFMSUB231PS,
  1850. A_VFMSUB231SD,
  1851. A_VFMSUB231SS,
  1852. A_VFMSUBADD132PD,
  1853. A_VFMSUBADD132PS,
  1854. A_VFMSUBADD213PD,
  1855. A_VFMSUBADD213PS,
  1856. A_VFMSUBADD231PD,
  1857. A_VFMSUBADD231PS,
  1858. A_VFNMADD132PD,
  1859. A_VFNMADD132PS,
  1860. A_VFNMADD132SD,
  1861. A_VFNMADD132SS,
  1862. A_VFNMADD213PD,
  1863. A_VFNMADD213PS,
  1864. A_VFNMADD213SD,
  1865. A_VFNMADD213SS,
  1866. A_VFNMADD231PD,
  1867. A_VFNMADD231PS,
  1868. A_VFNMADD231SD,
  1869. A_VFNMADD231SS,
  1870. A_VFNMSUB132PD,
  1871. A_VFNMSUB132PS,
  1872. A_VFNMSUB132SD,
  1873. A_VFNMSUB132SS,
  1874. A_VFNMSUB213PD,
  1875. A_VFNMSUB213PS,
  1876. A_VFNMSUB213SD,
  1877. A_VFNMSUB213SS,
  1878. A_VFNMSUB231PD,
  1879. A_VFNMSUB231PS,
  1880. A_VFNMSUB231SD,
  1881. A_VFNMSUB231SS],[S_NO]) and
  1882. { we mix single and double opperations here because we assume that the compiler
  1883. generates vmovapd only after double operations and vmovaps only after single operations }
  1884. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1885. GetNextInstruction(hp1,hp2) and
  1886. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1887. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1888. begin
  1889. TransferUsedRegs(TmpUsedRegs);
  1890. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1891. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1892. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1893. begin
  1894. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1895. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1896. RemoveInstruction(hp2);
  1897. end;
  1898. end
  1899. else if (hp1.typ = ait_instruction) and
  1900. GetNextInstruction(hp1, hp2) and
  1901. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1902. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1903. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1904. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1905. (((taicpu(p).opcode=A_MOVAPS) and
  1906. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1907. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1908. ((taicpu(p).opcode=A_MOVAPD) and
  1909. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1910. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1911. ) then
  1912. { change
  1913. movapX reg,reg2
  1914. addsX/subsX/... reg3, reg2
  1915. movapX reg2,reg
  1916. to
  1917. addsX/subsX/... reg3,reg
  1918. }
  1919. begin
  1920. TransferUsedRegs(TmpUsedRegs);
  1921. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1922. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1923. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1924. begin
  1925. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1926. debug_op2str(taicpu(p).opcode)+' '+
  1927. debug_op2str(taicpu(hp1).opcode)+' '+
  1928. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1929. { we cannot eliminate the first move if
  1930. the operations uses the same register for source and dest }
  1931. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1932. RemoveCurrentP(p, nil);
  1933. p:=hp1;
  1934. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1935. RemoveInstruction(hp2);
  1936. result:=true;
  1937. end;
  1938. end
  1939. else if (hp1.typ = ait_instruction) and
  1940. (((taicpu(p).opcode=A_VMOVAPD) and
  1941. (taicpu(hp1).opcode=A_VCOMISD)) or
  1942. ((taicpu(p).opcode=A_VMOVAPS) and
  1943. ((taicpu(hp1).opcode=A_VCOMISS))
  1944. )
  1945. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1946. { change
  1947. movapX reg,reg1
  1948. vcomisX reg1,reg1
  1949. to
  1950. vcomisX reg,reg
  1951. }
  1952. begin
  1953. TransferUsedRegs(TmpUsedRegs);
  1954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1955. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1956. begin
  1957. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1958. debug_op2str(taicpu(p).opcode)+' '+
  1959. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1960. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1961. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  1962. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1963. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  1964. RemoveCurrentP(p, nil);
  1965. result:=true;
  1966. exit;
  1967. end;
  1968. end
  1969. end;
  1970. end;
  1971. end;
  1972. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1973. var
  1974. hp1 : tai;
  1975. begin
  1976. result:=false;
  1977. { replace
  1978. V<Op>X %mreg1,%mreg2,%mreg3
  1979. VMovX %mreg3,%mreg4
  1980. dealloc %mreg3
  1981. by
  1982. V<Op>X %mreg1,%mreg2,%mreg4
  1983. ?
  1984. }
  1985. if GetNextInstruction(p,hp1) and
  1986. { we mix single and double operations here because we assume that the compiler
  1987. generates vmovapd only after double operations and vmovaps only after single operations }
  1988. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1989. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1990. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1991. begin
  1992. TransferUsedRegs(TmpUsedRegs);
  1993. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1994. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1995. begin
  1996. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1997. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1998. RemoveInstruction(hp1);
  1999. result:=true;
  2000. end;
  2001. end;
  2002. end;
  2003. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2004. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2005. begin
  2006. Result := False;
  2007. { For safety reasons, only check for exact register matches }
  2008. { Check base register }
  2009. if (ref.base = AOldReg) then
  2010. begin
  2011. ref.base := ANewReg;
  2012. Result := True;
  2013. end;
  2014. { Check index register }
  2015. if (ref.index = AOldReg) then
  2016. begin
  2017. ref.index := ANewReg;
  2018. Result := True;
  2019. end;
  2020. end;
  2021. { Replaces all references to AOldReg in an operand to ANewReg }
  2022. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2023. var
  2024. OldSupReg, NewSupReg: TSuperRegister;
  2025. OldSubReg, NewSubReg: TSubRegister;
  2026. OldRegType: TRegisterType;
  2027. ThisOper: POper;
  2028. begin
  2029. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2030. Result := False;
  2031. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2032. InternalError(2020011801);
  2033. OldSupReg := getsupreg(AOldReg);
  2034. OldSubReg := getsubreg(AOldReg);
  2035. OldRegType := getregtype(AOldReg);
  2036. NewSupReg := getsupreg(ANewReg);
  2037. NewSubReg := getsubreg(ANewReg);
  2038. if OldRegType <> getregtype(ANewReg) then
  2039. InternalError(2020011802);
  2040. if OldSubReg <> NewSubReg then
  2041. InternalError(2020011803);
  2042. case ThisOper^.typ of
  2043. top_reg:
  2044. if (
  2045. (ThisOper^.reg = AOldReg) or
  2046. (
  2047. (OldRegType = R_INTREGISTER) and
  2048. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2049. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2050. (
  2051. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2052. {$ifndef x86_64}
  2053. and (
  2054. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2055. don't have an 8-bit representation }
  2056. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2057. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2058. )
  2059. {$endif x86_64}
  2060. )
  2061. )
  2062. ) then
  2063. begin
  2064. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2065. Result := True;
  2066. end;
  2067. top_ref:
  2068. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2069. Result := True;
  2070. else
  2071. ;
  2072. end;
  2073. end;
  2074. { Replaces all references to AOldReg in an instruction to ANewReg }
  2075. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2076. const
  2077. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2078. var
  2079. OperIdx: Integer;
  2080. begin
  2081. Result := False;
  2082. for OperIdx := 0 to p.ops - 1 do
  2083. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2084. begin
  2085. { The shift and rotate instructions can only use CL }
  2086. if not (
  2087. (OperIdx = 0) and
  2088. { This second condition just helps to avoid unnecessarily
  2089. calling MatchInstruction for 10 different opcodes }
  2090. (p.oper[0]^.reg = NR_CL) and
  2091. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2092. ) then
  2093. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2094. end
  2095. else if p.oper[OperIdx]^.typ = top_ref then
  2096. { It's okay to replace registers in references that get written to }
  2097. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2098. end;
  2099. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2100. begin
  2101. with ref^ do
  2102. Result :=
  2103. (index = NR_NO) and
  2104. (
  2105. {$ifdef x86_64}
  2106. (
  2107. (base = NR_RIP) and
  2108. (refaddr in [addr_pic, addr_pic_no_got])
  2109. ) or
  2110. {$endif x86_64}
  2111. (base = NR_STACK_POINTER_REG) or
  2112. (base = current_procinfo.framepointer)
  2113. );
  2114. end;
  2115. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2116. var
  2117. l: asizeint;
  2118. begin
  2119. Result := False;
  2120. { Should have been checked previously }
  2121. if p.opcode <> A_LEA then
  2122. InternalError(2020072501);
  2123. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2124. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2125. not(cs_opt_size in current_settings.optimizerswitches) then
  2126. exit;
  2127. with p.oper[0]^.ref^ do
  2128. begin
  2129. if (base <> p.oper[1]^.reg) or
  2130. (index <> NR_NO) or
  2131. assigned(symbol) then
  2132. exit;
  2133. l:=offset;
  2134. if (l=1) and UseIncDec then
  2135. begin
  2136. p.opcode:=A_INC;
  2137. p.loadreg(0,p.oper[1]^.reg);
  2138. p.ops:=1;
  2139. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2140. end
  2141. else if (l=-1) and UseIncDec then
  2142. begin
  2143. p.opcode:=A_DEC;
  2144. p.loadreg(0,p.oper[1]^.reg);
  2145. p.ops:=1;
  2146. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2147. end
  2148. else
  2149. begin
  2150. if (l<0) and (l<>-2147483648) then
  2151. begin
  2152. p.opcode:=A_SUB;
  2153. p.loadConst(0,-l);
  2154. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2155. end
  2156. else
  2157. begin
  2158. p.opcode:=A_ADD;
  2159. p.loadConst(0,l);
  2160. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2161. end;
  2162. end;
  2163. end;
  2164. Result := True;
  2165. end;
  2166. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2167. var
  2168. CurrentReg, ReplaceReg: TRegister;
  2169. begin
  2170. Result := False;
  2171. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2172. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2173. case hp.opcode of
  2174. A_FSTSW, A_FNSTSW,
  2175. A_IN, A_INS, A_OUT, A_OUTS,
  2176. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2177. { These routines have explicit operands, but they are restricted in
  2178. what they can be (e.g. IN and OUT can only read from AL, AX or
  2179. EAX. }
  2180. Exit;
  2181. A_IMUL:
  2182. begin
  2183. { The 1-operand version writes to implicit registers
  2184. The 2-operand version reads from the first operator, and reads
  2185. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2186. the 3-operand version reads from a register that it doesn't write to
  2187. }
  2188. case hp.ops of
  2189. 1:
  2190. if (
  2191. (
  2192. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2193. ) or
  2194. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2195. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2196. begin
  2197. Result := True;
  2198. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2199. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2200. end;
  2201. 2:
  2202. { Only modify the first parameter }
  2203. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2204. begin
  2205. Result := True;
  2206. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2207. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2208. end;
  2209. 3:
  2210. { Only modify the second parameter }
  2211. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2212. begin
  2213. Result := True;
  2214. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2215. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2216. end;
  2217. else
  2218. InternalError(2020012901);
  2219. end;
  2220. end;
  2221. else
  2222. if (hp.ops > 0) and
  2223. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2224. begin
  2225. Result := True;
  2226. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2227. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2228. end;
  2229. end;
  2230. end;
  2231. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2232. var
  2233. hp1, hp2, hp3: tai;
  2234. DoOptimisation, TempBool: Boolean;
  2235. {$ifdef x86_64}
  2236. NewConst: TCGInt;
  2237. {$endif x86_64}
  2238. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2239. begin
  2240. if taicpu(hp1).opcode = signed_movop then
  2241. begin
  2242. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2243. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2244. end
  2245. else
  2246. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2247. end;
  2248. function TryConstMerge(var p1, p2: tai): Boolean;
  2249. var
  2250. ThisRef: TReference;
  2251. begin
  2252. Result := False;
  2253. ThisRef := taicpu(p2).oper[1]^.ref^;
  2254. { Only permit writes to the stack, since we can guarantee alignment with that }
  2255. if (ThisRef.index = NR_NO) and
  2256. (
  2257. (ThisRef.base = NR_STACK_POINTER_REG) or
  2258. (ThisRef.base = current_procinfo.framepointer)
  2259. ) then
  2260. begin
  2261. case taicpu(p).opsize of
  2262. S_B:
  2263. begin
  2264. { Word writes must be on a 2-byte boundary }
  2265. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2266. begin
  2267. { Reduce offset of second reference to see if it is sequential with the first }
  2268. Dec(ThisRef.offset, 1);
  2269. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2270. begin
  2271. { Make sure the constants aren't represented as a
  2272. negative number, as these won't merge properly }
  2273. taicpu(p1).opsize := S_W;
  2274. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2275. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2276. RemoveInstruction(p2);
  2277. Result := True;
  2278. end;
  2279. end;
  2280. end;
  2281. S_W:
  2282. begin
  2283. { Longword writes must be on a 4-byte boundary }
  2284. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2285. begin
  2286. { Reduce offset of second reference to see if it is sequential with the first }
  2287. Dec(ThisRef.offset, 2);
  2288. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2289. begin
  2290. { Make sure the constants aren't represented as a
  2291. negative number, as these won't merge properly }
  2292. taicpu(p1).opsize := S_L;
  2293. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2294. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2295. RemoveInstruction(p2);
  2296. Result := True;
  2297. end;
  2298. end;
  2299. end;
  2300. {$ifdef x86_64}
  2301. S_L:
  2302. begin
  2303. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2304. see if the constants can be encoded this way. }
  2305. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2306. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2307. { Quadword writes must be on an 8-byte boundary }
  2308. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2309. begin
  2310. { Reduce offset of second reference to see if it is sequential with the first }
  2311. Dec(ThisRef.offset, 4);
  2312. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2313. begin
  2314. { Make sure the constants aren't represented as a
  2315. negative number, as these won't merge properly }
  2316. taicpu(p1).opsize := S_Q;
  2317. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2318. taicpu(p1).oper[0]^.val := NewConst;
  2319. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2320. RemoveInstruction(p2);
  2321. Result := True;
  2322. end;
  2323. end;
  2324. end;
  2325. {$endif x86_64}
  2326. else
  2327. ;
  2328. end;
  2329. end;
  2330. end;
  2331. var
  2332. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2333. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2334. NewSize: topsize;
  2335. CurrentReg, ActiveReg: TRegister;
  2336. SourceRef, TargetRef: TReference;
  2337. MovAligned, MovUnaligned: TAsmOp;
  2338. ThisRef: TReference;
  2339. begin
  2340. Result:=false;
  2341. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2342. { remove mov reg1,reg1? }
  2343. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2344. then
  2345. begin
  2346. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2347. { take care of the register (de)allocs following p }
  2348. RemoveCurrentP(p, hp1);
  2349. Result:=true;
  2350. exit;
  2351. end;
  2352. { All the next optimisations require a next instruction }
  2353. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2354. Exit;
  2355. { Look for:
  2356. mov %reg1,%reg2
  2357. ??? %reg2,r/m
  2358. Change to:
  2359. mov %reg1,%reg2
  2360. ??? %reg1,r/m
  2361. }
  2362. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2363. begin
  2364. CurrentReg := taicpu(p).oper[1]^.reg;
  2365. if RegReadByInstruction(CurrentReg, hp1) and
  2366. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2367. begin
  2368. { A change has occurred, just not in p }
  2369. Result := True;
  2370. TransferUsedRegs(TmpUsedRegs);
  2371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2372. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2373. { Just in case something didn't get modified (e.g. an
  2374. implicit register) }
  2375. not RegReadByInstruction(CurrentReg, hp1) then
  2376. begin
  2377. { We can remove the original MOV }
  2378. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2379. RemoveCurrentp(p, hp1);
  2380. { UsedRegs got updated by RemoveCurrentp }
  2381. Result := True;
  2382. Exit;
  2383. end;
  2384. { If we know a MOV instruction has become a null operation, we might as well
  2385. get rid of it now to save time. }
  2386. if (taicpu(hp1).opcode = A_MOV) and
  2387. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2388. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2389. { Just being a register is enough to confirm it's a null operation }
  2390. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2391. begin
  2392. Result := True;
  2393. { Speed-up to reduce a pipeline stall... if we had something like...
  2394. movl %eax,%edx
  2395. movw %dx,%ax
  2396. ... the second instruction would change to movw %ax,%ax, but
  2397. given that it is now %ax that's active rather than %eax,
  2398. penalties might occur due to a partial register write, so instead,
  2399. change it to a MOVZX instruction when optimising for speed.
  2400. }
  2401. if not (cs_opt_size in current_settings.optimizerswitches) and
  2402. IsMOVZXAcceptable and
  2403. (taicpu(hp1).opsize < taicpu(p).opsize)
  2404. {$ifdef x86_64}
  2405. { operations already implicitly set the upper 64 bits to zero }
  2406. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2407. {$endif x86_64}
  2408. then
  2409. begin
  2410. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2411. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2412. case taicpu(p).opsize of
  2413. S_W:
  2414. if taicpu(hp1).opsize = S_B then
  2415. taicpu(hp1).opsize := S_BL
  2416. else
  2417. InternalError(2020012911);
  2418. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2419. case taicpu(hp1).opsize of
  2420. S_B:
  2421. taicpu(hp1).opsize := S_BL;
  2422. S_W:
  2423. taicpu(hp1).opsize := S_WL;
  2424. else
  2425. InternalError(2020012912);
  2426. end;
  2427. else
  2428. InternalError(2020012910);
  2429. end;
  2430. taicpu(hp1).opcode := A_MOVZX;
  2431. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2432. end
  2433. else
  2434. begin
  2435. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2436. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2437. RemoveInstruction(hp1);
  2438. { The instruction after what was hp1 is now the immediate next instruction,
  2439. so we can continue to make optimisations if it's present }
  2440. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2441. Exit;
  2442. hp1 := hp2;
  2443. end;
  2444. end;
  2445. end;
  2446. end;
  2447. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2448. overwrites the original destination register. e.g.
  2449. movl ###,%reg2d
  2450. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2451. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2452. }
  2453. if (taicpu(p).oper[1]^.typ = top_reg) and
  2454. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2455. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2456. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2457. begin
  2458. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2459. begin
  2460. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2461. case taicpu(p).oper[0]^.typ of
  2462. top_const:
  2463. { We have something like:
  2464. movb $x, %regb
  2465. movzbl %regb,%regd
  2466. Change to:
  2467. movl $x, %regd
  2468. }
  2469. begin
  2470. case taicpu(hp1).opsize of
  2471. S_BW:
  2472. begin
  2473. convert_mov_value(A_MOVSX, $FF);
  2474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2475. taicpu(p).opsize := S_W;
  2476. end;
  2477. S_BL:
  2478. begin
  2479. convert_mov_value(A_MOVSX, $FF);
  2480. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2481. taicpu(p).opsize := S_L;
  2482. end;
  2483. S_WL:
  2484. begin
  2485. convert_mov_value(A_MOVSX, $FFFF);
  2486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2487. taicpu(p).opsize := S_L;
  2488. end;
  2489. {$ifdef x86_64}
  2490. S_BQ:
  2491. begin
  2492. convert_mov_value(A_MOVSX, $FF);
  2493. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2494. taicpu(p).opsize := S_Q;
  2495. end;
  2496. S_WQ:
  2497. begin
  2498. convert_mov_value(A_MOVSX, $FFFF);
  2499. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2500. taicpu(p).opsize := S_Q;
  2501. end;
  2502. S_LQ:
  2503. begin
  2504. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2505. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2506. taicpu(p).opsize := S_Q;
  2507. end;
  2508. {$endif x86_64}
  2509. else
  2510. { If hp1 was a MOV instruction, it should have been
  2511. optimised already }
  2512. InternalError(2020021001);
  2513. end;
  2514. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2515. RemoveInstruction(hp1);
  2516. Result := True;
  2517. Exit;
  2518. end;
  2519. top_ref:
  2520. begin
  2521. { We have something like:
  2522. movb mem, %regb
  2523. movzbl %regb,%regd
  2524. Change to:
  2525. movzbl mem, %regd
  2526. }
  2527. ThisRef := taicpu(p).oper[0]^.ref^;
  2528. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2529. begin
  2530. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2531. taicpu(hp1).loadref(0, ThisRef);
  2532. { Make sure any registers in the references are properly tracked }
  2533. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2534. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2535. if (ThisRef.index <> NR_NO) then
  2536. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2537. RemoveCurrentP(p, hp1);
  2538. Result := True;
  2539. Exit;
  2540. end;
  2541. end;
  2542. else
  2543. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2544. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2545. Exit;
  2546. end;
  2547. end
  2548. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2549. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2550. optimised }
  2551. else
  2552. begin
  2553. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2554. RemoveCurrentP(p, hp1);
  2555. Result := True;
  2556. Exit;
  2557. end;
  2558. end;
  2559. if (taicpu(hp1).opcode = A_AND) and
  2560. (taicpu(p).oper[1]^.typ = top_reg) and
  2561. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2562. begin
  2563. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2564. begin
  2565. case taicpu(p).opsize of
  2566. S_L:
  2567. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2568. begin
  2569. { Optimize out:
  2570. mov x, %reg
  2571. and ffffffffh, %reg
  2572. }
  2573. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2574. RemoveInstruction(hp1);
  2575. Result:=true;
  2576. exit;
  2577. end;
  2578. S_Q: { TODO: Confirm if this is even possible }
  2579. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2580. begin
  2581. { Optimize out:
  2582. mov x, %reg
  2583. and ffffffffffffffffh, %reg
  2584. }
  2585. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2586. RemoveInstruction(hp1);
  2587. Result:=true;
  2588. exit;
  2589. end;
  2590. else
  2591. ;
  2592. end;
  2593. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2594. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2595. GetNextInstruction(hp1,hp2) and
  2596. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2597. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2598. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2599. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2600. GetNextInstruction(hp2,hp3) and
  2601. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2602. (taicpu(hp3).condition in [C_E,C_NE]) then
  2603. begin
  2604. TransferUsedRegs(TmpUsedRegs);
  2605. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2606. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2607. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2608. begin
  2609. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2610. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2611. taicpu(hp1).opcode:=A_TEST;
  2612. RemoveInstruction(hp2);
  2613. RemoveCurrentP(p, hp1);
  2614. Result:=true;
  2615. exit;
  2616. end;
  2617. end;
  2618. end
  2619. else if IsMOVZXAcceptable and
  2620. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2621. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2622. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2623. then
  2624. begin
  2625. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2626. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2627. case taicpu(p).opsize of
  2628. S_B:
  2629. if (taicpu(hp1).oper[0]^.val = $ff) then
  2630. begin
  2631. { Convert:
  2632. movb x, %regl movb x, %regl
  2633. andw ffh, %regw andl ffh, %regd
  2634. To:
  2635. movzbw x, %regd movzbl x, %regd
  2636. (Identical registers, just different sizes)
  2637. }
  2638. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2639. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2640. case taicpu(hp1).opsize of
  2641. S_W: NewSize := S_BW;
  2642. S_L: NewSize := S_BL;
  2643. {$ifdef x86_64}
  2644. S_Q: NewSize := S_BQ;
  2645. {$endif x86_64}
  2646. else
  2647. InternalError(2018011510);
  2648. end;
  2649. end
  2650. else
  2651. NewSize := S_NO;
  2652. S_W:
  2653. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2654. begin
  2655. { Convert:
  2656. movw x, %regw
  2657. andl ffffh, %regd
  2658. To:
  2659. movzwl x, %regd
  2660. (Identical registers, just different sizes)
  2661. }
  2662. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2663. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2664. case taicpu(hp1).opsize of
  2665. S_L: NewSize := S_WL;
  2666. {$ifdef x86_64}
  2667. S_Q: NewSize := S_WQ;
  2668. {$endif x86_64}
  2669. else
  2670. InternalError(2018011511);
  2671. end;
  2672. end
  2673. else
  2674. NewSize := S_NO;
  2675. else
  2676. NewSize := S_NO;
  2677. end;
  2678. if NewSize <> S_NO then
  2679. begin
  2680. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2681. { The actual optimization }
  2682. taicpu(p).opcode := A_MOVZX;
  2683. taicpu(p).changeopsize(NewSize);
  2684. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2685. { Safeguard if "and" is followed by a conditional command }
  2686. TransferUsedRegs(TmpUsedRegs);
  2687. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2688. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2689. begin
  2690. { At this point, the "and" command is effectively equivalent to
  2691. "test %reg,%reg". This will be handled separately by the
  2692. Peephole Optimizer. [Kit] }
  2693. DebugMsg(SPeepholeOptimization + PreMessage +
  2694. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2695. end
  2696. else
  2697. begin
  2698. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2699. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2700. RemoveInstruction(hp1);
  2701. end;
  2702. Result := True;
  2703. Exit;
  2704. end;
  2705. end;
  2706. end;
  2707. if (taicpu(hp1).opcode = A_OR) and
  2708. (taicpu(p).oper[1]^.typ = top_reg) and
  2709. MatchOperand(taicpu(p).oper[0]^, 0) and
  2710. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2711. begin
  2712. { mov 0, %reg
  2713. or ###,%reg
  2714. Change to (only if the flags are not used):
  2715. mov ###,%reg
  2716. }
  2717. TransferUsedRegs(TmpUsedRegs);
  2718. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2719. DoOptimisation := True;
  2720. { Even if the flags are used, we might be able to do the optimisation
  2721. if the conditions are predictable }
  2722. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2723. begin
  2724. { Only perform if ### = %reg (the same register) or equal to 0,
  2725. so %reg is guaranteed to still have a value of zero }
  2726. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2727. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2728. begin
  2729. hp2 := hp1;
  2730. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2731. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2732. GetNextInstruction(hp2, hp3) do
  2733. begin
  2734. { Don't continue modifying if the flags state is getting changed }
  2735. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2736. Break;
  2737. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2738. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2739. begin
  2740. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2741. begin
  2742. { Condition is always true }
  2743. case taicpu(hp3).opcode of
  2744. A_Jcc:
  2745. begin
  2746. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2747. { Check for jump shortcuts before we destroy the condition }
  2748. DoJumpOptimizations(hp3, TempBool);
  2749. MakeUnconditional(taicpu(hp3));
  2750. Result := True;
  2751. end;
  2752. A_CMOVcc:
  2753. begin
  2754. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2755. taicpu(hp3).opcode := A_MOV;
  2756. taicpu(hp3).condition := C_None;
  2757. Result := True;
  2758. end;
  2759. A_SETcc:
  2760. begin
  2761. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2762. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2763. taicpu(hp3).opcode := A_MOV;
  2764. taicpu(hp3).ops := 2;
  2765. taicpu(hp3).condition := C_None;
  2766. taicpu(hp3).opsize := S_B;
  2767. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2768. taicpu(hp3).loadconst(0, 1);
  2769. Result := True;
  2770. end;
  2771. else
  2772. InternalError(2021090701);
  2773. end;
  2774. end
  2775. 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
  2776. begin
  2777. { Condition is always false }
  2778. case taicpu(hp3).opcode of
  2779. A_Jcc:
  2780. begin
  2781. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2782. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2783. RemoveInstruction(hp3);
  2784. Result := True;
  2785. { Since hp3 was deleted, hp2 must not be updated }
  2786. Continue;
  2787. end;
  2788. A_CMOVcc:
  2789. begin
  2790. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2791. RemoveInstruction(hp3);
  2792. Result := True;
  2793. { Since hp3 was deleted, hp2 must not be updated }
  2794. Continue;
  2795. end;
  2796. A_SETcc:
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2799. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2800. taicpu(hp3).opcode := A_MOV;
  2801. taicpu(hp3).ops := 2;
  2802. taicpu(hp3).condition := C_None;
  2803. taicpu(hp3).opsize := S_B;
  2804. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2805. taicpu(hp3).loadconst(0, 0);
  2806. Result := True;
  2807. end;
  2808. else
  2809. InternalError(2021090702);
  2810. end;
  2811. end
  2812. else
  2813. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2814. DoOptimisation := False;
  2815. end;
  2816. hp2 := hp3;
  2817. end;
  2818. { Flags are still in use - don't optimise }
  2819. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2820. DoOptimisation := False;
  2821. end
  2822. else
  2823. DoOptimisation := False;
  2824. end;
  2825. if DoOptimisation then
  2826. begin
  2827. {$ifdef x86_64}
  2828. { OR only supports 32-bit sign-extended constants for 64-bit
  2829. instructions, so compensate for this if the constant is
  2830. encoded as a value greater than or equal to 2^31 }
  2831. if (taicpu(hp1).opsize = S_Q) and
  2832. (taicpu(hp1).oper[0]^.typ = top_const) and
  2833. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2834. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2835. {$endif x86_64}
  2836. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2837. taicpu(hp1).opcode := A_MOV;
  2838. RemoveCurrentP(p, hp1);
  2839. Result := True;
  2840. Exit;
  2841. end;
  2842. end;
  2843. { Next instruction is also a MOV ? }
  2844. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2845. begin
  2846. if MatchOpType(taicpu(p), top_const, top_ref) and
  2847. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2848. TryConstMerge(p, hp1) then
  2849. begin
  2850. Result := True;
  2851. { In case we have four byte writes in a row, check for 2 more
  2852. right now so we don't have to wait for another iteration of
  2853. pass 1
  2854. }
  2855. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2856. case taicpu(p).opsize of
  2857. S_W:
  2858. begin
  2859. if GetNextInstruction(p, hp1) and
  2860. MatchInstruction(hp1, A_MOV, [S_B]) and
  2861. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2862. GetNextInstruction(hp1, hp2) and
  2863. MatchInstruction(hp2, A_MOV, [S_B]) and
  2864. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2865. { Try to merge the two bytes }
  2866. TryConstMerge(hp1, hp2) then
  2867. { Now try to merge the two words (hp2 will get deleted) }
  2868. TryConstMerge(p, hp1);
  2869. end;
  2870. S_L:
  2871. begin
  2872. { Though this only really benefits x86_64 and not i386, it
  2873. gets a potential optimisation done faster and hence
  2874. reduces the number of times OptPass1MOV is entered }
  2875. if GetNextInstruction(p, hp1) and
  2876. MatchInstruction(hp1, A_MOV, [S_W]) and
  2877. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2878. GetNextInstruction(hp1, hp2) and
  2879. MatchInstruction(hp2, A_MOV, [S_W]) and
  2880. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2881. { Try to merge the two words }
  2882. TryConstMerge(hp1, hp2) then
  2883. { This will always fail on i386, so don't bother
  2884. calling it unless we're doing x86_64 }
  2885. {$ifdef x86_64}
  2886. { Now try to merge the two longwords (hp2 will get deleted) }
  2887. TryConstMerge(p, hp1)
  2888. {$endif x86_64}
  2889. ;
  2890. end;
  2891. else
  2892. ;
  2893. end;
  2894. Exit;
  2895. end;
  2896. if (taicpu(p).oper[1]^.typ = top_reg) and
  2897. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2898. begin
  2899. CurrentReg := taicpu(p).oper[1]^.reg;
  2900. TransferUsedRegs(TmpUsedRegs);
  2901. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2902. { we have
  2903. mov x, %treg
  2904. mov %treg, y
  2905. }
  2906. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2907. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2908. { we've got
  2909. mov x, %treg
  2910. mov %treg, y
  2911. with %treg is not used after }
  2912. case taicpu(p).oper[0]^.typ Of
  2913. { top_reg is covered by DeepMOVOpt }
  2914. top_const:
  2915. begin
  2916. { change
  2917. mov const, %treg
  2918. mov %treg, y
  2919. to
  2920. mov const, y
  2921. }
  2922. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2923. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2924. begin
  2925. if taicpu(hp1).oper[1]^.typ=top_reg then
  2926. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2927. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2928. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2929. RemoveInstruction(hp1);
  2930. Result:=true;
  2931. Exit;
  2932. end;
  2933. end;
  2934. top_ref:
  2935. case taicpu(hp1).oper[1]^.typ of
  2936. top_reg:
  2937. begin
  2938. { change
  2939. mov mem, %treg
  2940. mov %treg, %reg
  2941. to
  2942. mov mem, %reg"
  2943. }
  2944. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2945. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2946. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2947. RemoveInstruction(hp1);
  2948. Result:=true;
  2949. Exit;
  2950. end;
  2951. top_ref:
  2952. begin
  2953. {$ifdef x86_64}
  2954. { Look for the following to simplify:
  2955. mov x(mem1), %reg
  2956. mov %reg, y(mem2)
  2957. mov x+8(mem1), %reg
  2958. mov %reg, y+8(mem2)
  2959. Change to:
  2960. movdqu x(mem1), %xmmreg
  2961. movdqu %xmmreg, y(mem2)
  2962. ...but only as long as the memory blocks don't overlap
  2963. }
  2964. SourceRef := taicpu(p).oper[0]^.ref^;
  2965. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2966. if (taicpu(p).opsize = S_Q) and
  2967. GetNextInstruction(hp1, hp2) and
  2968. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2969. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2970. begin
  2971. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2972. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2973. Inc(SourceRef.offset, 8);
  2974. if UseAVX then
  2975. begin
  2976. MovAligned := A_VMOVDQA;
  2977. MovUnaligned := A_VMOVDQU;
  2978. end
  2979. else
  2980. begin
  2981. MovAligned := A_MOVDQA;
  2982. MovUnaligned := A_MOVDQU;
  2983. end;
  2984. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  2985. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  2986. begin
  2987. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2988. Inc(TargetRef.offset, 8);
  2989. if GetNextInstruction(hp2, hp3) and
  2990. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2991. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2992. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2993. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2994. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2995. begin
  2996. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2997. if CurrentReg <> NR_NO then
  2998. begin
  2999. { Remember that the offsets are 8 ahead }
  3000. if ((SourceRef.offset mod 16) = 8) and
  3001. (
  3002. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3003. (SourceRef.base = current_procinfo.framepointer) or
  3004. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3005. ) then
  3006. taicpu(p).opcode := MovAligned
  3007. else
  3008. taicpu(p).opcode := MovUnaligned;
  3009. taicpu(p).opsize := S_XMM;
  3010. taicpu(p).oper[1]^.reg := CurrentReg;
  3011. if ((TargetRef.offset mod 16) = 8) and
  3012. (
  3013. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3014. (TargetRef.base = current_procinfo.framepointer) or
  3015. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3016. ) then
  3017. taicpu(hp1).opcode := MovAligned
  3018. else
  3019. taicpu(hp1).opcode := MovUnaligned;
  3020. taicpu(hp1).opsize := S_XMM;
  3021. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3022. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3023. RemoveInstruction(hp2);
  3024. RemoveInstruction(hp3);
  3025. Result := True;
  3026. Exit;
  3027. end;
  3028. end;
  3029. end
  3030. else
  3031. begin
  3032. { See if the next references are 8 less rather than 8 greater }
  3033. Dec(SourceRef.offset, 16); { -8 the other way }
  3034. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3035. begin
  3036. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3037. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3038. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3039. GetNextInstruction(hp2, hp3) and
  3040. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3041. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3042. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3043. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3044. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3045. begin
  3046. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3047. if CurrentReg <> NR_NO then
  3048. begin
  3049. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3050. if ((SourceRef.offset mod 16) = 0) and
  3051. (
  3052. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3053. (SourceRef.base = current_procinfo.framepointer) or
  3054. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3055. ) then
  3056. taicpu(hp2).opcode := MovAligned
  3057. else
  3058. taicpu(hp2).opcode := MovUnaligned;
  3059. taicpu(hp2).opsize := S_XMM;
  3060. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3061. if ((TargetRef.offset mod 16) = 0) and
  3062. (
  3063. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3064. (TargetRef.base = current_procinfo.framepointer) or
  3065. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3066. ) then
  3067. taicpu(hp3).opcode := MovAligned
  3068. else
  3069. taicpu(hp3).opcode := MovUnaligned;
  3070. taicpu(hp3).opsize := S_XMM;
  3071. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3072. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3073. RemoveInstruction(hp1);
  3074. RemoveCurrentP(p, hp2);
  3075. Result := True;
  3076. Exit;
  3077. end;
  3078. end;
  3079. end;
  3080. end;
  3081. end;
  3082. {$endif x86_64}
  3083. end;
  3084. else
  3085. { The write target should be a reg or a ref }
  3086. InternalError(2021091601);
  3087. end;
  3088. else
  3089. ;
  3090. end
  3091. else
  3092. { %treg is used afterwards, but all eventualities
  3093. other than the first MOV instruction being a constant
  3094. are covered by DeepMOVOpt, so only check for that }
  3095. if (taicpu(p).oper[0]^.typ = top_const) and
  3096. (
  3097. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3098. not (cs_opt_size in current_settings.optimizerswitches) or
  3099. (taicpu(hp1).opsize = S_B)
  3100. ) and
  3101. (
  3102. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3103. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3104. ) then
  3105. begin
  3106. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3107. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3108. end;
  3109. end;
  3110. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3111. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3112. { mov reg1, mem1 or mov mem1, reg1
  3113. mov mem2, reg2 mov reg2, mem2}
  3114. begin
  3115. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3116. { mov reg1, mem1 or mov mem1, reg1
  3117. mov mem2, reg1 mov reg2, mem1}
  3118. begin
  3119. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3120. { Removes the second statement from
  3121. mov reg1, mem1/reg2
  3122. mov mem1/reg2, reg1 }
  3123. begin
  3124. if taicpu(p).oper[0]^.typ=top_reg then
  3125. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3127. RemoveInstruction(hp1);
  3128. Result:=true;
  3129. exit;
  3130. end
  3131. else
  3132. begin
  3133. TransferUsedRegs(TmpUsedRegs);
  3134. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3135. if (taicpu(p).oper[1]^.typ = top_ref) and
  3136. { mov reg1, mem1
  3137. mov mem2, reg1 }
  3138. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3139. GetNextInstruction(hp1, hp2) and
  3140. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3141. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3142. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3143. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3144. { change to
  3145. mov reg1, mem1 mov reg1, mem1
  3146. mov mem2, reg1 cmp reg1, mem2
  3147. cmp mem1, reg1
  3148. }
  3149. begin
  3150. RemoveInstruction(hp2);
  3151. taicpu(hp1).opcode := A_CMP;
  3152. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3153. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3154. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3155. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3156. end;
  3157. end;
  3158. end
  3159. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3160. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3161. begin
  3162. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3163. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3164. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3165. end
  3166. else
  3167. begin
  3168. TransferUsedRegs(TmpUsedRegs);
  3169. if GetNextInstruction(hp1, hp2) and
  3170. MatchOpType(taicpu(p),top_ref,top_reg) and
  3171. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3172. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3173. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3174. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3175. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3176. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3177. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3178. { mov mem1, %reg1
  3179. mov %reg1, mem2
  3180. mov mem2, reg2
  3181. to:
  3182. mov mem1, reg2
  3183. mov reg2, mem2}
  3184. begin
  3185. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3186. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3187. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3188. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3189. RemoveInstruction(hp2);
  3190. Result := True;
  3191. end
  3192. {$ifdef i386}
  3193. { this is enabled for i386 only, as the rules to create the reg sets below
  3194. are too complicated for x86-64, so this makes this code too error prone
  3195. on x86-64
  3196. }
  3197. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3198. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3199. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3200. { mov mem1, reg1 mov mem1, reg1
  3201. mov reg1, mem2 mov reg1, mem2
  3202. mov mem2, reg2 mov mem2, reg1
  3203. to: to:
  3204. mov mem1, reg1 mov mem1, reg1
  3205. mov mem1, reg2 mov reg1, mem2
  3206. mov reg1, mem2
  3207. or (if mem1 depends on reg1
  3208. and/or if mem2 depends on reg2)
  3209. to:
  3210. mov mem1, reg1
  3211. mov reg1, mem2
  3212. mov reg1, reg2
  3213. }
  3214. begin
  3215. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3216. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3217. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3218. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3219. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3220. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3221. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3222. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3223. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3224. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3225. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3226. end
  3227. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3228. begin
  3229. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3230. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3231. end
  3232. else
  3233. begin
  3234. RemoveInstruction(hp2);
  3235. end
  3236. {$endif i386}
  3237. ;
  3238. end;
  3239. end
  3240. { movl [mem1],reg1
  3241. movl [mem1],reg2
  3242. to
  3243. movl [mem1],reg1
  3244. movl reg1,reg2
  3245. }
  3246. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3247. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3248. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3249. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3250. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3251. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3252. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3253. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3254. begin
  3255. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3256. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3257. end;
  3258. { movl const1,[mem1]
  3259. movl [mem1],reg1
  3260. to
  3261. movl const1,reg1
  3262. movl reg1,[mem1]
  3263. }
  3264. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3265. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3266. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3267. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3268. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3269. begin
  3270. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3271. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3272. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3273. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3274. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3275. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3276. Result:=true;
  3277. exit;
  3278. end;
  3279. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3280. { Change:
  3281. movl %reg1,%reg2
  3282. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3283. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3284. To:
  3285. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3286. movl x(%reg1),%reg1
  3287. movl %reg1,%regX
  3288. }
  3289. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3290. begin
  3291. CurrentReg := taicpu(p).oper[0]^.reg;
  3292. ActiveReg := taicpu(p).oper[1]^.reg;
  3293. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3294. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3295. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3296. GetNextInstruction(hp1, hp2) and
  3297. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3298. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3299. begin
  3300. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3301. if RegInRef(ActiveReg, SourceRef) and
  3302. { If %reg1 also appears in the second reference, then it will
  3303. not refer to the same memory block as the first reference }
  3304. not RegInRef(CurrentReg, SourceRef) then
  3305. begin
  3306. { Check to see if the references match if %reg2 is changed to %reg1 }
  3307. if SourceRef.base = ActiveReg then
  3308. SourceRef.base := CurrentReg;
  3309. if SourceRef.index = ActiveReg then
  3310. SourceRef.index := CurrentReg;
  3311. { RefsEqual also checks to ensure both references are non-volatile }
  3312. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3313. begin
  3314. taicpu(hp2).loadreg(0, CurrentReg);
  3315. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3316. Result := True;
  3317. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3318. begin
  3319. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3320. RemoveCurrentP(p, hp1);
  3321. Exit;
  3322. end
  3323. else
  3324. begin
  3325. { Check to see if %reg2 is no longer in use }
  3326. TransferUsedRegs(TmpUsedRegs);
  3327. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3328. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3329. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3330. begin
  3331. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3332. RemoveCurrentP(p, hp1);
  3333. Exit;
  3334. end;
  3335. end;
  3336. { If we reach this point, p and hp1 weren't actually modified,
  3337. so we can do a bit more work on this pass }
  3338. end;
  3339. end;
  3340. end;
  3341. end;
  3342. end;
  3343. { search further than the next instruction for a mov (as long as it's not a jump) }
  3344. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3345. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3346. (taicpu(p).oper[1]^.typ = top_reg) and
  3347. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3348. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3349. begin
  3350. { we work with hp2 here, so hp1 can be still used later on when
  3351. checking for GetNextInstruction_p }
  3352. hp3 := hp1;
  3353. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3354. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3355. { Saves on a large number of dereferences }
  3356. ActiveReg := taicpu(p).oper[1]^.reg;
  3357. TransferUsedRegs(TmpUsedRegs);
  3358. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3359. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3360. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3361. (hp2.typ=ait_instruction) do
  3362. begin
  3363. case taicpu(hp2).opcode of
  3364. A_POP:
  3365. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3366. begin
  3367. if not CrossJump and
  3368. not RegUsedBetween(ActiveReg, p, hp2) then
  3369. begin
  3370. { We can remove the original MOV since the register
  3371. wasn't used between it and its popping from the stack }
  3372. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3373. RemoveCurrentp(p, hp1);
  3374. Result := True;
  3375. Exit;
  3376. end;
  3377. { Can't go any further }
  3378. Break;
  3379. end;
  3380. A_MOV:
  3381. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3382. ((taicpu(p).oper[0]^.typ=top_const) or
  3383. ((taicpu(p).oper[0]^.typ=top_reg) and
  3384. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3385. )
  3386. ) then
  3387. begin
  3388. { we have
  3389. mov x, %treg
  3390. mov %treg, y
  3391. }
  3392. { We don't need to call UpdateUsedRegs for every instruction between
  3393. p and hp2 because the register we're concerned about will not
  3394. become deallocated (otherwise GetNextInstructionUsingReg would
  3395. have stopped at an earlier instruction). [Kit] }
  3396. TempRegUsed :=
  3397. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3398. RegReadByInstruction(ActiveReg, hp3) or
  3399. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3400. case taicpu(p).oper[0]^.typ Of
  3401. top_reg:
  3402. begin
  3403. { change
  3404. mov %reg, %treg
  3405. mov %treg, y
  3406. to
  3407. mov %reg, y
  3408. }
  3409. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3411. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3412. begin
  3413. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3414. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3415. if TempRegUsed then
  3416. begin
  3417. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3418. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3419. { Set the start of the next GetNextInstructionUsingRegCond search
  3420. to start at the entry right before hp2 (which is about to be removed) }
  3421. hp3 := tai(hp2.Previous);
  3422. RemoveInstruction(hp2);
  3423. { See if there's more we can optimise }
  3424. Continue;
  3425. end
  3426. else
  3427. begin
  3428. RemoveInstruction(hp2);
  3429. { We can remove the original MOV too }
  3430. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3431. RemoveCurrentP(p, hp1);
  3432. Result:=true;
  3433. Exit;
  3434. end;
  3435. end
  3436. else
  3437. begin
  3438. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3439. taicpu(hp2).loadReg(0, CurrentReg);
  3440. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3441. { Check to see if the register also appears in the reference }
  3442. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3443. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3444. { Don't remove the first instruction if the temporary register is in use }
  3445. if not TempRegUsed and
  3446. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3447. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3448. begin
  3449. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3450. RemoveCurrentP(p, hp1);
  3451. Result:=true;
  3452. Exit;
  3453. end;
  3454. { No need to set Result to True here. If there's another instruction later
  3455. on that can be optimised, it will be detected when the main Pass 1 loop
  3456. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3457. end;
  3458. end;
  3459. top_const:
  3460. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3461. begin
  3462. { change
  3463. mov const, %treg
  3464. mov %treg, y
  3465. to
  3466. mov const, y
  3467. }
  3468. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3469. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3470. begin
  3471. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3472. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3473. if TempRegUsed then
  3474. begin
  3475. { Don't remove the first instruction if the temporary register is in use }
  3476. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3477. { No need to set Result to True. If there's another instruction later on
  3478. that can be optimised, it will be detected when the main Pass 1 loop
  3479. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3480. end
  3481. else
  3482. begin
  3483. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3484. RemoveCurrentP(p, hp1);
  3485. Result:=true;
  3486. Exit;
  3487. end;
  3488. end;
  3489. end;
  3490. else
  3491. Internalerror(2019103001);
  3492. end;
  3493. end
  3494. else
  3495. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3496. begin
  3497. if not CrossJump and
  3498. not RegUsedBetween(ActiveReg, p, hp2) and
  3499. not RegReadByInstruction(ActiveReg, hp2) then
  3500. begin
  3501. { Register is not used before it is overwritten }
  3502. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3503. RemoveCurrentp(p, hp1);
  3504. Result := True;
  3505. Exit;
  3506. end;
  3507. if (taicpu(p).oper[0]^.typ = top_const) and
  3508. (taicpu(hp2).oper[0]^.typ = top_const) then
  3509. begin
  3510. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3511. begin
  3512. { Same value - register hasn't changed }
  3513. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3514. RemoveInstruction(hp2);
  3515. Result := True;
  3516. { See if there's more we can optimise }
  3517. Continue;
  3518. end;
  3519. end;
  3520. end;
  3521. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3522. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3523. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3524. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3525. begin
  3526. {
  3527. Change from:
  3528. mov ###, %reg
  3529. ...
  3530. movs/z %reg,%reg (Same register, just different sizes)
  3531. To:
  3532. movs/z ###, %reg (Longer version)
  3533. ...
  3534. (remove)
  3535. }
  3536. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3537. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3538. { Keep the first instruction as mov if ### is a constant }
  3539. if taicpu(p).oper[0]^.typ = top_const then
  3540. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3541. else
  3542. begin
  3543. taicpu(p).opcode := taicpu(hp2).opcode;
  3544. taicpu(p).opsize := taicpu(hp2).opsize;
  3545. end;
  3546. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3547. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3548. RemoveInstruction(hp2);
  3549. Result := True;
  3550. Exit;
  3551. end;
  3552. else
  3553. { Move down to the MatchOpType if-block below };
  3554. end;
  3555. { Also catches MOV/S/Z instructions that aren't modified }
  3556. if taicpu(p).oper[0]^.typ = top_reg then
  3557. begin
  3558. CurrentReg := taicpu(p).oper[0]^.reg;
  3559. if
  3560. not RegModifiedByInstruction(CurrentReg, hp3) and
  3561. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3562. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3563. begin
  3564. Result := True;
  3565. { Just in case something didn't get modified (e.g. an
  3566. implicit register). Also, if it does read from this
  3567. register, then there's no longer an advantage to
  3568. changing the register on subsequent instructions.}
  3569. if not RegReadByInstruction(ActiveReg, hp2) then
  3570. begin
  3571. { If a conditional jump was crossed, do not delete
  3572. the original MOV no matter what }
  3573. if not CrossJump and
  3574. { RegEndOfLife returns True if the register is
  3575. deallocated before the next instruction or has
  3576. been loaded with a new value }
  3577. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3578. begin
  3579. { We can remove the original MOV }
  3580. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3581. RemoveCurrentp(p, hp1);
  3582. Exit;
  3583. end;
  3584. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3585. begin
  3586. { See if there's more we can optimise }
  3587. hp3 := hp2;
  3588. Continue;
  3589. end;
  3590. end;
  3591. end;
  3592. end;
  3593. { Break out of the while loop under normal circumstances }
  3594. Break;
  3595. end;
  3596. end;
  3597. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3598. (taicpu(p).oper[1]^.typ = top_reg) and
  3599. (taicpu(p).opsize = S_L) and
  3600. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3601. (taicpu(hp2).opcode = A_AND) and
  3602. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3603. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3604. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3605. ) then
  3606. begin
  3607. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3608. begin
  3609. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3610. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3611. begin
  3612. { Optimize out:
  3613. mov x, %reg
  3614. and ffffffffh, %reg
  3615. }
  3616. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3617. RemoveInstruction(hp2);
  3618. Result:=true;
  3619. exit;
  3620. end;
  3621. end;
  3622. end;
  3623. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3624. x >= RetOffset) as it doesn't do anything (it writes either to a
  3625. parameter or to the temporary storage room for the function
  3626. result)
  3627. }
  3628. if IsExitCode(hp1) and
  3629. (taicpu(p).oper[1]^.typ = top_ref) and
  3630. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3631. (
  3632. (
  3633. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3634. not (
  3635. assigned(current_procinfo.procdef.funcretsym) and
  3636. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3637. )
  3638. ) or
  3639. { Also discard writes to the stack that are below the base pointer,
  3640. as this is temporary storage rather than a function result on the
  3641. stack, say. }
  3642. (
  3643. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3644. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3645. )
  3646. ) then
  3647. begin
  3648. RemoveCurrentp(p, hp1);
  3649. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3650. RemoveLastDeallocForFuncRes(p);
  3651. Result:=true;
  3652. exit;
  3653. end;
  3654. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3655. begin
  3656. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3657. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3658. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3659. begin
  3660. { change
  3661. mov reg1, mem1
  3662. test/cmp x, mem1
  3663. to
  3664. mov reg1, mem1
  3665. test/cmp x, reg1
  3666. }
  3667. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3668. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3669. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3670. Result := True;
  3671. Exit;
  3672. end;
  3673. if DoMovCmpMemOpt(p, hp1, True) then
  3674. begin
  3675. Result := True;
  3676. Exit;
  3677. end;
  3678. end;
  3679. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3680. { If the flags register is in use, don't change the instruction to an
  3681. ADD otherwise this will scramble the flags. [Kit] }
  3682. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3683. begin
  3684. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3685. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3686. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3687. ) or
  3688. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3689. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3690. )
  3691. ) then
  3692. { mov reg1,ref
  3693. lea reg2,[reg1,reg2]
  3694. to
  3695. add reg2,ref}
  3696. begin
  3697. TransferUsedRegs(TmpUsedRegs);
  3698. { reg1 may not be used afterwards }
  3699. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3700. begin
  3701. Taicpu(hp1).opcode:=A_ADD;
  3702. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3703. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3704. RemoveCurrentp(p, hp1);
  3705. result:=true;
  3706. exit;
  3707. end;
  3708. end;
  3709. { If the LEA instruction can be converted into an arithmetic instruction,
  3710. it may be possible to then fold it in the next optimisation, otherwise
  3711. there's nothing more that can be optimised here. }
  3712. if not ConvertLEA(taicpu(hp1)) then
  3713. Exit;
  3714. end;
  3715. if (taicpu(p).oper[1]^.typ = top_reg) and
  3716. (hp1.typ = ait_instruction) and
  3717. GetNextInstruction(hp1, hp2) and
  3718. MatchInstruction(hp2,A_MOV,[]) and
  3719. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3720. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3721. (
  3722. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3723. {$ifdef x86_64}
  3724. or
  3725. (
  3726. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3727. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3728. )
  3729. {$endif x86_64}
  3730. ) then
  3731. begin
  3732. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3733. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3734. { change movsX/movzX reg/ref, reg2
  3735. add/sub/or/... reg3/$const, reg2
  3736. mov reg2 reg/ref
  3737. dealloc reg2
  3738. to
  3739. add/sub/or/... reg3/$const, reg/ref }
  3740. begin
  3741. TransferUsedRegs(TmpUsedRegs);
  3742. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3743. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3744. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3745. begin
  3746. { by example:
  3747. movswl %si,%eax movswl %si,%eax p
  3748. decl %eax addl %edx,%eax hp1
  3749. movw %ax,%si movw %ax,%si hp2
  3750. ->
  3751. movswl %si,%eax movswl %si,%eax p
  3752. decw %eax addw %edx,%eax hp1
  3753. movw %ax,%si movw %ax,%si hp2
  3754. }
  3755. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3756. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3757. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3758. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3759. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3760. {
  3761. ->
  3762. movswl %si,%eax movswl %si,%eax p
  3763. decw %si addw %dx,%si hp1
  3764. movw %ax,%si movw %ax,%si hp2
  3765. }
  3766. case taicpu(hp1).ops of
  3767. 1:
  3768. begin
  3769. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3770. if taicpu(hp1).oper[0]^.typ=top_reg then
  3771. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3772. end;
  3773. 2:
  3774. begin
  3775. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3776. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3777. (taicpu(hp1).opcode<>A_SHL) and
  3778. (taicpu(hp1).opcode<>A_SHR) and
  3779. (taicpu(hp1).opcode<>A_SAR) then
  3780. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3781. end;
  3782. else
  3783. internalerror(2008042701);
  3784. end;
  3785. {
  3786. ->
  3787. decw %si addw %dx,%si p
  3788. }
  3789. RemoveInstruction(hp2);
  3790. RemoveCurrentP(p, hp1);
  3791. Result:=True;
  3792. Exit;
  3793. end;
  3794. end;
  3795. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3796. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3797. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3798. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3799. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3800. )
  3801. {$ifdef i386}
  3802. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3803. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3804. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3805. {$endif i386}
  3806. then
  3807. { change movsX/movzX reg/ref, reg2
  3808. add/sub/or/... regX/$const, reg2
  3809. mov reg2, reg3
  3810. dealloc reg2
  3811. to
  3812. movsX/movzX reg/ref, reg3
  3813. add/sub/or/... reg3/$const, reg3
  3814. }
  3815. begin
  3816. TransferUsedRegs(TmpUsedRegs);
  3817. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3819. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3820. begin
  3821. { by example:
  3822. movswl %si,%eax movswl %si,%eax p
  3823. decl %eax addl %edx,%eax hp1
  3824. movw %ax,%si movw %ax,%si hp2
  3825. ->
  3826. movswl %si,%eax movswl %si,%eax p
  3827. decw %eax addw %edx,%eax hp1
  3828. movw %ax,%si movw %ax,%si hp2
  3829. }
  3830. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3831. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3832. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3833. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3834. { limit size of constants as well to avoid assembler errors, but
  3835. check opsize to avoid overflow when left shifting the 1 }
  3836. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3837. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3838. {$ifdef x86_64}
  3839. { Be careful of, for example:
  3840. movl %reg1,%reg2
  3841. addl %reg3,%reg2
  3842. movq %reg2,%reg4
  3843. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3844. }
  3845. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3846. begin
  3847. taicpu(hp2).changeopsize(S_L);
  3848. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3849. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3850. end;
  3851. {$endif x86_64}
  3852. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3853. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3854. if taicpu(p).oper[0]^.typ=top_reg then
  3855. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3856. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3857. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3858. {
  3859. ->
  3860. movswl %si,%eax movswl %si,%eax p
  3861. decw %si addw %dx,%si hp1
  3862. movw %ax,%si movw %ax,%si hp2
  3863. }
  3864. case taicpu(hp1).ops of
  3865. 1:
  3866. begin
  3867. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3868. if taicpu(hp1).oper[0]^.typ=top_reg then
  3869. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3870. end;
  3871. 2:
  3872. begin
  3873. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3874. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3875. (taicpu(hp1).opcode<>A_SHL) and
  3876. (taicpu(hp1).opcode<>A_SHR) and
  3877. (taicpu(hp1).opcode<>A_SAR) then
  3878. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3879. end;
  3880. else
  3881. internalerror(2018111801);
  3882. end;
  3883. {
  3884. ->
  3885. decw %si addw %dx,%si p
  3886. }
  3887. RemoveInstruction(hp2);
  3888. end;
  3889. end;
  3890. end;
  3891. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3892. GetNextInstruction(hp1, hp2) and
  3893. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3894. MatchOperand(Taicpu(p).oper[0]^,0) and
  3895. (Taicpu(p).oper[1]^.typ = top_reg) and
  3896. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3897. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3898. { mov reg1,0
  3899. bts reg1,operand1 --> mov reg1,operand2
  3900. or reg1,operand2 bts reg1,operand1}
  3901. begin
  3902. Taicpu(hp2).opcode:=A_MOV;
  3903. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3904. asml.remove(hp1);
  3905. insertllitem(hp2,hp2.next,hp1);
  3906. RemoveCurrentp(p, hp1);
  3907. Result:=true;
  3908. exit;
  3909. end;
  3910. {
  3911. mov ref,reg0
  3912. <op> reg0,reg1
  3913. dealloc reg0
  3914. to
  3915. <op> ref,reg1
  3916. }
  3917. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3918. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3919. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3920. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3921. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3922. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3923. begin
  3924. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3925. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3926. RemoveCurrentp(p, hp1);
  3927. Result:=true;
  3928. exit;
  3929. end;
  3930. {$ifdef x86_64}
  3931. { Convert:
  3932. movq x(ref),%reg64
  3933. shrq y,%reg64
  3934. To:
  3935. movl x+4(ref),%reg32
  3936. shrl y-32,%reg32 (Remove if y = 32)
  3937. }
  3938. if (taicpu(p).opsize = S_Q) and
  3939. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3940. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3941. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3942. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3943. (taicpu(hp1).oper[0]^.val >= 32) and
  3944. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3945. begin
  3946. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3947. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3948. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3949. { Convert to 32-bit }
  3950. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3951. taicpu(p).opsize := S_L;
  3952. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3953. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3954. if (taicpu(hp1).oper[0]^.val = 32) then
  3955. begin
  3956. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3957. RemoveInstruction(hp1);
  3958. end
  3959. else
  3960. begin
  3961. { This will potentially open up more arithmetic operations since
  3962. the peephole optimizer now has a big hint that only the lower
  3963. 32 bits are currently in use (and opcodes are smaller in size) }
  3964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3965. taicpu(hp1).opsize := S_L;
  3966. Dec(taicpu(hp1).oper[0]^.val, 32);
  3967. DebugMsg(SPeepholeOptimization + PreMessage +
  3968. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3969. end;
  3970. Result := True;
  3971. Exit;
  3972. end;
  3973. {$endif x86_64}
  3974. { Backward optimisation. If we have:
  3975. func. %reg1,%reg2
  3976. mov %reg2,%reg3
  3977. (dealloc %reg2)
  3978. Change to:
  3979. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3980. }
  3981. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3982. begin
  3983. CurrentReg := taicpu(p).oper[0]^.reg;
  3984. ActiveReg := taicpu(p).oper[1]^.reg;
  3985. TransferUsedRegs(TmpUsedRegs);
  3986. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3987. GetLastInstruction(p, hp2) and
  3988. (hp2.typ = ait_instruction) and
  3989. { Have to make sure it's an instruction that only reads from
  3990. operand 1 and only writes (not reads or modifies) from operand 2;
  3991. in essence, a one-operand pure function such as BSR or POPCNT }
  3992. (taicpu(hp2).ops = 2) and
  3993. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3994. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3995. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3996. begin
  3997. case taicpu(hp2).opcode of
  3998. A_FSTSW, A_FNSTSW,
  3999. A_IN, A_INS, A_OUT, A_OUTS,
  4000. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  4001. { These routines have explicit operands, but they are restricted in
  4002. what they can be (e.g. IN and OUT can only read from AL, AX or
  4003. EAX. }
  4004. A_CMOVcc:
  4005. { CMOV is not valid either because then CurrentReg will depend
  4006. on an unknown value if the condition is False and hence is
  4007. not a pure write }
  4008. ;
  4009. else
  4010. begin
  4011. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4012. taicpu(hp2).oper[1]^.reg := ActiveReg;
  4013. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  4014. RemoveCurrentp(p, hp1);
  4015. Result := True;
  4016. Exit;
  4017. end;
  4018. end;
  4019. end;
  4020. end;
  4021. end;
  4022. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4023. var
  4024. hp1 : tai;
  4025. begin
  4026. Result:=false;
  4027. if taicpu(p).ops <> 2 then
  4028. exit;
  4029. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4030. GetNextInstruction(p,hp1) then
  4031. begin
  4032. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4033. (taicpu(hp1).ops = 2) then
  4034. begin
  4035. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4036. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4037. { movXX reg1, mem1 or movXX mem1, reg1
  4038. movXX mem2, reg2 movXX reg2, mem2}
  4039. begin
  4040. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4041. { movXX reg1, mem1 or movXX mem1, reg1
  4042. movXX mem2, reg1 movXX reg2, mem1}
  4043. begin
  4044. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4045. begin
  4046. { Removes the second statement from
  4047. movXX reg1, mem1/reg2
  4048. movXX mem1/reg2, reg1
  4049. }
  4050. if taicpu(p).oper[0]^.typ=top_reg then
  4051. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4052. { Removes the second statement from
  4053. movXX mem1/reg1, reg2
  4054. movXX reg2, mem1/reg1
  4055. }
  4056. if (taicpu(p).oper[1]^.typ=top_reg) and
  4057. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4058. begin
  4059. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4060. RemoveInstruction(hp1);
  4061. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4062. Result:=true;
  4063. exit;
  4064. end
  4065. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4066. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4067. begin
  4068. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4069. RemoveInstruction(hp1);
  4070. Result:=true;
  4071. exit;
  4072. end;
  4073. end
  4074. end;
  4075. end;
  4076. end;
  4077. end;
  4078. end;
  4079. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4080. var
  4081. hp1 : tai;
  4082. begin
  4083. result:=false;
  4084. { replace
  4085. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4086. MovX %mreg2,%mreg1
  4087. dealloc %mreg2
  4088. by
  4089. <Op>X %mreg2,%mreg1
  4090. ?
  4091. }
  4092. if GetNextInstruction(p,hp1) and
  4093. { we mix single and double opperations here because we assume that the compiler
  4094. generates vmovapd only after double operations and vmovaps only after single operations }
  4095. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4096. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4097. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4098. (taicpu(p).oper[0]^.typ=top_reg) then
  4099. begin
  4100. TransferUsedRegs(TmpUsedRegs);
  4101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4103. begin
  4104. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4105. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4106. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4107. RemoveInstruction(hp1);
  4108. result:=true;
  4109. end;
  4110. end;
  4111. end;
  4112. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4113. var
  4114. hp1, p_label, p_dist, hp1_dist: tai;
  4115. JumpLabel, JumpLabel_dist: TAsmLabel;
  4116. FirstValue, SecondValue: TCGInt;
  4117. begin
  4118. Result := False;
  4119. if (taicpu(p).oper[0]^.typ = top_const) and
  4120. (taicpu(p).oper[0]^.val <> -1) then
  4121. begin
  4122. { Convert unsigned maximum constants to -1 to aid optimisation }
  4123. case taicpu(p).opsize of
  4124. S_B:
  4125. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4126. begin
  4127. taicpu(p).oper[0]^.val := -1;
  4128. Result := True;
  4129. Exit;
  4130. end;
  4131. S_W:
  4132. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4133. begin
  4134. taicpu(p).oper[0]^.val := -1;
  4135. Result := True;
  4136. Exit;
  4137. end;
  4138. S_L:
  4139. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4140. begin
  4141. taicpu(p).oper[0]^.val := -1;
  4142. Result := True;
  4143. Exit;
  4144. end;
  4145. {$ifdef x86_64}
  4146. S_Q:
  4147. { Storing anything greater than $7FFFFFFF is not possible so do
  4148. nothing };
  4149. {$endif x86_64}
  4150. else
  4151. InternalError(2021121001);
  4152. end;
  4153. end;
  4154. if GetNextInstruction(p, hp1) and
  4155. TrySwapMovCmp(p, hp1) then
  4156. begin
  4157. Result := True;
  4158. Exit;
  4159. end;
  4160. { Search for:
  4161. test $x,(reg/ref)
  4162. jne @lbl1
  4163. test $y,(reg/ref) (same register or reference)
  4164. jne @lbl1
  4165. Change to:
  4166. test $(x or y),(reg/ref)
  4167. jne @lbl1
  4168. (Note, this doesn't work with je instead of jne)
  4169. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4170. Also search for:
  4171. test $x,(reg/ref)
  4172. je @lbl1
  4173. test $y,(reg/ref)
  4174. je/jne @lbl2
  4175. If (x or y) = x, then the second jump is deterministic
  4176. }
  4177. if (
  4178. (
  4179. (taicpu(p).oper[0]^.typ = top_const) or
  4180. (
  4181. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4182. (taicpu(p).oper[0]^.typ = top_reg) and
  4183. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4184. )
  4185. ) and
  4186. MatchInstruction(hp1, A_JCC, [])
  4187. ) then
  4188. begin
  4189. if (taicpu(p).oper[0]^.typ = top_reg) and
  4190. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4191. FirstValue := -1
  4192. else
  4193. FirstValue := taicpu(p).oper[0]^.val;
  4194. { If we have several test/jne's in a row, it might be the case that
  4195. the second label doesn't go to the same location, but the one
  4196. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4197. so accommodate for this with a while loop.
  4198. }
  4199. hp1_dist := hp1;
  4200. if GetNextInstruction(hp1, p_dist) and
  4201. (p_dist.typ = ait_instruction) and
  4202. (
  4203. (
  4204. (taicpu(p_dist).opcode = A_TEST) and
  4205. (
  4206. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4207. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4208. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4209. )
  4210. ) or
  4211. (
  4212. { cmp 0,%reg = test %reg,%reg }
  4213. (taicpu(p_dist).opcode = A_CMP) and
  4214. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4215. )
  4216. ) and
  4217. { Make sure the destination operands are actually the same }
  4218. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4219. GetNextInstruction(p_dist, hp1_dist) and
  4220. MatchInstruction(hp1_dist, A_JCC, []) then
  4221. begin
  4222. if
  4223. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4224. (
  4225. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4226. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4227. ) then
  4228. SecondValue := -1
  4229. else
  4230. SecondValue := taicpu(p_dist).oper[0]^.val;
  4231. { If both of the TEST constants are identical, delete the second
  4232. TEST that is unnecessary. }
  4233. if (FirstValue = SecondValue) then
  4234. begin
  4235. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4236. RemoveInstruction(p_dist);
  4237. { Don't let the flags register become deallocated and reallocated between the jumps }
  4238. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4239. Result := True;
  4240. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4241. begin
  4242. { Since the second jump's condition is a subset of the first, we
  4243. know it will never branch because the first jump dominates it.
  4244. Get it out of the way now rather than wait for the jump
  4245. optimisations for a speed boost. }
  4246. if IsJumpToLabel(taicpu(hp1_dist)) then
  4247. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4248. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4249. RemoveInstruction(hp1_dist);
  4250. end
  4251. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4252. begin
  4253. { If the inverse of the first condition is a subset of the second,
  4254. the second one will definitely branch if the first one doesn't }
  4255. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4256. MakeUnconditional(taicpu(hp1_dist));
  4257. RemoveDeadCodeAfterJump(hp1_dist);
  4258. end;
  4259. Exit;
  4260. end;
  4261. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4262. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4263. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4264. then the second jump will never branch, so it can also be
  4265. removed regardless of where it goes }
  4266. (
  4267. (FirstValue = -1) or
  4268. (SecondValue = -1) or
  4269. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4270. ) then
  4271. begin
  4272. { Same jump location... can be a register since nothing's changed }
  4273. { If any of the entries are equivalent to test %reg,%reg, then the
  4274. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4275. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4276. if IsJumpToLabel(taicpu(hp1_dist)) then
  4277. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4278. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4279. RemoveInstruction(hp1_dist);
  4280. { Only remove the second test if no jumps or other conditional instructions follow }
  4281. TransferUsedRegs(TmpUsedRegs);
  4282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4283. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4284. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4285. RemoveInstruction(p_dist);
  4286. Result := True;
  4287. Exit;
  4288. end;
  4289. end;
  4290. end;
  4291. { Search for:
  4292. test %reg,%reg
  4293. j(c1) @lbl1
  4294. ...
  4295. @lbl:
  4296. test %reg,%reg (same register)
  4297. j(c2) @lbl2
  4298. If c2 is a subset of c1, change to:
  4299. test %reg,%reg
  4300. j(c1) @lbl2
  4301. (@lbl1 may become a dead label as a result)
  4302. }
  4303. if (taicpu(p).oper[1]^.typ = top_reg) and
  4304. (taicpu(p).oper[0]^.typ = top_reg) and
  4305. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4306. MatchInstruction(hp1, A_JCC, []) and
  4307. IsJumpToLabel(taicpu(hp1)) then
  4308. begin
  4309. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4310. p_label := nil;
  4311. if Assigned(JumpLabel) then
  4312. p_label := getlabelwithsym(JumpLabel);
  4313. if Assigned(p_label) and
  4314. GetNextInstruction(p_label, p_dist) and
  4315. MatchInstruction(p_dist, A_TEST, []) and
  4316. { It's fine if the second test uses smaller sub-registers }
  4317. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4318. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4319. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4320. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4321. GetNextInstruction(p_dist, hp1_dist) and
  4322. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4323. begin
  4324. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4325. if JumpLabel = JumpLabel_dist then
  4326. { This is an infinite loop }
  4327. Exit;
  4328. { Best optimisation when the first condition is a subset (or equal) of the second }
  4329. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4330. begin
  4331. { Any registers used here will already be allocated }
  4332. if Assigned(JumpLabel_dist) then
  4333. JumpLabel_dist.IncRefs;
  4334. if Assigned(JumpLabel) then
  4335. JumpLabel.DecRefs;
  4336. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4337. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4338. Result := True;
  4339. Exit;
  4340. end;
  4341. end;
  4342. end;
  4343. end;
  4344. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4345. var
  4346. hp1, hp2: tai;
  4347. ActiveReg: TRegister;
  4348. OldOffset: asizeint;
  4349. ThisConst: TCGInt;
  4350. function RegDeallocated: Boolean;
  4351. begin
  4352. TransferUsedRegs(TmpUsedRegs);
  4353. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4354. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4355. end;
  4356. begin
  4357. result:=false;
  4358. hp1 := nil;
  4359. { replace
  4360. addX const,%reg1
  4361. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4362. dealloc %reg1
  4363. by
  4364. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4365. }
  4366. if MatchOpType(taicpu(p),top_const,top_reg) then
  4367. begin
  4368. ActiveReg := taicpu(p).oper[1]^.reg;
  4369. { Ensures the entire register was updated }
  4370. if (taicpu(p).opsize >= S_L) and
  4371. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4372. MatchInstruction(hp1,A_LEA,[]) and
  4373. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4374. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4375. (
  4376. { Cover the case where the register in the reference is also the destination register }
  4377. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4378. (
  4379. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4380. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4381. RegDeallocated
  4382. )
  4383. ) then
  4384. begin
  4385. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4386. {$push}
  4387. {$R-}{$Q-}
  4388. { Explicitly disable overflow checking for these offset calculation
  4389. as those do not matter for the final result }
  4390. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4391. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4392. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4393. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4394. {$pop}
  4395. {$ifdef x86_64}
  4396. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4397. begin
  4398. { Overflow; abort }
  4399. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4400. end
  4401. else
  4402. {$endif x86_64}
  4403. begin
  4404. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4405. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4406. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4407. RemoveCurrentP(p, hp1)
  4408. else
  4409. RemoveCurrentP(p);
  4410. result:=true;
  4411. Exit;
  4412. end;
  4413. end;
  4414. if (
  4415. { Save calling GetNextInstructionUsingReg again }
  4416. Assigned(hp1) or
  4417. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4418. ) and
  4419. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4420. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4421. begin
  4422. if taicpu(hp1).oper[0]^.typ = top_const then
  4423. begin
  4424. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4425. if taicpu(hp1).opcode = A_ADD then
  4426. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4427. else
  4428. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4429. Result := True;
  4430. { Handle any overflows }
  4431. case taicpu(p).opsize of
  4432. S_B:
  4433. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4434. S_W:
  4435. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4436. S_L:
  4437. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4438. {$ifdef x86_64}
  4439. S_Q:
  4440. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4441. { Overflow; abort }
  4442. Result := False
  4443. else
  4444. taicpu(p).oper[0]^.val := ThisConst;
  4445. {$endif x86_64}
  4446. else
  4447. InternalError(2021102610);
  4448. end;
  4449. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4450. if Result then
  4451. begin
  4452. if (taicpu(p).oper[0]^.val < 0) and
  4453. (
  4454. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4455. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4456. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4457. ) then
  4458. begin
  4459. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4460. taicpu(p).opcode := A_SUB;
  4461. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4462. end
  4463. else
  4464. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4465. RemoveInstruction(hp1);
  4466. end;
  4467. end
  4468. else
  4469. begin
  4470. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4471. TransferUsedRegs(TmpUsedRegs);
  4472. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4473. hp2 := p;
  4474. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4475. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4477. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4478. begin
  4479. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4480. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4481. Asml.Remove(p);
  4482. Asml.InsertAfter(p, hp1);
  4483. p := hp1;
  4484. Result := True;
  4485. end;
  4486. end;
  4487. end;
  4488. end;
  4489. end;
  4490. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4491. var
  4492. hp1: tai;
  4493. ref: Integer;
  4494. saveref: treference;
  4495. Multiple: TCGInt;
  4496. Adjacent: Boolean;
  4497. begin
  4498. Result:=false;
  4499. { play save and throw an error if LEA uses a seg register prefix,
  4500. this is most likely an error somewhere else }
  4501. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4502. internalerror(2022022001);
  4503. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4504. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4505. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4506. (
  4507. { do not mess with leas accessing the stack pointer
  4508. unless it's a null operation }
  4509. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4510. (
  4511. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4512. (taicpu(p).oper[0]^.ref^.offset = 0)
  4513. )
  4514. ) and
  4515. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4516. begin
  4517. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4518. begin
  4519. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4520. begin
  4521. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4522. taicpu(p).oper[1]^.reg);
  4523. InsertLLItem(p.previous,p.next, hp1);
  4524. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4525. p.free;
  4526. p:=hp1;
  4527. end
  4528. else
  4529. begin
  4530. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4531. RemoveCurrentP(p);
  4532. end;
  4533. Result:=true;
  4534. exit;
  4535. end
  4536. else if (
  4537. { continue to use lea to adjust the stack pointer,
  4538. it is the recommended way, but only if not optimizing for size }
  4539. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4540. (cs_opt_size in current_settings.optimizerswitches)
  4541. ) and
  4542. { If the flags register is in use, don't change the instruction
  4543. to an ADD otherwise this will scramble the flags. [Kit] }
  4544. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4545. ConvertLEA(taicpu(p)) then
  4546. begin
  4547. Result:=true;
  4548. exit;
  4549. end;
  4550. end;
  4551. { Don't optimise if the stack or frame pointer is the destination register }
  4552. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4553. Exit;
  4554. if GetNextInstruction(p,hp1) and
  4555. (hp1.typ=ait_instruction) then
  4556. begin
  4557. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4558. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4559. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4560. begin
  4561. TransferUsedRegs(TmpUsedRegs);
  4562. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4563. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4564. begin
  4565. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4566. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4567. RemoveInstruction(hp1);
  4568. result:=true;
  4569. exit;
  4570. end;
  4571. end;
  4572. { changes
  4573. lea <ref1>, reg1
  4574. <op> ...,<ref. with reg1>,...
  4575. to
  4576. <op> ...,<ref1>,... }
  4577. { find a reference which uses reg1 }
  4578. 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
  4579. ref:=0
  4580. 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
  4581. ref:=1
  4582. else
  4583. ref:=-1;
  4584. if (ref<>-1) and
  4585. { reg1 must be either the base or the index }
  4586. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4587. begin
  4588. { reg1 can be removed from the reference }
  4589. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4590. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4591. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4592. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4593. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4594. else
  4595. Internalerror(2019111201);
  4596. { check if the can insert all data of the lea into the second instruction }
  4597. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4598. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4599. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4600. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4601. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4602. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4603. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4604. {$ifdef x86_64}
  4605. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4606. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4607. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4608. )
  4609. {$endif x86_64}
  4610. then
  4611. begin
  4612. { reg1 might not used by the second instruction after it is remove from the reference }
  4613. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4614. begin
  4615. TransferUsedRegs(TmpUsedRegs);
  4616. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4617. { reg1 is not updated so it might not be used afterwards }
  4618. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4619. begin
  4620. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4621. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4622. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4623. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4624. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4625. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4626. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4627. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4628. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4629. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4630. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4631. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4632. RemoveCurrentP(p, hp1);
  4633. result:=true;
  4634. exit;
  4635. end
  4636. end;
  4637. end;
  4638. { recover }
  4639. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4640. end;
  4641. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4642. if Adjacent or
  4643. { Check further ahead (up to 2 instructions ahead for -O2) }
  4644. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4645. begin
  4646. { Check common LEA/LEA conditions }
  4647. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4648. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4649. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4650. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4651. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4652. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4653. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4654. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4655. (
  4656. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4657. calling it (since it calls GetNextInstruction) }
  4658. Adjacent or
  4659. (
  4660. (
  4661. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4662. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4663. ) and (
  4664. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4665. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4666. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4667. )
  4668. )
  4669. ) then
  4670. begin
  4671. { changes
  4672. lea (regX,scale), reg1
  4673. lea offset(reg1,reg1), reg1
  4674. to
  4675. lea offset(regX,scale*2), reg1
  4676. and
  4677. lea (regX,scale1), reg1
  4678. lea offset(reg1,scale2), reg1
  4679. to
  4680. lea offset(regX,scale1*scale2), reg1
  4681. ... so long as the final scale does not exceed 8
  4682. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4683. }
  4684. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4685. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4686. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4687. (
  4688. (
  4689. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4690. ) or (
  4691. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4692. (
  4693. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4694. (
  4695. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4696. Adjacent or
  4697. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4698. )
  4699. )
  4700. )
  4701. ) and (
  4702. (
  4703. { lea (reg1,scale2), reg1 variant }
  4704. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4705. (
  4706. (
  4707. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4708. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4709. ) or (
  4710. { lea (regX,regX), reg1 variant }
  4711. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4712. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4713. )
  4714. )
  4715. ) or (
  4716. { lea (reg1,reg1), reg1 variant }
  4717. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4718. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4719. )
  4720. ) then
  4721. begin
  4722. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4723. { Make everything homogeneous to make calculations easier }
  4724. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4725. begin
  4726. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4727. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4728. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4729. else
  4730. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4731. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4732. end;
  4733. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4734. begin
  4735. { Just to prevent miscalculations }
  4736. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4737. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4738. else
  4739. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4740. end
  4741. else
  4742. begin
  4743. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4744. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4745. end;
  4746. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4747. RemoveCurrentP(p);
  4748. result:=true;
  4749. exit;
  4750. end
  4751. { changes
  4752. lea offset1(regX), reg1
  4753. lea offset2(reg1), reg1
  4754. to
  4755. lea offset1+offset2(regX), reg1 }
  4756. else if
  4757. (
  4758. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4759. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4760. ) or (
  4761. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4762. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4763. (
  4764. (
  4765. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4766. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4767. ) or (
  4768. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4769. (
  4770. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4771. (
  4772. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4773. (
  4774. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4775. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4776. )
  4777. )
  4778. )
  4779. )
  4780. )
  4781. ) then
  4782. begin
  4783. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4784. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4785. begin
  4786. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4787. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4788. { if the register is used as index and base, we have to increase for base as well
  4789. and adapt base }
  4790. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4791. begin
  4792. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4793. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4794. end;
  4795. end
  4796. else
  4797. begin
  4798. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4799. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4800. end;
  4801. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4802. begin
  4803. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4804. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4805. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4806. end;
  4807. RemoveCurrentP(p);
  4808. result:=true;
  4809. exit;
  4810. end;
  4811. end;
  4812. { Change:
  4813. leal/q $x(%reg1),%reg2
  4814. ...
  4815. shll/q $y,%reg2
  4816. To:
  4817. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4818. }
  4819. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4820. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4821. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4822. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  4823. (taicpu(hp1).oper[0]^.val <= 3) then
  4824. begin
  4825. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4826. TransferUsedRegs(TmpUsedRegs);
  4827. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4828. if
  4829. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4830. (this works even if scalefactor is zero) }
  4831. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4832. { Ensure offset doesn't go out of bounds }
  4833. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4834. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4835. (
  4836. (
  4837. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  4838. (
  4839. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4840. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4841. (
  4842. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4843. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4844. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4845. )
  4846. )
  4847. ) or (
  4848. (
  4849. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4850. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4851. ) and
  4852. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  4853. )
  4854. ) then
  4855. begin
  4856. repeat
  4857. with taicpu(p).oper[0]^.ref^ do
  4858. begin
  4859. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4860. if index = base then
  4861. begin
  4862. if Multiple > 4 then
  4863. { Optimisation will no longer work because resultant
  4864. scale factor will exceed 8 }
  4865. Break;
  4866. base := NR_NO;
  4867. scalefactor := 2;
  4868. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4869. end
  4870. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4871. begin
  4872. { Scale factor only works on the index register }
  4873. index := base;
  4874. base := NR_NO;
  4875. end;
  4876. { For safety }
  4877. if scalefactor <= 1 then
  4878. begin
  4879. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4880. scalefactor := Multiple;
  4881. end
  4882. else
  4883. begin
  4884. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4885. scalefactor := scalefactor * Multiple;
  4886. end;
  4887. offset := offset * Multiple;
  4888. end;
  4889. RemoveInstruction(hp1);
  4890. Result := True;
  4891. Exit;
  4892. { This repeat..until loop exists for the benefit of Break }
  4893. until True;
  4894. end;
  4895. end;
  4896. end;
  4897. end;
  4898. end;
  4899. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4900. var
  4901. hp1 : tai;
  4902. begin
  4903. DoSubAddOpt := False;
  4904. if taicpu(p).oper[0]^.typ <> top_const then
  4905. { Should have been confirmed before calling }
  4906. InternalError(2021102601);
  4907. if GetLastInstruction(p, hp1) and
  4908. (hp1.typ = ait_instruction) and
  4909. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4910. case taicpu(hp1).opcode Of
  4911. A_DEC:
  4912. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4913. begin
  4914. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4915. RemoveInstruction(hp1);
  4916. end;
  4917. A_SUB:
  4918. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4919. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4920. begin
  4921. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4922. RemoveInstruction(hp1);
  4923. end;
  4924. A_ADD:
  4925. begin
  4926. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4927. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4928. begin
  4929. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4930. RemoveInstruction(hp1);
  4931. if (taicpu(p).oper[0]^.val = 0) then
  4932. begin
  4933. hp1 := tai(p.next);
  4934. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4935. if not GetLastInstruction(hp1, p) then
  4936. p := hp1;
  4937. DoSubAddOpt := True;
  4938. end
  4939. end;
  4940. end;
  4941. else
  4942. ;
  4943. end;
  4944. end;
  4945. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4946. begin
  4947. Result := False;
  4948. if UpdateTmpUsedRegs then
  4949. TransferUsedRegs(TmpUsedRegs);
  4950. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4951. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4952. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4953. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4954. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4955. (
  4956. (
  4957. (taicpu(hp1).opcode = A_TEST)
  4958. ) or (
  4959. (taicpu(hp1).opcode = A_CMP) and
  4960. { A sanity check more than anything }
  4961. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4962. )
  4963. ) then
  4964. begin
  4965. { change
  4966. mov mem, %reg
  4967. cmp/test x, %reg / test %reg,%reg
  4968. (reg deallocated)
  4969. to
  4970. cmp/test x, mem / cmp 0, mem
  4971. }
  4972. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4973. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4974. begin
  4975. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4976. if (taicpu(hp1).opcode = A_TEST) and
  4977. (
  4978. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4979. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4980. ) then
  4981. begin
  4982. taicpu(hp1).opcode := A_CMP;
  4983. taicpu(hp1).loadconst(0, 0);
  4984. end;
  4985. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4986. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4987. RemoveCurrentP(p, hp1);
  4988. Result := True;
  4989. Exit;
  4990. end;
  4991. end;
  4992. end;
  4993. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4994. var
  4995. hp2, hp3, hp4, hp5, hp6: tai;
  4996. ThisReg: TRegister;
  4997. JumpLoc: TAsmLabel;
  4998. begin
  4999. Result := False;
  5000. {
  5001. Convert:
  5002. j<c> .L1
  5003. .L2:
  5004. mov 1,reg
  5005. jmp .L3 (or ret, although it might not be a RET yet)
  5006. .L1:
  5007. mov 0,reg
  5008. jmp .L3 (or ret)
  5009. ( As long as .L3 <> .L1 or .L2)
  5010. To:
  5011. mov 0,reg
  5012. set<not(c)> reg
  5013. jmp .L3 (or ret)
  5014. .L2:
  5015. mov 1,reg
  5016. jmp .L3 (or ret)
  5017. .L1:
  5018. mov 0,reg
  5019. jmp .L3 (or ret)
  5020. }
  5021. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5022. Exit;
  5023. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5024. if GetNextInstruction(hp_label, hp2) and
  5025. MatchInstruction(hp2,A_MOV,[]) and
  5026. (taicpu(hp2).oper[0]^.typ = top_const) and
  5027. (
  5028. (
  5029. (taicpu(hp2).oper[1]^.typ = top_reg)
  5030. {$ifdef i386}
  5031. { Under i386, ESI, EDI, EBP and ESP
  5032. don't have an 8-bit representation }
  5033. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5034. {$endif i386}
  5035. ) or (
  5036. {$ifdef i386}
  5037. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5038. {$endif i386}
  5039. (taicpu(hp2).opsize = S_B)
  5040. )
  5041. ) and
  5042. GetNextInstruction(hp2, hp3) and
  5043. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5044. (
  5045. (taicpu(hp3).opcode=A_RET) or
  5046. (
  5047. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5048. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5049. )
  5050. ) and
  5051. GetNextInstruction(hp3, hp4) and
  5052. SkipAligns(hp4, hp4) and
  5053. (hp4.typ=ait_label) and
  5054. (tai_label(hp4).labsym=JumpLoc) and
  5055. (
  5056. not (cs_opt_size in current_settings.optimizerswitches) or
  5057. { If the initial jump is the label's only reference, then it will
  5058. become a dead label if the other conditions are met and hence
  5059. remove at least 2 instructions, including a jump }
  5060. (JumpLoc.getrefs = 1)
  5061. ) and
  5062. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5063. that will be optimised out }
  5064. GetNextInstruction(hp4, hp5) and
  5065. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5066. (taicpu(hp5).oper[0]^.typ = top_const) and
  5067. (
  5068. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5069. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5070. ) and
  5071. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5072. GetNextInstruction(hp5,hp6) and
  5073. (
  5074. (hp6.typ<>ait_label) or
  5075. SkipLabels(hp6, hp6)
  5076. ) and
  5077. (hp6.typ=ait_instruction) then
  5078. begin
  5079. { First, let's look at the two jumps that are hp3 and hp6 }
  5080. if not
  5081. (
  5082. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5083. (
  5084. (taicpu(hp6).opcode=A_RET) or
  5085. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5086. )
  5087. ) then
  5088. { If condition is False, then the JMP/RET instructions matched conventionally }
  5089. begin
  5090. { See if one of the jumps can be instantly converted into a RET }
  5091. if (taicpu(hp3).opcode=A_JMP) then
  5092. begin
  5093. { Reuse hp5 }
  5094. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5095. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5096. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5097. Exit;
  5098. if MatchInstruction(hp5, A_RET, []) then
  5099. begin
  5100. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5101. ConvertJumpToRET(hp3, hp5);
  5102. Result := True;
  5103. end
  5104. else
  5105. Exit;
  5106. end;
  5107. if (taicpu(hp6).opcode=A_JMP) then
  5108. begin
  5109. { Reuse hp5 }
  5110. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5111. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5112. Exit;
  5113. if MatchInstruction(hp5, A_RET, []) then
  5114. begin
  5115. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5116. ConvertJumpToRET(hp6, hp5);
  5117. Result := True;
  5118. end
  5119. else
  5120. Exit;
  5121. end;
  5122. if not
  5123. (
  5124. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5125. (
  5126. (taicpu(hp6).opcode=A_RET) or
  5127. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5128. )
  5129. ) then
  5130. { Still doesn't match }
  5131. Exit;
  5132. end;
  5133. if (taicpu(hp2).oper[0]^.val = 1) then
  5134. begin
  5135. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5136. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5137. end
  5138. else
  5139. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5140. if taicpu(hp2).opsize=S_B then
  5141. begin
  5142. if taicpu(hp2).oper[1]^.typ = top_reg then
  5143. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5144. else
  5145. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5146. hp2 := p;
  5147. end
  5148. else
  5149. begin
  5150. { Will be a register because the size can't be S_B otherwise }
  5151. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5152. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5153. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5154. { Inserting it right before p will guarantee that the flags are also tracked }
  5155. Asml.InsertBefore(hp2, p);
  5156. end;
  5157. taicpu(hp4).condition:=taicpu(p).condition;
  5158. asml.InsertBefore(hp4, hp2);
  5159. JumpLoc.decrefs;
  5160. if taicpu(hp3).opcode = A_JMP then
  5161. begin
  5162. MakeUnconditional(taicpu(p));
  5163. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5164. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5165. end
  5166. else
  5167. begin
  5168. taicpu(p).condition := C_None;
  5169. taicpu(p).opcode := A_RET;
  5170. taicpu(p).clearop(0);
  5171. taicpu(p).ops := 0;
  5172. end;
  5173. if (JumpLoc.getrefs = 0) then
  5174. RemoveDeadCodeAfterJump(hp3);
  5175. Result:=true;
  5176. exit;
  5177. end;
  5178. end;
  5179. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5180. var
  5181. hp1, hp2: tai;
  5182. ActiveReg: TRegister;
  5183. OldOffset: asizeint;
  5184. ThisConst: TCGInt;
  5185. function RegDeallocated: Boolean;
  5186. begin
  5187. TransferUsedRegs(TmpUsedRegs);
  5188. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5189. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5190. end;
  5191. begin
  5192. Result:=false;
  5193. hp1 := nil;
  5194. { replace
  5195. subX const,%reg1
  5196. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5197. dealloc %reg1
  5198. by
  5199. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5200. }
  5201. if MatchOpType(taicpu(p),top_const,top_reg) then
  5202. begin
  5203. ActiveReg := taicpu(p).oper[1]^.reg;
  5204. { Ensures the entire register was updated }
  5205. if (taicpu(p).opsize >= S_L) and
  5206. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5207. MatchInstruction(hp1,A_LEA,[]) and
  5208. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5209. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5210. (
  5211. { Cover the case where the register in the reference is also the destination register }
  5212. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5213. (
  5214. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5215. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5216. RegDeallocated
  5217. )
  5218. ) then
  5219. begin
  5220. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5221. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5222. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5223. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5224. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5225. {$ifdef x86_64}
  5226. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5227. begin
  5228. { Overflow; abort }
  5229. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5230. end
  5231. else
  5232. {$endif x86_64}
  5233. begin
  5234. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5235. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5236. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5237. RemoveCurrentP(p, hp1)
  5238. else
  5239. RemoveCurrentP(p);
  5240. result:=true;
  5241. Exit;
  5242. end;
  5243. end;
  5244. if (
  5245. { Save calling GetNextInstructionUsingReg again }
  5246. Assigned(hp1) or
  5247. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5248. ) and
  5249. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5250. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5251. begin
  5252. if taicpu(hp1).oper[0]^.typ = top_const then
  5253. begin
  5254. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5255. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5256. Result := True;
  5257. { Handle any overflows }
  5258. case taicpu(p).opsize of
  5259. S_B:
  5260. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5261. S_W:
  5262. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5263. S_L:
  5264. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5265. {$ifdef x86_64}
  5266. S_Q:
  5267. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5268. { Overflow; abort }
  5269. Result := False
  5270. else
  5271. taicpu(p).oper[0]^.val := ThisConst;
  5272. {$endif x86_64}
  5273. else
  5274. InternalError(2021102610);
  5275. end;
  5276. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5277. if Result then
  5278. begin
  5279. if (taicpu(p).oper[0]^.val < 0) and
  5280. (
  5281. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5282. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5283. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5284. ) then
  5285. begin
  5286. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5287. taicpu(p).opcode := A_SUB;
  5288. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5289. end
  5290. else
  5291. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5292. RemoveInstruction(hp1);
  5293. end;
  5294. end
  5295. else
  5296. begin
  5297. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5298. TransferUsedRegs(TmpUsedRegs);
  5299. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5300. hp2 := p;
  5301. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5302. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5303. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5304. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5305. begin
  5306. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5307. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5308. Asml.Remove(p);
  5309. Asml.InsertAfter(p, hp1);
  5310. p := hp1;
  5311. Result := True;
  5312. Exit;
  5313. end;
  5314. end;
  5315. end;
  5316. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5317. { * change "sub/add const1, reg" or "dec reg" followed by
  5318. "sub const2, reg" to one "sub ..., reg" }
  5319. {$ifdef i386}
  5320. if (taicpu(p).oper[0]^.val = 2) and
  5321. (ActiveReg = NR_ESP) and
  5322. { Don't do the sub/push optimization if the sub }
  5323. { comes from setting up the stack frame (JM) }
  5324. (not(GetLastInstruction(p,hp1)) or
  5325. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5326. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5327. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5328. begin
  5329. hp1 := tai(p.next);
  5330. while Assigned(hp1) and
  5331. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5332. not RegReadByInstruction(NR_ESP,hp1) and
  5333. not RegModifiedByInstruction(NR_ESP,hp1) do
  5334. hp1 := tai(hp1.next);
  5335. if Assigned(hp1) and
  5336. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5337. begin
  5338. taicpu(hp1).changeopsize(S_L);
  5339. if taicpu(hp1).oper[0]^.typ=top_reg then
  5340. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5341. hp1 := tai(p.next);
  5342. RemoveCurrentp(p, hp1);
  5343. Result:=true;
  5344. exit;
  5345. end;
  5346. end;
  5347. {$endif i386}
  5348. if DoSubAddOpt(p) then
  5349. Result:=true;
  5350. end;
  5351. end;
  5352. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5353. var
  5354. TmpBool1,TmpBool2 : Boolean;
  5355. tmpref : treference;
  5356. hp1,hp2: tai;
  5357. mask: tcgint;
  5358. begin
  5359. Result:=false;
  5360. { All these optimisations work on "shl/sal const,%reg" }
  5361. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5362. Exit;
  5363. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5364. (taicpu(p).oper[0]^.val <= 3) then
  5365. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5366. begin
  5367. { should we check the next instruction? }
  5368. TmpBool1 := True;
  5369. { have we found an add/sub which could be
  5370. integrated in the lea? }
  5371. TmpBool2 := False;
  5372. reference_reset(tmpref,2,[]);
  5373. TmpRef.index := taicpu(p).oper[1]^.reg;
  5374. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5375. while TmpBool1 and
  5376. GetNextInstruction(p, hp1) and
  5377. (tai(hp1).typ = ait_instruction) and
  5378. ((((taicpu(hp1).opcode = A_ADD) or
  5379. (taicpu(hp1).opcode = A_SUB)) and
  5380. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5381. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5382. (((taicpu(hp1).opcode = A_INC) or
  5383. (taicpu(hp1).opcode = A_DEC)) and
  5384. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5385. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5386. ((taicpu(hp1).opcode = A_LEA) and
  5387. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5388. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5389. (not GetNextInstruction(hp1,hp2) or
  5390. not instrReadsFlags(hp2)) Do
  5391. begin
  5392. TmpBool1 := False;
  5393. if taicpu(hp1).opcode=A_LEA then
  5394. begin
  5395. if (TmpRef.base = NR_NO) and
  5396. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5397. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5398. { Segment register isn't a concern here }
  5399. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5400. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5401. begin
  5402. TmpBool1 := True;
  5403. TmpBool2 := True;
  5404. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5405. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5406. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5407. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5408. RemoveInstruction(hp1);
  5409. end
  5410. end
  5411. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5412. begin
  5413. TmpBool1 := True;
  5414. TmpBool2 := True;
  5415. case taicpu(hp1).opcode of
  5416. A_ADD:
  5417. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5418. A_SUB:
  5419. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5420. else
  5421. internalerror(2019050536);
  5422. end;
  5423. RemoveInstruction(hp1);
  5424. end
  5425. else
  5426. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5427. (((taicpu(hp1).opcode = A_ADD) and
  5428. (TmpRef.base = NR_NO)) or
  5429. (taicpu(hp1).opcode = A_INC) or
  5430. (taicpu(hp1).opcode = A_DEC)) then
  5431. begin
  5432. TmpBool1 := True;
  5433. TmpBool2 := True;
  5434. case taicpu(hp1).opcode of
  5435. A_ADD:
  5436. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5437. A_INC:
  5438. inc(TmpRef.offset);
  5439. A_DEC:
  5440. dec(TmpRef.offset);
  5441. else
  5442. internalerror(2019050535);
  5443. end;
  5444. RemoveInstruction(hp1);
  5445. end;
  5446. end;
  5447. if TmpBool2
  5448. {$ifndef x86_64}
  5449. or
  5450. ((current_settings.optimizecputype < cpu_Pentium2) and
  5451. (taicpu(p).oper[0]^.val <= 3) and
  5452. not(cs_opt_size in current_settings.optimizerswitches))
  5453. {$endif x86_64}
  5454. then
  5455. begin
  5456. if not(TmpBool2) and
  5457. (taicpu(p).oper[0]^.val=1) then
  5458. begin
  5459. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5460. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5461. end
  5462. else
  5463. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5464. taicpu(p).oper[1]^.reg);
  5465. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5466. InsertLLItem(p.previous, p.next, hp1);
  5467. p.free;
  5468. p := hp1;
  5469. end;
  5470. end
  5471. {$ifndef x86_64}
  5472. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5473. begin
  5474. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5475. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5476. (unlike shl, which is only Tairable in the U pipe) }
  5477. if taicpu(p).oper[0]^.val=1 then
  5478. begin
  5479. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5480. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5481. InsertLLItem(p.previous, p.next, hp1);
  5482. p.free;
  5483. p := hp1;
  5484. end
  5485. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5486. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5487. else if (taicpu(p).opsize = S_L) and
  5488. (taicpu(p).oper[0]^.val<= 3) then
  5489. begin
  5490. reference_reset(tmpref,2,[]);
  5491. TmpRef.index := taicpu(p).oper[1]^.reg;
  5492. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5493. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5494. InsertLLItem(p.previous, p.next, hp1);
  5495. p.free;
  5496. p := hp1;
  5497. end;
  5498. end
  5499. {$endif x86_64}
  5500. else if
  5501. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5502. (
  5503. (
  5504. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5505. SetAndTest(hp1, hp2)
  5506. {$ifdef x86_64}
  5507. ) or
  5508. (
  5509. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5510. GetNextInstruction(hp1, hp2) and
  5511. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5512. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5513. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5514. {$endif x86_64}
  5515. )
  5516. ) and
  5517. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5518. begin
  5519. { Change:
  5520. shl x, %reg1
  5521. mov -(1<<x), %reg2
  5522. and %reg2, %reg1
  5523. Or:
  5524. shl x, %reg1
  5525. and -(1<<x), %reg1
  5526. To just:
  5527. shl x, %reg1
  5528. Since the and operation only zeroes bits that are already zero from the shl operation
  5529. }
  5530. case taicpu(p).oper[0]^.val of
  5531. 8:
  5532. mask:=$FFFFFFFFFFFFFF00;
  5533. 16:
  5534. mask:=$FFFFFFFFFFFF0000;
  5535. 32:
  5536. mask:=$FFFFFFFF00000000;
  5537. 63:
  5538. { Constant pre-calculated to prevent overflow errors with Int64 }
  5539. mask:=$8000000000000000;
  5540. else
  5541. begin
  5542. if taicpu(p).oper[0]^.val >= 64 then
  5543. { Shouldn't happen realistically, since the register
  5544. is guaranteed to be set to zero at this point }
  5545. mask := 0
  5546. else
  5547. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5548. end;
  5549. end;
  5550. if taicpu(hp1).oper[0]^.val = mask then
  5551. begin
  5552. { Everything checks out, perform the optimisation, as long as
  5553. the FLAGS register isn't being used}
  5554. TransferUsedRegs(TmpUsedRegs);
  5555. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5556. {$ifdef x86_64}
  5557. if (hp1 <> hp2) then
  5558. begin
  5559. { "shl/mov/and" version }
  5560. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5561. { Don't do the optimisation if the FLAGS register is in use }
  5562. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5563. begin
  5564. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5565. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5566. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5567. begin
  5568. RemoveInstruction(hp1);
  5569. Result := True;
  5570. end;
  5571. { Only set Result to True if the 'mov' instruction was removed }
  5572. RemoveInstruction(hp2);
  5573. end;
  5574. end
  5575. else
  5576. {$endif x86_64}
  5577. begin
  5578. { "shl/and" version }
  5579. { Don't do the optimisation if the FLAGS register is in use }
  5580. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5581. begin
  5582. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5583. RemoveInstruction(hp1);
  5584. Result := True;
  5585. end;
  5586. end;
  5587. Exit;
  5588. end
  5589. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5590. begin
  5591. { Even if the mask doesn't allow for its removal, we might be
  5592. able to optimise the mask for the "shl/and" version, which
  5593. may permit other peephole optimisations }
  5594. {$ifdef DEBUG_AOPTCPU}
  5595. mask := taicpu(hp1).oper[0]^.val and mask;
  5596. if taicpu(hp1).oper[0]^.val <> mask then
  5597. begin
  5598. DebugMsg(
  5599. SPeepholeOptimization +
  5600. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5601. ' to $' + debug_tostr(mask) +
  5602. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5603. taicpu(hp1).oper[0]^.val := mask;
  5604. end;
  5605. {$else DEBUG_AOPTCPU}
  5606. { If debugging is off, just set the operand even if it's the same }
  5607. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5608. {$endif DEBUG_AOPTCPU}
  5609. end;
  5610. end;
  5611. {
  5612. change
  5613. shl/sal const,reg
  5614. <op> ...(...,reg,1),...
  5615. into
  5616. <op> ...(...,reg,1 shl const),...
  5617. if const in 1..3
  5618. }
  5619. if MatchOpType(taicpu(p), top_const, top_reg) and
  5620. (taicpu(p).oper[0]^.val in [1..3]) and
  5621. GetNextInstruction(p, hp1) and
  5622. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5623. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5624. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5625. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5626. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5627. begin
  5628. TransferUsedRegs(TmpUsedRegs);
  5629. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5630. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5631. begin
  5632. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5633. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5634. RemoveCurrentP(p);
  5635. Result:=true;
  5636. end;
  5637. end;
  5638. end;
  5639. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5640. var
  5641. CurrentRef: TReference;
  5642. FullReg: TRegister;
  5643. hp1, hp2: tai;
  5644. begin
  5645. Result := False;
  5646. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5647. Exit;
  5648. { We assume you've checked if the operand is actually a reference by
  5649. this point. If it isn't, you'll most likely get an access violation }
  5650. CurrentRef := first_mov.oper[1]^.ref^;
  5651. { Memory must be aligned }
  5652. if (CurrentRef.offset mod 4) <> 0 then
  5653. Exit;
  5654. Inc(CurrentRef.offset);
  5655. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5656. if MatchOperand(second_mov.oper[0]^, 0) and
  5657. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5658. GetNextInstruction(second_mov, hp1) and
  5659. (hp1.typ = ait_instruction) and
  5660. (taicpu(hp1).opcode = A_MOV) and
  5661. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5662. (taicpu(hp1).oper[0]^.val = 0) then
  5663. begin
  5664. Inc(CurrentRef.offset);
  5665. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5666. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5667. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5668. begin
  5669. case taicpu(hp1).opsize of
  5670. S_B:
  5671. if GetNextInstruction(hp1, hp2) and
  5672. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5673. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5674. (taicpu(hp2).oper[0]^.val = 0) then
  5675. begin
  5676. Inc(CurrentRef.offset);
  5677. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5678. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5679. (taicpu(hp2).opsize = S_B) then
  5680. begin
  5681. RemoveInstruction(hp1);
  5682. RemoveInstruction(hp2);
  5683. first_mov.opsize := S_L;
  5684. if first_mov.oper[0]^.typ = top_reg then
  5685. begin
  5686. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5687. { Reuse second_mov as a MOVZX instruction }
  5688. second_mov.opcode := A_MOVZX;
  5689. second_mov.opsize := S_BL;
  5690. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5691. second_mov.loadreg(1, FullReg);
  5692. first_mov.oper[0]^.reg := FullReg;
  5693. asml.Remove(second_mov);
  5694. asml.InsertBefore(second_mov, first_mov);
  5695. end
  5696. else
  5697. { It's a value }
  5698. begin
  5699. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5700. RemoveInstruction(second_mov);
  5701. end;
  5702. Result := True;
  5703. Exit;
  5704. end;
  5705. end;
  5706. S_W:
  5707. begin
  5708. RemoveInstruction(hp1);
  5709. first_mov.opsize := S_L;
  5710. if first_mov.oper[0]^.typ = top_reg then
  5711. begin
  5712. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5713. { Reuse second_mov as a MOVZX instruction }
  5714. second_mov.opcode := A_MOVZX;
  5715. second_mov.opsize := S_BL;
  5716. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5717. second_mov.loadreg(1, FullReg);
  5718. first_mov.oper[0]^.reg := FullReg;
  5719. asml.Remove(second_mov);
  5720. asml.InsertBefore(second_mov, first_mov);
  5721. end
  5722. else
  5723. { It's a value }
  5724. begin
  5725. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5726. RemoveInstruction(second_mov);
  5727. end;
  5728. Result := True;
  5729. Exit;
  5730. end;
  5731. else
  5732. ;
  5733. end;
  5734. end;
  5735. end;
  5736. end;
  5737. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5738. { returns true if a "continue" should be done after this optimization }
  5739. var
  5740. hp1, hp2: tai;
  5741. begin
  5742. Result := false;
  5743. if MatchOpType(taicpu(p),top_ref) and
  5744. GetNextInstruction(p, hp1) and
  5745. (hp1.typ = ait_instruction) and
  5746. (((taicpu(hp1).opcode = A_FLD) and
  5747. (taicpu(p).opcode = A_FSTP)) or
  5748. ((taicpu(p).opcode = A_FISTP) and
  5749. (taicpu(hp1).opcode = A_FILD))) and
  5750. MatchOpType(taicpu(hp1),top_ref) and
  5751. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5752. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5753. begin
  5754. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5755. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5756. GetNextInstruction(hp1, hp2) and
  5757. (hp2.typ = ait_instruction) and
  5758. IsExitCode(hp2) and
  5759. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5760. not(assigned(current_procinfo.procdef.funcretsym) and
  5761. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5762. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5763. begin
  5764. RemoveInstruction(hp1);
  5765. RemoveCurrentP(p, hp2);
  5766. RemoveLastDeallocForFuncRes(p);
  5767. Result := true;
  5768. end
  5769. else
  5770. { we can do this only in fast math mode as fstp is rounding ...
  5771. ... still disabled as it breaks the compiler and/or rtl }
  5772. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5773. { ... or if another fstp equal to the first one follows }
  5774. (GetNextInstruction(hp1,hp2) and
  5775. (hp2.typ = ait_instruction) and
  5776. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5777. (taicpu(p).opsize=taicpu(hp2).opsize))
  5778. ) and
  5779. { fst can't store an extended/comp value }
  5780. (taicpu(p).opsize <> S_FX) and
  5781. (taicpu(p).opsize <> S_IQ) then
  5782. begin
  5783. if (taicpu(p).opcode = A_FSTP) then
  5784. taicpu(p).opcode := A_FST
  5785. else
  5786. taicpu(p).opcode := A_FIST;
  5787. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5788. RemoveInstruction(hp1);
  5789. end;
  5790. end;
  5791. end;
  5792. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5793. var
  5794. hp1, hp2: tai;
  5795. begin
  5796. result:=false;
  5797. if MatchOpType(taicpu(p),top_reg) and
  5798. GetNextInstruction(p, hp1) and
  5799. (hp1.typ = Ait_Instruction) and
  5800. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5801. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5802. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5803. { change to
  5804. fld reg fxxx reg,st
  5805. fxxxp st, st1 (hp1)
  5806. Remark: non commutative operations must be reversed!
  5807. }
  5808. begin
  5809. case taicpu(hp1).opcode Of
  5810. A_FMULP,A_FADDP,
  5811. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5812. begin
  5813. case taicpu(hp1).opcode Of
  5814. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5815. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5816. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5817. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5818. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5819. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5820. else
  5821. internalerror(2019050534);
  5822. end;
  5823. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5824. taicpu(hp1).oper[1]^.reg := NR_ST;
  5825. RemoveCurrentP(p, hp1);
  5826. Result:=true;
  5827. exit;
  5828. end;
  5829. else
  5830. ;
  5831. end;
  5832. end
  5833. else
  5834. if MatchOpType(taicpu(p),top_ref) and
  5835. GetNextInstruction(p, hp2) and
  5836. (hp2.typ = Ait_Instruction) and
  5837. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5838. (taicpu(p).opsize in [S_FS, S_FL]) and
  5839. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5840. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5841. if GetLastInstruction(p, hp1) and
  5842. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5843. MatchOpType(taicpu(hp1),top_ref) and
  5844. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5845. if ((taicpu(hp2).opcode = A_FMULP) or
  5846. (taicpu(hp2).opcode = A_FADDP)) then
  5847. { change to
  5848. fld/fst mem1 (hp1) fld/fst mem1
  5849. fld mem1 (p) fadd/
  5850. faddp/ fmul st, st
  5851. fmulp st, st1 (hp2) }
  5852. begin
  5853. RemoveCurrentP(p, hp1);
  5854. if (taicpu(hp2).opcode = A_FADDP) then
  5855. taicpu(hp2).opcode := A_FADD
  5856. else
  5857. taicpu(hp2).opcode := A_FMUL;
  5858. taicpu(hp2).oper[1]^.reg := NR_ST;
  5859. end
  5860. else
  5861. { change to
  5862. fld/fst mem1 (hp1) fld/fst mem1
  5863. fld mem1 (p) fld st}
  5864. begin
  5865. taicpu(p).changeopsize(S_FL);
  5866. taicpu(p).loadreg(0,NR_ST);
  5867. end
  5868. else
  5869. begin
  5870. case taicpu(hp2).opcode Of
  5871. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5872. { change to
  5873. fld/fst mem1 (hp1) fld/fst mem1
  5874. fld mem2 (p) fxxx mem2
  5875. fxxxp st, st1 (hp2) }
  5876. begin
  5877. case taicpu(hp2).opcode Of
  5878. A_FADDP: taicpu(p).opcode := A_FADD;
  5879. A_FMULP: taicpu(p).opcode := A_FMUL;
  5880. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5881. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5882. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5883. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5884. else
  5885. internalerror(2019050533);
  5886. end;
  5887. RemoveInstruction(hp2);
  5888. end
  5889. else
  5890. ;
  5891. end
  5892. end
  5893. end;
  5894. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5895. begin
  5896. Result := condition_in(cond1, cond2) or
  5897. { Not strictly subsets due to the actual flags checked, but because we're
  5898. comparing integers, E is a subset of AE and GE and their aliases }
  5899. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5900. end;
  5901. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5902. var
  5903. v: TCGInt;
  5904. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5905. FirstMatch: Boolean;
  5906. NewReg: TRegister;
  5907. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5908. begin
  5909. Result:=false;
  5910. { All these optimisations need a next instruction }
  5911. if not GetNextInstruction(p, hp1) then
  5912. Exit;
  5913. { Search for:
  5914. cmp ###,###
  5915. j(c1) @lbl1
  5916. ...
  5917. @lbl:
  5918. cmp ###.### (same comparison as above)
  5919. j(c2) @lbl2
  5920. If c1 is a subset of c2, change to:
  5921. cmp ###,###
  5922. j(c2) @lbl2
  5923. (@lbl1 may become a dead label as a result)
  5924. }
  5925. { Also handle cases where there are multiple jumps in a row }
  5926. p_jump := hp1;
  5927. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5928. begin
  5929. if IsJumpToLabel(taicpu(p_jump)) then
  5930. begin
  5931. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5932. p_label := nil;
  5933. if Assigned(JumpLabel) then
  5934. p_label := getlabelwithsym(JumpLabel);
  5935. if Assigned(p_label) and
  5936. GetNextInstruction(p_label, p_dist) and
  5937. MatchInstruction(p_dist, A_CMP, []) and
  5938. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5939. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5940. GetNextInstruction(p_dist, hp1_dist) and
  5941. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5942. begin
  5943. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5944. if JumpLabel = JumpLabel_dist then
  5945. { This is an infinite loop }
  5946. Exit;
  5947. { Best optimisation when the first condition is a subset (or equal) of the second }
  5948. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5949. begin
  5950. { Any registers used here will already be allocated }
  5951. if Assigned(JumpLabel_dist) then
  5952. JumpLabel_dist.IncRefs;
  5953. if Assigned(JumpLabel) then
  5954. JumpLabel.DecRefs;
  5955. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5956. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5957. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5958. Result := True;
  5959. { Don't exit yet. Since p and p_jump haven't actually been
  5960. removed, we can check for more on this iteration }
  5961. end
  5962. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5963. GetNextInstruction(hp1_dist, hp1_label) and
  5964. SkipAligns(hp1_label, hp1_label) and
  5965. (hp1_label.typ = ait_label) then
  5966. begin
  5967. JumpLabel_far := tai_label(hp1_label).labsym;
  5968. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5969. { This is an infinite loop }
  5970. Exit;
  5971. if Assigned(JumpLabel_far) then
  5972. begin
  5973. { In this situation, if the first jump branches, the second one will never,
  5974. branch so change the destination label to after the second jump }
  5975. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5976. if Assigned(JumpLabel) then
  5977. JumpLabel.DecRefs;
  5978. JumpLabel_far.IncRefs;
  5979. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5980. Result := True;
  5981. { Don't exit yet. Since p and p_jump haven't actually been
  5982. removed, we can check for more on this iteration }
  5983. Continue;
  5984. end;
  5985. end;
  5986. end;
  5987. end;
  5988. { Search for:
  5989. cmp ###,###
  5990. j(c1) @lbl1
  5991. cmp ###,### (same as first)
  5992. Remove second cmp
  5993. }
  5994. if GetNextInstruction(p_jump, hp2) and
  5995. (
  5996. (
  5997. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5998. (
  5999. (
  6000. MatchOpType(taicpu(p), top_const, top_reg) and
  6001. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6002. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6003. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6004. ) or (
  6005. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6006. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6007. )
  6008. )
  6009. ) or (
  6010. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6011. MatchOperand(taicpu(p).oper[0]^, 0) and
  6012. (taicpu(p).oper[1]^.typ = top_reg) and
  6013. MatchInstruction(hp2, A_TEST, []) and
  6014. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6015. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6016. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6017. )
  6018. ) then
  6019. begin
  6020. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6021. RemoveInstruction(hp2);
  6022. Result := True;
  6023. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6024. end;
  6025. GetNextInstruction(p_jump, p_jump);
  6026. end;
  6027. {
  6028. Try to optimise the following:
  6029. cmp $x,### ($x and $y can be registers or constants)
  6030. je @lbl1 (only reference)
  6031. cmp $y,### (### are identical)
  6032. @Lbl:
  6033. sete %reg1
  6034. Change to:
  6035. cmp $x,###
  6036. sete %reg2 (allocate new %reg2)
  6037. cmp $y,###
  6038. sete %reg1
  6039. orb %reg2,%reg1
  6040. (dealloc %reg2)
  6041. This adds an instruction (so don't perform under -Os), but it removes
  6042. a conditional branch.
  6043. }
  6044. if not (cs_opt_size in current_settings.optimizerswitches) and
  6045. (
  6046. (hp1 = p_jump) or
  6047. GetNextInstruction(p, hp1)
  6048. ) and
  6049. MatchInstruction(hp1, A_Jcc, []) and
  6050. IsJumpToLabel(taicpu(hp1)) and
  6051. (taicpu(hp1).condition in [C_E, C_Z]) and
  6052. GetNextInstruction(hp1, hp2) and
  6053. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6054. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6055. { The first operand of CMP instructions can only be a register or
  6056. immediate anyway, so no need to check }
  6057. GetNextInstruction(hp2, p_label) and
  6058. (p_label.typ = ait_label) and
  6059. (tai_label(p_label).labsym.getrefs = 1) and
  6060. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6061. GetNextInstruction(p_label, p_dist) and
  6062. MatchInstruction(p_dist, A_SETcc, []) and
  6063. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6064. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6065. begin
  6066. TransferUsedRegs(TmpUsedRegs);
  6067. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6068. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6069. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6070. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6071. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6072. { Get the instruction after the SETcc instruction so we can
  6073. allocate a new register over the entire range }
  6074. GetNextInstruction(p_dist, hp1_dist) then
  6075. begin
  6076. { Register can appear in p if it's not used afterwards, so only
  6077. allocate between hp1 and hp1_dist }
  6078. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6079. if NewReg <> NR_NO then
  6080. begin
  6081. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6082. { Change the jump instruction into a SETcc instruction }
  6083. taicpu(hp1).opcode := A_SETcc;
  6084. taicpu(hp1).opsize := S_B;
  6085. taicpu(hp1).loadreg(0, NewReg);
  6086. { This is now a dead label }
  6087. tai_label(p_label).labsym.decrefs;
  6088. { Prefer adding before the next instruction so the FLAGS
  6089. register is deallicated first }
  6090. AsmL.InsertBefore(
  6091. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6092. hp1_dist
  6093. );
  6094. Result := True;
  6095. { Don't exit yet, as p wasn't changed and hp1, while
  6096. modified, is still intact and might be optimised by the
  6097. SETcc optimisation below }
  6098. end;
  6099. end;
  6100. end;
  6101. if taicpu(p).oper[0]^.typ = top_const then
  6102. begin
  6103. if (taicpu(p).oper[0]^.val = 0) and
  6104. (taicpu(p).oper[1]^.typ = top_reg) and
  6105. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6106. begin
  6107. hp2 := p;
  6108. FirstMatch := True;
  6109. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6110. anything meaningful once it's converted to "test %reg,%reg";
  6111. additionally, some jumps will always (or never) branch, so
  6112. evaluate every jump immediately following the
  6113. comparison, optimising the conditions if possible.
  6114. Similarly with SETcc... those that are always set to 0 or 1
  6115. are changed to MOV instructions }
  6116. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6117. (
  6118. GetNextInstruction(hp2, hp1) and
  6119. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6120. ) do
  6121. begin
  6122. FirstMatch := False;
  6123. case taicpu(hp1).condition of
  6124. C_B, C_C, C_NAE, C_O:
  6125. { For B/NAE:
  6126. Will never branch since an unsigned integer can never be below zero
  6127. For C/O:
  6128. Result cannot overflow because 0 is being subtracted
  6129. }
  6130. begin
  6131. if taicpu(hp1).opcode = A_Jcc then
  6132. begin
  6133. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6134. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6135. RemoveInstruction(hp1);
  6136. { Since hp1 was deleted, hp2 must not be updated }
  6137. Continue;
  6138. end
  6139. else
  6140. begin
  6141. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6142. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6143. taicpu(hp1).opcode := A_MOV;
  6144. taicpu(hp1).ops := 2;
  6145. taicpu(hp1).condition := C_None;
  6146. taicpu(hp1).opsize := S_B;
  6147. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6148. taicpu(hp1).loadconst(0, 0);
  6149. end;
  6150. end;
  6151. C_BE, C_NA:
  6152. begin
  6153. { Will only branch if equal to zero }
  6154. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6155. taicpu(hp1).condition := C_E;
  6156. end;
  6157. C_A, C_NBE:
  6158. begin
  6159. { Will only branch if not equal to zero }
  6160. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6161. taicpu(hp1).condition := C_NE;
  6162. end;
  6163. C_AE, C_NB, C_NC, C_NO:
  6164. begin
  6165. { Will always branch }
  6166. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6167. if taicpu(hp1).opcode = A_Jcc then
  6168. begin
  6169. MakeUnconditional(taicpu(hp1));
  6170. { Any jumps/set that follow will now be dead code }
  6171. RemoveDeadCodeAfterJump(taicpu(hp1));
  6172. Break;
  6173. end
  6174. else
  6175. begin
  6176. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6177. taicpu(hp1).opcode := A_MOV;
  6178. taicpu(hp1).ops := 2;
  6179. taicpu(hp1).condition := C_None;
  6180. taicpu(hp1).opsize := S_B;
  6181. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6182. taicpu(hp1).loadconst(0, 1);
  6183. end;
  6184. end;
  6185. C_None:
  6186. InternalError(2020012201);
  6187. C_P, C_PE, C_NP, C_PO:
  6188. { We can't handle parity checks and they should never be generated
  6189. after a general-purpose CMP (it's used in some floating-point
  6190. comparisons that don't use CMP) }
  6191. InternalError(2020012202);
  6192. else
  6193. { Zero/Equality, Sign, their complements and all of the
  6194. signed comparisons do not need to be converted };
  6195. end;
  6196. hp2 := hp1;
  6197. end;
  6198. { Convert the instruction to a TEST }
  6199. taicpu(p).opcode := A_TEST;
  6200. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6201. Result := True;
  6202. Exit;
  6203. end
  6204. else if (taicpu(p).oper[0]^.val = 1) and
  6205. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6206. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6207. begin
  6208. { Convert; To:
  6209. cmp $1,r/m cmp $0,r/m
  6210. jl @lbl jle @lbl
  6211. }
  6212. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6213. taicpu(p).oper[0]^.val := 0;
  6214. taicpu(hp1).condition := C_LE;
  6215. { If the instruction is now "cmp $0,%reg", convert it to a
  6216. TEST (and effectively do the work of the "cmp $0,%reg" in
  6217. the block above)
  6218. If it's a reference, we can get away with not setting
  6219. Result to True because he haven't evaluated the jump
  6220. in this pass yet.
  6221. }
  6222. if (taicpu(p).oper[1]^.typ = top_reg) then
  6223. begin
  6224. taicpu(p).opcode := A_TEST;
  6225. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6226. Result := True;
  6227. end;
  6228. Exit;
  6229. end
  6230. else if (taicpu(p).oper[1]^.typ = top_reg)
  6231. {$ifdef x86_64}
  6232. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6233. {$endif x86_64}
  6234. then
  6235. begin
  6236. { cmp register,$8000 neg register
  6237. je target --> jo target
  6238. .... only if register is deallocated before jump.}
  6239. case Taicpu(p).opsize of
  6240. S_B: v:=$80;
  6241. S_W: v:=$8000;
  6242. S_L: v:=qword($80000000);
  6243. else
  6244. internalerror(2013112905);
  6245. end;
  6246. if (taicpu(p).oper[0]^.val=v) and
  6247. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6248. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6249. begin
  6250. TransferUsedRegs(TmpUsedRegs);
  6251. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6252. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6253. begin
  6254. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6255. Taicpu(p).opcode:=A_NEG;
  6256. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6257. Taicpu(p).clearop(1);
  6258. Taicpu(p).ops:=1;
  6259. if Taicpu(hp1).condition=C_E then
  6260. Taicpu(hp1).condition:=C_O
  6261. else
  6262. Taicpu(hp1).condition:=C_NO;
  6263. Result:=true;
  6264. exit;
  6265. end;
  6266. end;
  6267. end;
  6268. end;
  6269. if TrySwapMovCmp(p, hp1) then
  6270. begin
  6271. Result := True;
  6272. Exit;
  6273. end;
  6274. end;
  6275. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6276. var
  6277. hp1: tai;
  6278. begin
  6279. {
  6280. remove the second (v)pxor from
  6281. pxor reg,reg
  6282. ...
  6283. pxor reg,reg
  6284. }
  6285. Result:=false;
  6286. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6287. MatchOpType(taicpu(p),top_reg,top_reg) and
  6288. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6289. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6290. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6291. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6292. begin
  6293. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6294. RemoveInstruction(hp1);
  6295. Result:=true;
  6296. Exit;
  6297. end
  6298. {
  6299. replace
  6300. pxor reg1,reg1
  6301. movapd/s reg1,reg2
  6302. dealloc reg1
  6303. by
  6304. pxor reg2,reg2
  6305. }
  6306. else if GetNextInstruction(p,hp1) and
  6307. { we mix single and double opperations here because we assume that the compiler
  6308. generates vmovapd only after double operations and vmovaps only after single operations }
  6309. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6310. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6311. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6312. (taicpu(p).oper[0]^.typ=top_reg) then
  6313. begin
  6314. TransferUsedRegs(TmpUsedRegs);
  6315. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6316. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6317. begin
  6318. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6319. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6320. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6321. RemoveInstruction(hp1);
  6322. result:=true;
  6323. end;
  6324. end;
  6325. end;
  6326. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6327. var
  6328. hp1: tai;
  6329. begin
  6330. {
  6331. remove the second (v)pxor from
  6332. (v)pxor reg,reg
  6333. ...
  6334. (v)pxor reg,reg
  6335. }
  6336. Result:=false;
  6337. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6338. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6339. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6340. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6341. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6342. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6343. begin
  6344. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6345. RemoveInstruction(hp1);
  6346. Result:=true;
  6347. Exit;
  6348. end
  6349. else
  6350. Result:=OptPass1VOP(p);
  6351. end;
  6352. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6353. var
  6354. hp1 : tai;
  6355. begin
  6356. result:=false;
  6357. { replace
  6358. IMul const,%mreg1,%mreg2
  6359. Mov %reg2,%mreg3
  6360. dealloc %mreg3
  6361. by
  6362. Imul const,%mreg1,%mreg23
  6363. }
  6364. if (taicpu(p).ops=3) and
  6365. GetNextInstruction(p,hp1) and
  6366. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6367. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6368. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6369. begin
  6370. TransferUsedRegs(TmpUsedRegs);
  6371. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6372. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6373. begin
  6374. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6375. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6376. RemoveInstruction(hp1);
  6377. result:=true;
  6378. end;
  6379. end;
  6380. end;
  6381. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6382. var
  6383. hp1 : tai;
  6384. begin
  6385. result:=false;
  6386. { replace
  6387. IMul %reg0,%reg1,%reg2
  6388. Mov %reg2,%reg3
  6389. dealloc %reg2
  6390. by
  6391. Imul %reg0,%reg1,%reg3
  6392. }
  6393. if GetNextInstruction(p,hp1) and
  6394. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6395. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6396. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6397. begin
  6398. TransferUsedRegs(TmpUsedRegs);
  6399. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6400. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6401. begin
  6402. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6403. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6404. RemoveInstruction(hp1);
  6405. result:=true;
  6406. end;
  6407. end;
  6408. end;
  6409. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6410. var
  6411. hp1: tai;
  6412. begin
  6413. Result:=false;
  6414. { get rid of
  6415. (v)cvtss2sd reg0,<reg1,>reg2
  6416. (v)cvtss2sd reg2,<reg2,>reg0
  6417. }
  6418. if GetNextInstruction(p,hp1) and
  6419. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6420. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6421. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6422. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6423. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6424. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6425. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6426. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6427. )
  6428. ) then
  6429. begin
  6430. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6431. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6432. begin
  6433. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6434. RemoveCurrentP(p);
  6435. RemoveInstruction(hp1);
  6436. end
  6437. else
  6438. begin
  6439. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6440. if taicpu(hp1).opcode=A_CVTSD2SS then
  6441. begin
  6442. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6443. taicpu(p).opcode:=A_MOVAPS;
  6444. end
  6445. else
  6446. begin
  6447. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6448. taicpu(p).opcode:=A_VMOVAPS;
  6449. end;
  6450. taicpu(p).ops:=2;
  6451. RemoveInstruction(hp1);
  6452. end;
  6453. Result:=true;
  6454. Exit;
  6455. end;
  6456. end;
  6457. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6458. var
  6459. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6460. ThisReg: TRegister;
  6461. begin
  6462. Result := False;
  6463. if not GetNextInstruction(p,hp1) then
  6464. Exit;
  6465. {
  6466. convert
  6467. j<c> .L1
  6468. mov 1,reg
  6469. jmp .L2
  6470. .L1
  6471. mov 0,reg
  6472. .L2
  6473. into
  6474. mov 0,reg
  6475. set<not(c)> reg
  6476. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6477. would destroy the flag contents
  6478. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6479. executed at the same time as a previous comparison.
  6480. set<not(c)> reg
  6481. movzx reg, reg
  6482. }
  6483. if MatchInstruction(hp1,A_MOV,[]) and
  6484. (taicpu(hp1).oper[0]^.typ = top_const) and
  6485. (
  6486. (
  6487. (taicpu(hp1).oper[1]^.typ = top_reg)
  6488. {$ifdef i386}
  6489. { Under i386, ESI, EDI, EBP and ESP
  6490. don't have an 8-bit representation }
  6491. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6492. {$endif i386}
  6493. ) or (
  6494. {$ifdef i386}
  6495. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6496. {$endif i386}
  6497. (taicpu(hp1).opsize = S_B)
  6498. )
  6499. ) and
  6500. GetNextInstruction(hp1,hp2) and
  6501. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6502. GetNextInstruction(hp2,hp3) and
  6503. SkipAligns(hp3, hp3) and
  6504. (hp3.typ=ait_label) and
  6505. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6506. GetNextInstruction(hp3,hp4) and
  6507. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6508. (taicpu(hp4).oper[0]^.typ = top_const) and
  6509. (
  6510. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6511. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6512. ) and
  6513. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6514. GetNextInstruction(hp4,hp5) and
  6515. SkipAligns(hp5, hp5) and
  6516. (hp5.typ=ait_label) and
  6517. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6518. begin
  6519. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6520. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6521. tai_label(hp3).labsym.DecRefs;
  6522. { If this isn't the only reference to the middle label, we can
  6523. still make a saving - only that the first jump and everything
  6524. that follows will remain. }
  6525. if (tai_label(hp3).labsym.getrefs = 0) then
  6526. begin
  6527. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6528. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6529. else
  6530. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6531. { remove jump, first label and second MOV (also catching any aligns) }
  6532. repeat
  6533. if not GetNextInstruction(hp2, hp3) then
  6534. InternalError(2021040810);
  6535. RemoveInstruction(hp2);
  6536. hp2 := hp3;
  6537. until hp2 = hp5;
  6538. { Don't decrement reference count before the removal loop
  6539. above, otherwise GetNextInstruction won't stop on the
  6540. the label }
  6541. tai_label(hp5).labsym.DecRefs;
  6542. end
  6543. else
  6544. begin
  6545. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6546. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6547. else
  6548. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6549. end;
  6550. taicpu(p).opcode:=A_SETcc;
  6551. taicpu(p).opsize:=S_B;
  6552. taicpu(p).is_jmp:=False;
  6553. if taicpu(hp1).opsize=S_B then
  6554. begin
  6555. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6556. if taicpu(hp1).oper[1]^.typ = top_reg then
  6557. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6558. RemoveInstruction(hp1);
  6559. end
  6560. else
  6561. begin
  6562. { Will be a register because the size can't be S_B otherwise }
  6563. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6564. taicpu(p).loadreg(0, ThisReg);
  6565. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6566. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6567. begin
  6568. case taicpu(hp1).opsize of
  6569. S_W:
  6570. taicpu(hp1).opsize := S_BW;
  6571. S_L:
  6572. taicpu(hp1).opsize := S_BL;
  6573. {$ifdef x86_64}
  6574. S_Q:
  6575. begin
  6576. taicpu(hp1).opsize := S_BL;
  6577. { Change the destination register to 32-bit }
  6578. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6579. end;
  6580. {$endif x86_64}
  6581. else
  6582. InternalError(2021040820);
  6583. end;
  6584. taicpu(hp1).opcode := A_MOVZX;
  6585. taicpu(hp1).loadreg(0, ThisReg);
  6586. end
  6587. else
  6588. begin
  6589. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6590. { hp1 is already a MOV instruction with the correct register }
  6591. taicpu(hp1).loadconst(0, 0);
  6592. { Inserting it right before p will guarantee that the flags are also tracked }
  6593. asml.Remove(hp1);
  6594. asml.InsertBefore(hp1, p);
  6595. end;
  6596. end;
  6597. Result:=true;
  6598. exit;
  6599. end
  6600. else if (hp1.typ = ait_label) then
  6601. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6602. end;
  6603. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6604. var
  6605. hp1, hp2, hp3: tai;
  6606. SourceRef, TargetRef: TReference;
  6607. CurrentReg: TRegister;
  6608. begin
  6609. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6610. if not UseAVX then
  6611. InternalError(2021100501);
  6612. Result := False;
  6613. { Look for the following to simplify:
  6614. vmovdqa/u x(mem1), %xmmreg
  6615. vmovdqa/u %xmmreg, y(mem2)
  6616. vmovdqa/u x+16(mem1), %xmmreg
  6617. vmovdqa/u %xmmreg, y+16(mem2)
  6618. Change to:
  6619. vmovdqa/u x(mem1), %ymmreg
  6620. vmovdqa/u %ymmreg, y(mem2)
  6621. vpxor %ymmreg, %ymmreg, %ymmreg
  6622. ( The VPXOR instruction is to zero the upper half, thus removing the
  6623. need to call the potentially expensive VZEROUPPER instruction. Other
  6624. peephole optimisations can remove VPXOR if it's unnecessary )
  6625. }
  6626. TransferUsedRegs(TmpUsedRegs);
  6627. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6628. { NOTE: In the optimisations below, if the references dictate that an
  6629. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6630. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6631. if (taicpu(p).opsize = S_XMM) and
  6632. MatchOpType(taicpu(p), top_ref, top_reg) and
  6633. GetNextInstruction(p, hp1) and
  6634. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6635. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6636. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6637. begin
  6638. SourceRef := taicpu(p).oper[0]^.ref^;
  6639. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6640. if GetNextInstruction(hp1, hp2) and
  6641. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6642. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6643. begin
  6644. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6645. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6646. Inc(SourceRef.offset, 16);
  6647. { Reuse the register in the first block move }
  6648. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6649. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6650. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6651. begin
  6652. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6653. Inc(TargetRef.offset, 16);
  6654. if GetNextInstruction(hp2, hp3) and
  6655. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6656. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6657. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6658. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6659. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6660. begin
  6661. { Update the register tracking to the new size }
  6662. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6663. { Remember that the offsets are 16 ahead }
  6664. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6665. if not (
  6666. ((SourceRef.offset mod 32) = 16) and
  6667. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6668. ) then
  6669. taicpu(p).opcode := A_VMOVDQU;
  6670. taicpu(p).opsize := S_YMM;
  6671. taicpu(p).oper[1]^.reg := CurrentReg;
  6672. if not (
  6673. ((TargetRef.offset mod 32) = 16) and
  6674. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6675. ) then
  6676. taicpu(hp1).opcode := A_VMOVDQU;
  6677. taicpu(hp1).opsize := S_YMM;
  6678. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6679. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6680. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6681. if (pi_uses_ymm in current_procinfo.flags) then
  6682. RemoveInstruction(hp2)
  6683. else
  6684. begin
  6685. taicpu(hp2).opcode := A_VPXOR;
  6686. taicpu(hp2).opsize := S_YMM;
  6687. taicpu(hp2).loadreg(0, CurrentReg);
  6688. taicpu(hp2).loadreg(1, CurrentReg);
  6689. taicpu(hp2).loadreg(2, CurrentReg);
  6690. taicpu(hp2).ops := 3;
  6691. end;
  6692. RemoveInstruction(hp3);
  6693. Result := True;
  6694. Exit;
  6695. end;
  6696. end
  6697. else
  6698. begin
  6699. { See if the next references are 16 less rather than 16 greater }
  6700. Dec(SourceRef.offset, 32); { -16 the other way }
  6701. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6702. begin
  6703. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6704. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6705. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6706. GetNextInstruction(hp2, hp3) and
  6707. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6708. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6709. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6710. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6711. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6712. begin
  6713. { Update the register tracking to the new size }
  6714. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6715. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6716. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6717. if not(
  6718. ((SourceRef.offset mod 32) = 0) and
  6719. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6720. ) then
  6721. taicpu(hp2).opcode := A_VMOVDQU;
  6722. taicpu(hp2).opsize := S_YMM;
  6723. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6724. if not (
  6725. ((TargetRef.offset mod 32) = 0) and
  6726. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6727. ) then
  6728. taicpu(hp3).opcode := A_VMOVDQU;
  6729. taicpu(hp3).opsize := S_YMM;
  6730. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6731. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6732. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6733. if (pi_uses_ymm in current_procinfo.flags) then
  6734. RemoveInstruction(hp1)
  6735. else
  6736. begin
  6737. taicpu(hp1).opcode := A_VPXOR;
  6738. taicpu(hp1).opsize := S_YMM;
  6739. taicpu(hp1).loadreg(0, CurrentReg);
  6740. taicpu(hp1).loadreg(1, CurrentReg);
  6741. taicpu(hp1).loadreg(2, CurrentReg);
  6742. taicpu(hp1).ops := 3;
  6743. Asml.Remove(hp1);
  6744. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6745. end;
  6746. RemoveCurrentP(p, hp2);
  6747. Result := True;
  6748. Exit;
  6749. end;
  6750. end;
  6751. end;
  6752. end;
  6753. end;
  6754. end;
  6755. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6756. var
  6757. hp2, hp3, first_assignment: tai;
  6758. IncCount, OperIdx: Integer;
  6759. OrigLabel: TAsmLabel;
  6760. begin
  6761. Count := 0;
  6762. Result := False;
  6763. first_assignment := nil;
  6764. if (LoopCount >= 20) then
  6765. begin
  6766. { Guard against infinite loops }
  6767. Exit;
  6768. end;
  6769. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6770. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6771. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6772. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6773. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6774. Exit;
  6775. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6776. {
  6777. change
  6778. jmp .L1
  6779. ...
  6780. .L1:
  6781. mov ##, ## ( multiple movs possible )
  6782. jmp/ret
  6783. into
  6784. mov ##, ##
  6785. jmp/ret
  6786. }
  6787. if not Assigned(hp1) then
  6788. begin
  6789. hp1 := GetLabelWithSym(OrigLabel);
  6790. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6791. Exit;
  6792. end;
  6793. hp2 := hp1;
  6794. while Assigned(hp2) do
  6795. begin
  6796. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6797. SkipLabels(hp2,hp2);
  6798. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6799. Break;
  6800. case taicpu(hp2).opcode of
  6801. A_MOVSS:
  6802. begin
  6803. if taicpu(hp2).ops = 0 then
  6804. { Wrong MOVSS }
  6805. Break;
  6806. Inc(Count);
  6807. if Count >= 5 then
  6808. { Too many to be worthwhile }
  6809. Break;
  6810. GetNextInstruction(hp2, hp2);
  6811. Continue;
  6812. end;
  6813. A_MOV,
  6814. A_MOVD,
  6815. A_MOVQ,
  6816. A_MOVSX,
  6817. {$ifdef x86_64}
  6818. A_MOVSXD,
  6819. {$endif x86_64}
  6820. A_MOVZX,
  6821. A_MOVAPS,
  6822. A_MOVUPS,
  6823. A_MOVSD,
  6824. A_MOVAPD,
  6825. A_MOVUPD,
  6826. A_MOVDQA,
  6827. A_MOVDQU,
  6828. A_VMOVSS,
  6829. A_VMOVAPS,
  6830. A_VMOVUPS,
  6831. A_VMOVSD,
  6832. A_VMOVAPD,
  6833. A_VMOVUPD,
  6834. A_VMOVDQA,
  6835. A_VMOVDQU:
  6836. begin
  6837. Inc(Count);
  6838. if Count >= 5 then
  6839. { Too many to be worthwhile }
  6840. Break;
  6841. GetNextInstruction(hp2, hp2);
  6842. Continue;
  6843. end;
  6844. A_JMP:
  6845. begin
  6846. { Guard against infinite loops }
  6847. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6848. Exit;
  6849. { Analyse this jump first in case it also duplicates assignments }
  6850. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6851. begin
  6852. { Something did change! }
  6853. Result := True;
  6854. Inc(Count, IncCount);
  6855. if Count >= 5 then
  6856. begin
  6857. { Too many to be worthwhile }
  6858. Exit;
  6859. end;
  6860. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6861. Break;
  6862. end;
  6863. Result := True;
  6864. Break;
  6865. end;
  6866. A_RET:
  6867. begin
  6868. Result := True;
  6869. Break;
  6870. end;
  6871. else
  6872. Break;
  6873. end;
  6874. end;
  6875. if Result then
  6876. begin
  6877. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6878. if Count = 0 then
  6879. begin
  6880. Result := False;
  6881. Exit;
  6882. end;
  6883. hp3 := p;
  6884. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6885. while True do
  6886. begin
  6887. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6888. SkipLabels(hp1,hp1);
  6889. if (hp1.typ <> ait_instruction) then
  6890. InternalError(2021040720);
  6891. case taicpu(hp1).opcode of
  6892. A_JMP:
  6893. begin
  6894. { Change the original jump to the new destination }
  6895. OrigLabel.decrefs;
  6896. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6897. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6898. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6899. if not Assigned(first_assignment) then
  6900. InternalError(2021040810)
  6901. else
  6902. p := first_assignment;
  6903. Exit;
  6904. end;
  6905. A_RET:
  6906. begin
  6907. { Now change the jump into a RET instruction }
  6908. ConvertJumpToRET(p, hp1);
  6909. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6910. if not Assigned(first_assignment) then
  6911. InternalError(2021040811)
  6912. else
  6913. p := first_assignment;
  6914. Exit;
  6915. end;
  6916. else
  6917. begin
  6918. { Duplicate the MOV instruction }
  6919. hp3:=tai(hp1.getcopy);
  6920. if first_assignment = nil then
  6921. first_assignment := hp3;
  6922. asml.InsertBefore(hp3, p);
  6923. { Make sure the compiler knows about any final registers written here }
  6924. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6925. with taicpu(hp3).oper[OperIdx]^ do
  6926. begin
  6927. case typ of
  6928. top_ref:
  6929. begin
  6930. if (ref^.base <> NR_NO) and
  6931. (getsupreg(ref^.base) <> RS_ESP) and
  6932. (getsupreg(ref^.base) <> RS_EBP)
  6933. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6934. then
  6935. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6936. if (ref^.index <> NR_NO) and
  6937. (getsupreg(ref^.index) <> RS_ESP) and
  6938. (getsupreg(ref^.index) <> RS_EBP)
  6939. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6940. (ref^.index <> ref^.base) then
  6941. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6942. end;
  6943. top_reg:
  6944. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6945. else
  6946. ;
  6947. end;
  6948. end;
  6949. end;
  6950. end;
  6951. if not GetNextInstruction(hp1, hp1) then
  6952. { Should have dropped out earlier }
  6953. InternalError(2021040710);
  6954. end;
  6955. end;
  6956. end;
  6957. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6958. var
  6959. hp2: tai;
  6960. X: Integer;
  6961. const
  6962. WriteOp: array[0..3] of set of TInsChange = (
  6963. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6964. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6965. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6966. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6967. RegWriteFlags: array[0..7] of set of TInsChange = (
  6968. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6969. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6970. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6971. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6972. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6973. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6974. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6975. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6976. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6977. begin
  6978. { If we have something like:
  6979. cmp ###,%reg1
  6980. mov 0,%reg2
  6981. And no modified registers are shared, move the instruction to before
  6982. the comparison as this means it can be optimised without worrying
  6983. about the FLAGS register. (CMP/MOV is generated by
  6984. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6985. As long as the second instruction doesn't use the flags or one of the
  6986. registers used by CMP or TEST (also check any references that use the
  6987. registers), then it can be moved prior to the comparison.
  6988. }
  6989. Result := False;
  6990. if (hp1.typ <> ait_instruction) or
  6991. taicpu(hp1).is_jmp or
  6992. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6993. Exit;
  6994. { NOP is a pipeline fence, likely marking the beginning of the function
  6995. epilogue, so drop out. Similarly, drop out if POP or RET are
  6996. encountered }
  6997. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6998. Exit;
  6999. if (taicpu(hp1).opcode = A_MOVSS) and
  7000. (taicpu(hp1).ops = 0) then
  7001. { Wrong MOVSS }
  7002. Exit;
  7003. { Check for writes to specific registers first }
  7004. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7005. for X := 0 to 7 do
  7006. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7007. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7008. Exit;
  7009. for X := 0 to taicpu(hp1).ops - 1 do
  7010. begin
  7011. { Check to see if this operand writes to something }
  7012. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7013. { And matches something in the CMP/TEST instruction }
  7014. (
  7015. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7016. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7017. (
  7018. { If it's a register, make sure the register written to doesn't
  7019. appear in the cmp instruction as part of a reference }
  7020. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7021. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7022. )
  7023. ) then
  7024. Exit;
  7025. end;
  7026. { The instruction can be safely moved }
  7027. asml.Remove(hp1);
  7028. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  7029. if not GetLastInstruction(p, hp2) then
  7030. asml.InsertBefore(hp1, p)
  7031. else
  7032. asml.InsertAfter(hp1, hp2);
  7033. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7034. for X := 0 to taicpu(hp1).ops - 1 do
  7035. case taicpu(hp1).oper[X]^.typ of
  7036. top_reg:
  7037. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7038. top_ref:
  7039. begin
  7040. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7041. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7042. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7043. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7044. end;
  7045. else
  7046. ;
  7047. end;
  7048. if taicpu(hp1).opcode = A_LEA then
  7049. { The flags will be overwritten by the CMP/TEST instruction }
  7050. ConvertLEA(taicpu(hp1));
  7051. Result := True;
  7052. end;
  7053. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7054. function IsXCHGAcceptable: Boolean; inline;
  7055. begin
  7056. { Always accept if optimising for size }
  7057. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7058. (
  7059. {$ifdef x86_64}
  7060. { XCHG takes 3 cycles on AMD Athlon64 }
  7061. (current_settings.optimizecputype >= cpu_core_i)
  7062. {$else x86_64}
  7063. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7064. than 3, so it becomes a saving compared to three MOVs with two of
  7065. them able to execute simultaneously. [Kit] }
  7066. (current_settings.optimizecputype >= cpu_PentiumM)
  7067. {$endif x86_64}
  7068. );
  7069. end;
  7070. var
  7071. NewRef: TReference;
  7072. hp1, hp2, hp3, hp4: Tai;
  7073. {$ifndef x86_64}
  7074. OperIdx: Integer;
  7075. {$endif x86_64}
  7076. NewInstr : Taicpu;
  7077. NewAligh : Tai_align;
  7078. DestLabel: TAsmLabel;
  7079. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7080. var
  7081. NextInstr: tai;
  7082. begin
  7083. Result := False;
  7084. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7085. if not GetNextInstruction(InputInstr, NextInstr) or
  7086. (
  7087. { The FLAGS register isn't always tracked properly, so do not
  7088. perform this optimisation if a conditional statement follows }
  7089. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7090. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7091. ) then
  7092. begin
  7093. reference_reset(NewRef, 1, []);
  7094. NewRef.base := taicpu(p).oper[0]^.reg;
  7095. NewRef.scalefactor := 1;
  7096. if taicpu(InputInstr).opcode = A_ADD then
  7097. begin
  7098. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7099. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7100. end
  7101. else
  7102. begin
  7103. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7104. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7105. end;
  7106. taicpu(p).opcode := A_LEA;
  7107. taicpu(p).loadref(0, NewRef);
  7108. RemoveInstruction(InputInstr);
  7109. Result := True;
  7110. end;
  7111. end;
  7112. begin
  7113. Result:=false;
  7114. { This optimisation adds an instruction, so only do it for speed }
  7115. if not (cs_opt_size in current_settings.optimizerswitches) and
  7116. MatchOpType(taicpu(p), top_const, top_reg) and
  7117. (taicpu(p).oper[0]^.val = 0) then
  7118. begin
  7119. { To avoid compiler warning }
  7120. DestLabel := nil;
  7121. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7122. InternalError(2021040750);
  7123. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7124. Exit;
  7125. case hp1.typ of
  7126. ait_label:
  7127. begin
  7128. { Change:
  7129. mov $0,%reg mov $0,%reg
  7130. @Lbl1: @Lbl1:
  7131. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7132. je @Lbl2 jne @Lbl2
  7133. To: To:
  7134. mov $0,%reg mov $0,%reg
  7135. jmp @Lbl2 jmp @Lbl3
  7136. (align) (align)
  7137. @Lbl1: @Lbl1:
  7138. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7139. je @Lbl2 je @Lbl2
  7140. @Lbl3: <-- Only if label exists
  7141. (Not if it's optimised for size)
  7142. }
  7143. if not GetNextInstruction(hp1, hp2) then
  7144. Exit;
  7145. if not (cs_opt_size in current_settings.optimizerswitches) and
  7146. (hp2.typ = ait_instruction) and
  7147. (
  7148. { Register sizes must exactly match }
  7149. (
  7150. (taicpu(hp2).opcode = A_CMP) and
  7151. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7152. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7153. ) or (
  7154. (taicpu(hp2).opcode = A_TEST) and
  7155. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7156. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7157. )
  7158. ) and GetNextInstruction(hp2, hp3) and
  7159. (hp3.typ = ait_instruction) and
  7160. (taicpu(hp3).opcode = A_JCC) and
  7161. (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
  7162. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7163. begin
  7164. { Check condition of jump }
  7165. { Always true? }
  7166. if condition_in(C_E, taicpu(hp3).condition) then
  7167. begin
  7168. { Copy label symbol and obtain matching label entry for the
  7169. conditional jump, as this will be our destination}
  7170. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7171. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7172. Result := True;
  7173. end
  7174. { Always false? }
  7175. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7176. begin
  7177. { This is only worth it if there's a jump to take }
  7178. case hp2.typ of
  7179. ait_instruction:
  7180. begin
  7181. if taicpu(hp2).opcode = A_JMP then
  7182. begin
  7183. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7184. { An unconditional jump follows the conditional jump which will always be false,
  7185. so use this jump's destination for the new jump }
  7186. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7187. Result := True;
  7188. end
  7189. else if taicpu(hp2).opcode = A_JCC then
  7190. begin
  7191. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7192. if condition_in(C_E, taicpu(hp2).condition) then
  7193. begin
  7194. { A second conditional jump follows the conditional jump which will always be false,
  7195. while the second jump is always True, so use this jump's destination for the new jump }
  7196. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7197. Result := True;
  7198. end;
  7199. { Don't risk it if the jump isn't always true (Result remains False) }
  7200. end;
  7201. end;
  7202. else
  7203. { If anything else don't optimise };
  7204. end;
  7205. end;
  7206. if Result then
  7207. begin
  7208. { Just so we have something to insert as a paremeter}
  7209. reference_reset(NewRef, 1, []);
  7210. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7211. { Now actually load the correct parameter }
  7212. NewInstr.loadsymbol(0, DestLabel, 0);
  7213. { Get instruction before original label (may not be p under -O3) }
  7214. if not GetLastInstruction(hp1, hp2) then
  7215. { Shouldn't fail here }
  7216. InternalError(2021040701);
  7217. DestLabel.increfs;
  7218. AsmL.InsertAfter(NewInstr, hp2);
  7219. { Add new alignment field }
  7220. (* AsmL.InsertAfter(
  7221. cai_align.create_max(
  7222. current_settings.alignment.jumpalign,
  7223. current_settings.alignment.jumpalignskipmax
  7224. ),
  7225. NewInstr
  7226. ); *)
  7227. end;
  7228. Exit;
  7229. end;
  7230. end;
  7231. else
  7232. ;
  7233. end;
  7234. end;
  7235. if not GetNextInstruction(p, hp1) then
  7236. Exit;
  7237. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7238. and DoMovCmpMemOpt(p, hp1, True) then
  7239. begin
  7240. Result := True;
  7241. Exit;
  7242. end
  7243. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7244. begin
  7245. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7246. further, but we can't just put this jump optimisation in pass 1
  7247. because it tends to perform worse when conditional jumps are
  7248. nearby (e.g. when converting CMOV instructions). [Kit] }
  7249. if OptPass2JMP(hp1) then
  7250. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7251. Result := OptPass1MOV(p)
  7252. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7253. returned True and the instruction is still a MOV, thus checking
  7254. the optimisations below }
  7255. { If OptPass2JMP returned False, no optimisations were done to
  7256. the jump and there are no further optimisations that can be done
  7257. to the MOV instruction on this pass }
  7258. end
  7259. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7260. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7261. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7262. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7263. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7264. begin
  7265. { Change:
  7266. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7267. addl/q $x,%reg2 subl/q $x,%reg2
  7268. To:
  7269. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7270. }
  7271. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7272. { be lazy, checking separately for sub would be slightly better }
  7273. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7274. begin
  7275. TransferUsedRegs(TmpUsedRegs);
  7276. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7277. if TryMovArith2Lea(hp1) then
  7278. begin
  7279. Result := True;
  7280. Exit;
  7281. end
  7282. end
  7283. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7284. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7285. { Same as above, but also adds or subtracts to %reg2 in between.
  7286. It's still valid as long as the flags aren't in use }
  7287. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7288. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7289. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7290. { be lazy, checking separately for sub would be slightly better }
  7291. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7292. begin
  7293. TransferUsedRegs(TmpUsedRegs);
  7294. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7295. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7296. if TryMovArith2Lea(hp2) then
  7297. begin
  7298. Result := True;
  7299. Exit;
  7300. end;
  7301. end;
  7302. end
  7303. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7304. {$ifdef x86_64}
  7305. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7306. {$else x86_64}
  7307. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7308. {$endif x86_64}
  7309. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7310. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7311. { mov reg1, reg2 mov reg1, reg2
  7312. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7313. begin
  7314. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7315. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7316. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7317. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7318. TransferUsedRegs(TmpUsedRegs);
  7319. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7320. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7321. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7322. then
  7323. begin
  7324. RemoveCurrentP(p, hp1);
  7325. Result:=true;
  7326. end;
  7327. exit;
  7328. end
  7329. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7330. IsXCHGAcceptable and
  7331. { XCHG doesn't support 8-byte registers }
  7332. (taicpu(p).opsize <> S_B) and
  7333. MatchInstruction(hp1, A_MOV, []) and
  7334. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7335. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7336. GetNextInstruction(hp1, hp2) and
  7337. MatchInstruction(hp2, A_MOV, []) and
  7338. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7339. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7340. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7341. begin
  7342. { mov %reg1,%reg2
  7343. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7344. mov %reg2,%reg3
  7345. (%reg2 not used afterwards)
  7346. Note that xchg takes 3 cycles to execute, and generally mov's take
  7347. only one cycle apiece, but the first two mov's can be executed in
  7348. parallel, only taking 2 cycles overall. Older processors should
  7349. therefore only optimise for size. [Kit]
  7350. }
  7351. TransferUsedRegs(TmpUsedRegs);
  7352. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7353. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7354. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7355. begin
  7356. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7357. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7358. taicpu(hp1).opcode := A_XCHG;
  7359. RemoveCurrentP(p, hp1);
  7360. RemoveInstruction(hp2);
  7361. Result := True;
  7362. Exit;
  7363. end;
  7364. end
  7365. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7366. MatchInstruction(hp1, A_SAR, []) then
  7367. begin
  7368. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7369. begin
  7370. { the use of %edx also covers the opsize being S_L }
  7371. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7372. begin
  7373. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7374. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7375. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7376. begin
  7377. { Change:
  7378. movl %eax,%edx
  7379. sarl $31,%edx
  7380. To:
  7381. cltd
  7382. }
  7383. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7384. RemoveInstruction(hp1);
  7385. taicpu(p).opcode := A_CDQ;
  7386. taicpu(p).opsize := S_NO;
  7387. taicpu(p).clearop(1);
  7388. taicpu(p).clearop(0);
  7389. taicpu(p).ops:=0;
  7390. Result := True;
  7391. end
  7392. else if (cs_opt_size in current_settings.optimizerswitches) and
  7393. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7394. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7395. begin
  7396. { Change:
  7397. movl %edx,%eax
  7398. sarl $31,%edx
  7399. To:
  7400. movl %edx,%eax
  7401. cltd
  7402. Note that this creates a dependency between the two instructions,
  7403. so only perform if optimising for size.
  7404. }
  7405. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7406. taicpu(hp1).opcode := A_CDQ;
  7407. taicpu(hp1).opsize := S_NO;
  7408. taicpu(hp1).clearop(1);
  7409. taicpu(hp1).clearop(0);
  7410. taicpu(hp1).ops:=0;
  7411. end;
  7412. {$ifndef x86_64}
  7413. end
  7414. { Don't bother if CMOV is supported, because a more optimal
  7415. sequence would have been generated for the Abs() intrinsic }
  7416. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7417. { the use of %eax also covers the opsize being S_L }
  7418. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7419. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7420. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7421. GetNextInstruction(hp1, hp2) and
  7422. MatchInstruction(hp2, A_XOR, [S_L]) and
  7423. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7424. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7425. GetNextInstruction(hp2, hp3) and
  7426. MatchInstruction(hp3, A_SUB, [S_L]) and
  7427. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7428. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7429. begin
  7430. { Change:
  7431. movl %eax,%edx
  7432. sarl $31,%eax
  7433. xorl %eax,%edx
  7434. subl %eax,%edx
  7435. (Instruction that uses %edx)
  7436. (%eax deallocated)
  7437. (%edx deallocated)
  7438. To:
  7439. cltd
  7440. xorl %edx,%eax <-- Note the registers have swapped
  7441. subl %edx,%eax
  7442. (Instruction that uses %eax) <-- %eax rather than %edx
  7443. }
  7444. TransferUsedRegs(TmpUsedRegs);
  7445. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7446. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7447. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7448. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7449. begin
  7450. if GetNextInstruction(hp3, hp4) and
  7451. not RegModifiedByInstruction(NR_EDX, hp4) and
  7452. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7453. begin
  7454. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7455. taicpu(p).opcode := A_CDQ;
  7456. taicpu(p).clearop(1);
  7457. taicpu(p).clearop(0);
  7458. taicpu(p).ops:=0;
  7459. RemoveInstruction(hp1);
  7460. taicpu(hp2).loadreg(0, NR_EDX);
  7461. taicpu(hp2).loadreg(1, NR_EAX);
  7462. taicpu(hp3).loadreg(0, NR_EDX);
  7463. taicpu(hp3).loadreg(1, NR_EAX);
  7464. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7465. { Convert references in the following instruction (hp4) from %edx to %eax }
  7466. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7467. with taicpu(hp4).oper[OperIdx]^ do
  7468. case typ of
  7469. top_reg:
  7470. if getsupreg(reg) = RS_EDX then
  7471. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7472. top_ref:
  7473. begin
  7474. if getsupreg(reg) = RS_EDX then
  7475. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7476. if getsupreg(reg) = RS_EDX then
  7477. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7478. end;
  7479. else
  7480. ;
  7481. end;
  7482. end;
  7483. end;
  7484. {$else x86_64}
  7485. end;
  7486. end
  7487. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7488. { the use of %rdx also covers the opsize being S_Q }
  7489. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7490. begin
  7491. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7492. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7493. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7494. begin
  7495. { Change:
  7496. movq %rax,%rdx
  7497. sarq $63,%rdx
  7498. To:
  7499. cqto
  7500. }
  7501. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7502. RemoveInstruction(hp1);
  7503. taicpu(p).opcode := A_CQO;
  7504. taicpu(p).opsize := S_NO;
  7505. taicpu(p).clearop(1);
  7506. taicpu(p).clearop(0);
  7507. taicpu(p).ops:=0;
  7508. Result := True;
  7509. end
  7510. else if (cs_opt_size in current_settings.optimizerswitches) and
  7511. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7512. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7513. begin
  7514. { Change:
  7515. movq %rdx,%rax
  7516. sarq $63,%rdx
  7517. To:
  7518. movq %rdx,%rax
  7519. cqto
  7520. Note that this creates a dependency between the two instructions,
  7521. so only perform if optimising for size.
  7522. }
  7523. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7524. taicpu(hp1).opcode := A_CQO;
  7525. taicpu(hp1).opsize := S_NO;
  7526. taicpu(hp1).clearop(1);
  7527. taicpu(hp1).clearop(0);
  7528. taicpu(hp1).ops:=0;
  7529. {$endif x86_64}
  7530. end;
  7531. end;
  7532. end
  7533. else if MatchInstruction(hp1, A_MOV, []) and
  7534. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7535. { Though "GetNextInstruction" could be factored out, along with
  7536. the instructions that depend on hp2, it is an expensive call that
  7537. should be delayed for as long as possible, hence we do cheaper
  7538. checks first that are likely to be False. [Kit] }
  7539. begin
  7540. if (
  7541. (
  7542. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7543. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7544. (
  7545. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7546. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7547. )
  7548. ) or
  7549. (
  7550. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7551. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7552. (
  7553. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7554. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7555. )
  7556. )
  7557. ) and
  7558. GetNextInstruction(hp1, hp2) and
  7559. MatchInstruction(hp2, A_SAR, []) and
  7560. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7561. begin
  7562. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7563. begin
  7564. { Change:
  7565. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7566. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7567. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7568. To:
  7569. movl r/m,%eax <- Note the change in register
  7570. cltd
  7571. }
  7572. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7573. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7574. taicpu(p).loadreg(1, NR_EAX);
  7575. taicpu(hp1).opcode := A_CDQ;
  7576. taicpu(hp1).clearop(1);
  7577. taicpu(hp1).clearop(0);
  7578. taicpu(hp1).ops:=0;
  7579. RemoveInstruction(hp2);
  7580. (*
  7581. {$ifdef x86_64}
  7582. end
  7583. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7584. { This code sequence does not get generated - however it might become useful
  7585. if and when 128-bit signed integer types make an appearance, so the code
  7586. is kept here for when it is eventually needed. [Kit] }
  7587. (
  7588. (
  7589. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7590. (
  7591. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7592. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7593. )
  7594. ) or
  7595. (
  7596. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7597. (
  7598. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7599. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7600. )
  7601. )
  7602. ) and
  7603. GetNextInstruction(hp1, hp2) and
  7604. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7605. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7606. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7607. begin
  7608. { Change:
  7609. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7610. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7611. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7612. To:
  7613. movq r/m,%rax <- Note the change in register
  7614. cqto
  7615. }
  7616. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7617. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7618. taicpu(p).loadreg(1, NR_RAX);
  7619. taicpu(hp1).opcode := A_CQO;
  7620. taicpu(hp1).clearop(1);
  7621. taicpu(hp1).clearop(0);
  7622. taicpu(hp1).ops:=0;
  7623. RemoveInstruction(hp2);
  7624. {$endif x86_64}
  7625. *)
  7626. end;
  7627. end;
  7628. {$ifdef x86_64}
  7629. end
  7630. else if (taicpu(p).opsize = S_L) and
  7631. (taicpu(p).oper[1]^.typ = top_reg) and
  7632. (
  7633. MatchInstruction(hp1, A_MOV,[]) and
  7634. (taicpu(hp1).opsize = S_L) and
  7635. (taicpu(hp1).oper[1]^.typ = top_reg)
  7636. ) and (
  7637. GetNextInstruction(hp1, hp2) and
  7638. (tai(hp2).typ=ait_instruction) and
  7639. (taicpu(hp2).opsize = S_Q) and
  7640. (
  7641. (
  7642. MatchInstruction(hp2, A_ADD,[]) and
  7643. (taicpu(hp2).opsize = S_Q) and
  7644. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7645. (
  7646. (
  7647. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7648. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7649. ) or (
  7650. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7651. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7652. )
  7653. )
  7654. ) or (
  7655. MatchInstruction(hp2, A_LEA,[]) and
  7656. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7657. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7658. (
  7659. (
  7660. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7661. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7662. ) or (
  7663. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7664. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7665. )
  7666. ) and (
  7667. (
  7668. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7669. ) or (
  7670. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7671. )
  7672. )
  7673. )
  7674. )
  7675. ) and (
  7676. GetNextInstruction(hp2, hp3) and
  7677. MatchInstruction(hp3, A_SHR,[]) and
  7678. (taicpu(hp3).opsize = S_Q) and
  7679. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7680. (taicpu(hp3).oper[0]^.val = 1) and
  7681. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7682. ) then
  7683. begin
  7684. { Change movl x, reg1d movl x, reg1d
  7685. movl y, reg2d movl y, reg2d
  7686. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7687. shrq $1, reg1q shrq $1, reg1q
  7688. ( reg1d and reg2d can be switched around in the first two instructions )
  7689. To movl x, reg1d
  7690. addl y, reg1d
  7691. rcrl $1, reg1d
  7692. This corresponds to the common expression (x + y) shr 1, where
  7693. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7694. smaller code, but won't account for x + y causing an overflow). [Kit]
  7695. }
  7696. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7697. { Change first MOV command to have the same register as the final output }
  7698. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7699. else
  7700. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7701. { Change second MOV command to an ADD command. This is easier than
  7702. converting the existing command because it means we don't have to
  7703. touch 'y', which might be a complicated reference, and also the
  7704. fact that the third command might either be ADD or LEA. [Kit] }
  7705. taicpu(hp1).opcode := A_ADD;
  7706. { Delete old ADD/LEA instruction }
  7707. RemoveInstruction(hp2);
  7708. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7709. taicpu(hp3).opcode := A_RCR;
  7710. taicpu(hp3).changeopsize(S_L);
  7711. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7712. {$endif x86_64}
  7713. end;
  7714. end;
  7715. {$push}
  7716. {$q-}{$r-}
  7717. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7718. var
  7719. ThisReg: TRegister;
  7720. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7721. TargetSubReg: TSubRegister;
  7722. hp1, hp2: tai;
  7723. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7724. { Store list of found instructions so we don't have to call
  7725. GetNextInstructionUsingReg multiple times }
  7726. InstrList: array of taicpu;
  7727. InstrMax, Index: Integer;
  7728. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7729. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7730. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7731. WorkingValue: TCgInt;
  7732. PreMessage: string;
  7733. { Data flow analysis }
  7734. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7735. BitwiseOnly, OrXorUsed,
  7736. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7737. function CheckOverflowConditions: Boolean;
  7738. begin
  7739. Result := True;
  7740. if (TestValSignedMax > SignedUpperLimit) then
  7741. UpperSignedOverflow := True;
  7742. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7743. LowerSignedOverflow := True;
  7744. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7745. LowerUnsignedOverflow := True;
  7746. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7747. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7748. begin
  7749. { Absolute overflow }
  7750. Result := False;
  7751. Exit;
  7752. end;
  7753. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7754. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7755. ShiftDownOverflow := True;
  7756. if (TestValMin < 0) or (TestValMax < 0) then
  7757. begin
  7758. LowerUnsignedOverflow := True;
  7759. UpperUnsignedOverflow := True;
  7760. end;
  7761. end;
  7762. function AdjustInitialLoadAndSize: Boolean;
  7763. begin
  7764. Result := False;
  7765. if not p_removed then
  7766. begin
  7767. if TargetSize = MinSize then
  7768. begin
  7769. { Convert the input MOVZX to a MOV }
  7770. if (taicpu(p).oper[0]^.typ = top_reg) and
  7771. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7772. begin
  7773. { Or remove it completely! }
  7774. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7775. RemoveCurrentP(p);
  7776. p_removed := True;
  7777. end
  7778. else
  7779. begin
  7780. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7781. taicpu(p).opcode := A_MOV;
  7782. taicpu(p).oper[1]^.reg := ThisReg;
  7783. taicpu(p).opsize := TargetSize;
  7784. end;
  7785. Result := True;
  7786. end
  7787. else if TargetSize <> MaxSize then
  7788. begin
  7789. case MaxSize of
  7790. S_L:
  7791. if TargetSize = S_W then
  7792. begin
  7793. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7794. taicpu(p).opsize := S_BW;
  7795. taicpu(p).oper[1]^.reg := ThisReg;
  7796. Result := True;
  7797. end
  7798. else
  7799. InternalError(2020112341);
  7800. S_W:
  7801. if TargetSize = S_L then
  7802. begin
  7803. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7804. taicpu(p).opsize := S_BL;
  7805. taicpu(p).oper[1]^.reg := ThisReg;
  7806. Result := True;
  7807. end
  7808. else
  7809. InternalError(2020112342);
  7810. else
  7811. ;
  7812. end;
  7813. end
  7814. else if not hp1_removed and not RegInUse then
  7815. begin
  7816. { If we have something like:
  7817. movzbl (oper),%regd
  7818. add x, %regd
  7819. movzbl %regb, %regd
  7820. We can reduce the register size to the input of the final
  7821. movzbl instruction. Overflows won't have any effect.
  7822. }
  7823. if (taicpu(p).opsize in [S_BW, S_BL]) and
  7824. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7825. begin
  7826. TargetSize := S_B;
  7827. setsubreg(ThisReg, R_SUBL);
  7828. Result := True;
  7829. end
  7830. else if (taicpu(p).opsize = S_WL) and
  7831. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  7832. begin
  7833. TargetSize := S_W;
  7834. setsubreg(ThisReg, R_SUBW);
  7835. Result := True;
  7836. end;
  7837. if Result then
  7838. begin
  7839. { Convert the input MOVZX to a MOV }
  7840. if (taicpu(p).oper[0]^.typ = top_reg) and
  7841. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7842. begin
  7843. { Or remove it completely! }
  7844. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7845. RemoveCurrentP(p);
  7846. p_removed := True;
  7847. end
  7848. else
  7849. begin
  7850. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7851. taicpu(p).opcode := A_MOV;
  7852. taicpu(p).oper[1]^.reg := ThisReg;
  7853. taicpu(p).opsize := TargetSize;
  7854. end;
  7855. end;
  7856. end;
  7857. end;
  7858. end;
  7859. procedure AdjustFinalLoad;
  7860. begin
  7861. if not LowerUnsignedOverflow then
  7862. begin
  7863. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7864. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7865. begin
  7866. { Convert the output MOVZX to a MOV }
  7867. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7868. begin
  7869. { Or remove it completely! }
  7870. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7871. { Be careful; if p = hp1 and p was also removed, p
  7872. will become a dangling pointer }
  7873. if p = hp1 then
  7874. begin
  7875. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7876. p_removed := True;
  7877. end
  7878. else
  7879. RemoveInstruction(hp1);
  7880. hp1_removed := True;
  7881. end
  7882. else
  7883. begin
  7884. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7885. taicpu(hp1).opcode := A_MOV;
  7886. taicpu(hp1).oper[0]^.reg := ThisReg;
  7887. taicpu(hp1).opsize := TargetSize;
  7888. end;
  7889. end
  7890. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7891. begin
  7892. { Need to change the size of the output }
  7893. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7894. taicpu(hp1).oper[0]^.reg := ThisReg;
  7895. taicpu(hp1).opsize := S_BL;
  7896. end;
  7897. end;
  7898. end;
  7899. function CompressInstructions: Boolean;
  7900. var
  7901. LocalIndex: Integer;
  7902. begin
  7903. Result := False;
  7904. { The objective here is to try to find a combination that
  7905. removes one of the MOV/Z instructions. }
  7906. if (
  7907. (taicpu(p).oper[0]^.typ <> top_reg) or
  7908. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7909. ) and
  7910. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7911. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7912. begin
  7913. { Make a preference to remove the second MOVZX instruction }
  7914. case taicpu(hp1).opsize of
  7915. S_BL, S_WL:
  7916. begin
  7917. TargetSize := S_L;
  7918. TargetSubReg := R_SUBD;
  7919. end;
  7920. S_BW:
  7921. begin
  7922. TargetSize := S_W;
  7923. TargetSubReg := R_SUBW;
  7924. end;
  7925. else
  7926. InternalError(2020112302);
  7927. end;
  7928. end
  7929. else
  7930. begin
  7931. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7932. begin
  7933. { Exceeded lower bound but not upper bound }
  7934. TargetSize := MaxSize;
  7935. end
  7936. else if not LowerUnsignedOverflow then
  7937. begin
  7938. { Size didn't exceed lower bound }
  7939. TargetSize := MinSize;
  7940. end
  7941. else
  7942. Exit;
  7943. end;
  7944. case TargetSize of
  7945. S_B:
  7946. TargetSubReg := R_SUBL;
  7947. S_W:
  7948. TargetSubReg := R_SUBW;
  7949. S_L:
  7950. TargetSubReg := R_SUBD;
  7951. else
  7952. InternalError(2020112350);
  7953. end;
  7954. { Update the register to its new size }
  7955. setsubreg(ThisReg, TargetSubReg);
  7956. RegInUse := False;
  7957. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7958. begin
  7959. { Check to see if the active register is used afterwards;
  7960. if not, we can change it and make a saving. }
  7961. TransferUsedRegs(TmpUsedRegs);
  7962. { The target register may be marked as in use to cross
  7963. a jump to a distant label, so exclude it }
  7964. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7965. hp2 := p;
  7966. repeat
  7967. { Explicitly check for the excluded register (don't include the first
  7968. instruction as it may be reading from here }
  7969. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7970. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7971. begin
  7972. RegInUse := True;
  7973. Break;
  7974. end;
  7975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7976. if not GetNextInstruction(hp2, hp2) then
  7977. InternalError(2020112340);
  7978. until (hp2 = hp1);
  7979. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7980. { We might still be able to get away with this }
  7981. RegInUse := not
  7982. (
  7983. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7984. (hp2.typ = ait_instruction) and
  7985. (
  7986. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7987. instruction that doesn't actually contain ThisReg }
  7988. (cs_opt_level3 in current_settings.optimizerswitches) or
  7989. RegInInstruction(ThisReg, hp2)
  7990. ) and
  7991. RegLoadedWithNewValue(ThisReg, hp2)
  7992. );
  7993. if not RegInUse then
  7994. begin
  7995. { Force the register size to the same as this instruction so it can be removed}
  7996. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7997. begin
  7998. TargetSize := S_L;
  7999. TargetSubReg := R_SUBD;
  8000. end
  8001. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8002. begin
  8003. TargetSize := S_W;
  8004. TargetSubReg := R_SUBW;
  8005. end;
  8006. ThisReg := taicpu(hp1).oper[1]^.reg;
  8007. setsubreg(ThisReg, TargetSubReg);
  8008. RegChanged := True;
  8009. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8010. TransferUsedRegs(TmpUsedRegs);
  8011. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8012. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8013. if p = hp1 then
  8014. begin
  8015. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8016. p_removed := True;
  8017. end
  8018. else
  8019. RemoveInstruction(hp1);
  8020. hp1_removed := True;
  8021. { Instruction will become "mov %reg,%reg" }
  8022. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8023. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8024. begin
  8025. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8026. RemoveCurrentP(p);
  8027. p_removed := True;
  8028. end
  8029. else
  8030. taicpu(p).oper[1]^.reg := ThisReg;
  8031. Result := True;
  8032. end
  8033. else
  8034. begin
  8035. if TargetSize <> MaxSize then
  8036. begin
  8037. { Since the register is in use, we have to force it to
  8038. MaxSize otherwise part of it may become undefined later on }
  8039. TargetSize := MaxSize;
  8040. case TargetSize of
  8041. S_B:
  8042. TargetSubReg := R_SUBL;
  8043. S_W:
  8044. TargetSubReg := R_SUBW;
  8045. S_L:
  8046. TargetSubReg := R_SUBD;
  8047. else
  8048. InternalError(2020112351);
  8049. end;
  8050. setsubreg(ThisReg, TargetSubReg);
  8051. end;
  8052. AdjustFinalLoad;
  8053. end;
  8054. end
  8055. else
  8056. AdjustFinalLoad;
  8057. Result := AdjustInitialLoadAndSize or Result;
  8058. { Now go through every instruction we found and change the
  8059. size. If TargetSize = MaxSize, then almost no changes are
  8060. needed and Result can remain False if it hasn't been set
  8061. yet.
  8062. If RegChanged is True, then the register requires changing
  8063. and so the point about TargetSize = MaxSize doesn't apply. }
  8064. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8065. begin
  8066. for LocalIndex := 0 to InstrMax do
  8067. begin
  8068. { If p_removed is true, then the original MOV/Z was removed
  8069. and removing the AND instruction may not be safe if it
  8070. appears first }
  8071. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8072. InternalError(2020112310);
  8073. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8074. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8075. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8076. InstrList[LocalIndex].opsize := TargetSize;
  8077. end;
  8078. Result := True;
  8079. end;
  8080. end;
  8081. begin
  8082. Result := False;
  8083. p_removed := False;
  8084. hp1_removed := False;
  8085. ThisReg := taicpu(p).oper[1]^.reg;
  8086. { Check for:
  8087. movs/z ###,%ecx (or %cx or %rcx)
  8088. ...
  8089. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8090. (dealloc %ecx)
  8091. Change to:
  8092. mov ###,%cl (if ### = %cl, then remove completely)
  8093. ...
  8094. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8095. }
  8096. if (getsupreg(ThisReg) = RS_ECX) and
  8097. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8098. (hp1.typ = ait_instruction) and
  8099. (
  8100. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8101. instruction that doesn't actually contain ECX }
  8102. (cs_opt_level3 in current_settings.optimizerswitches) or
  8103. RegInInstruction(NR_ECX, hp1) or
  8104. (
  8105. { It's common for the shift/rotate's read/write register to be
  8106. initialised in between, so under -O2 and under, search ahead
  8107. one more instruction
  8108. }
  8109. GetNextInstruction(hp1, hp1) and
  8110. (hp1.typ = ait_instruction) and
  8111. RegInInstruction(NR_ECX, hp1)
  8112. )
  8113. ) and
  8114. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8115. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8116. begin
  8117. TransferUsedRegs(TmpUsedRegs);
  8118. hp2 := p;
  8119. repeat
  8120. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8121. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8122. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8123. begin
  8124. case taicpu(p).opsize of
  8125. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8126. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8127. begin
  8128. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8129. RemoveCurrentP(p);
  8130. end
  8131. else
  8132. begin
  8133. taicpu(p).opcode := A_MOV;
  8134. taicpu(p).opsize := S_B;
  8135. taicpu(p).oper[1]^.reg := NR_CL;
  8136. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8137. end;
  8138. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8139. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8140. begin
  8141. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8142. RemoveCurrentP(p);
  8143. end
  8144. else
  8145. begin
  8146. taicpu(p).opcode := A_MOV;
  8147. taicpu(p).opsize := S_W;
  8148. taicpu(p).oper[1]^.reg := NR_CX;
  8149. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8150. end;
  8151. {$ifdef x86_64}
  8152. S_LQ:
  8153. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8154. begin
  8155. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8156. RemoveCurrentP(p);
  8157. end
  8158. else
  8159. begin
  8160. taicpu(p).opcode := A_MOV;
  8161. taicpu(p).opsize := S_L;
  8162. taicpu(p).oper[1]^.reg := NR_ECX;
  8163. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8164. end;
  8165. {$endif x86_64}
  8166. else
  8167. InternalError(2021120401);
  8168. end;
  8169. Result := True;
  8170. Exit;
  8171. end;
  8172. end;
  8173. { This is anything but quick! }
  8174. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8175. Exit;
  8176. SetLength(InstrList, 0);
  8177. InstrMax := -1;
  8178. case taicpu(p).opsize of
  8179. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8180. begin
  8181. {$if defined(i386) or defined(i8086)}
  8182. { If the target size is 8-bit, make sure we can actually encode it }
  8183. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8184. Exit;
  8185. {$endif i386 or i8086}
  8186. LowerLimit := $FF;
  8187. SignedLowerLimit := $7F;
  8188. SignedLowerLimitBottom := -128;
  8189. MinSize := S_B;
  8190. if taicpu(p).opsize = S_BW then
  8191. begin
  8192. MaxSize := S_W;
  8193. UpperLimit := $FFFF;
  8194. SignedUpperLimit := $7FFF;
  8195. SignedUpperLimitBottom := -32768;
  8196. end
  8197. else
  8198. begin
  8199. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8200. MaxSize := S_L;
  8201. UpperLimit := $FFFFFFFF;
  8202. SignedUpperLimit := $7FFFFFFF;
  8203. SignedUpperLimitBottom := -2147483648;
  8204. end;
  8205. end;
  8206. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8207. begin
  8208. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8209. LowerLimit := $FFFF;
  8210. SignedLowerLimit := $7FFF;
  8211. SignedLowerLimitBottom := -32768;
  8212. UpperLimit := $FFFFFFFF;
  8213. SignedUpperLimit := $7FFFFFFF;
  8214. SignedUpperLimitBottom := -2147483648;
  8215. MinSize := S_W;
  8216. MaxSize := S_L;
  8217. end;
  8218. {$ifdef x86_64}
  8219. S_LQ:
  8220. begin
  8221. { Both the lower and upper limits are set to 32-bit. If a limit
  8222. is breached, then optimisation is impossible }
  8223. LowerLimit := $FFFFFFFF;
  8224. SignedLowerLimit := $7FFFFFFF;
  8225. SignedLowerLimitBottom := -2147483648;
  8226. UpperLimit := $FFFFFFFF;
  8227. SignedUpperLimit := $7FFFFFFF;
  8228. SignedUpperLimitBottom := -2147483648;
  8229. MinSize := S_L;
  8230. MaxSize := S_L;
  8231. end;
  8232. {$endif x86_64}
  8233. else
  8234. InternalError(2020112301);
  8235. end;
  8236. TestValMin := 0;
  8237. TestValMax := LowerLimit;
  8238. TestValSignedMax := SignedLowerLimit;
  8239. TryShiftDownLimit := LowerLimit;
  8240. TryShiftDown := S_NO;
  8241. ShiftDownOverflow := False;
  8242. RegChanged := False;
  8243. BitwiseOnly := True;
  8244. OrXorUsed := False;
  8245. UpperSignedOverflow := False;
  8246. LowerSignedOverflow := False;
  8247. UpperUnsignedOverflow := False;
  8248. LowerUnsignedOverflow := False;
  8249. hp1 := p;
  8250. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8251. (hp1.typ = ait_instruction) and
  8252. (
  8253. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8254. instruction that doesn't actually contain ThisReg }
  8255. (cs_opt_level3 in current_settings.optimizerswitches) or
  8256. { This allows this Movx optimisation to work through the SETcc instructions
  8257. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8258. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8259. skip over these SETcc instructions). }
  8260. (taicpu(hp1).opcode = A_SETcc) or
  8261. RegInInstruction(ThisReg, hp1)
  8262. ) do
  8263. begin
  8264. case taicpu(hp1).opcode of
  8265. A_INC,A_DEC:
  8266. begin
  8267. { Has to be an exact match on the register }
  8268. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8269. Break;
  8270. if taicpu(hp1).opcode = A_INC then
  8271. begin
  8272. Inc(TestValMin);
  8273. Inc(TestValMax);
  8274. Inc(TestValSignedMax);
  8275. end
  8276. else
  8277. begin
  8278. Dec(TestValMin);
  8279. Dec(TestValMax);
  8280. Dec(TestValSignedMax);
  8281. end;
  8282. end;
  8283. A_TEST, A_CMP:
  8284. begin
  8285. if (
  8286. { Too high a risk of non-linear behaviour that breaks DFA
  8287. here, unless it's cmp $0,%reg, which is equivalent to
  8288. test %reg,%reg }
  8289. OrXorUsed and
  8290. (taicpu(hp1).opcode = A_CMP) and
  8291. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8292. ) or
  8293. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8294. { Has to be an exact match on the register }
  8295. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8296. (
  8297. { Permit "test %reg,%reg" }
  8298. (taicpu(hp1).opcode = A_TEST) and
  8299. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8300. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8301. ) or
  8302. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8303. { Make sure the comparison value is not smaller than the
  8304. smallest allowed signed value for the minimum size (e.g.
  8305. -128 for 8-bit) }
  8306. not (
  8307. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8308. { Is it in the negative range? }
  8309. (
  8310. (taicpu(hp1).oper[0]^.val < 0) and
  8311. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8312. )
  8313. ) then
  8314. Break;
  8315. { Check to see if the active register is used afterwards }
  8316. TransferUsedRegs(TmpUsedRegs);
  8317. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8318. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8319. begin
  8320. { Make sure the comparison or any previous instructions
  8321. hasn't pushed the test values outside of the range of
  8322. MinSize }
  8323. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8324. begin
  8325. { Exceeded lower bound but not upper bound }
  8326. Exit;
  8327. end
  8328. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8329. begin
  8330. { Size didn't exceed lower bound }
  8331. TargetSize := MinSize;
  8332. end
  8333. else
  8334. Break;
  8335. case TargetSize of
  8336. S_B:
  8337. TargetSubReg := R_SUBL;
  8338. S_W:
  8339. TargetSubReg := R_SUBW;
  8340. S_L:
  8341. TargetSubReg := R_SUBD;
  8342. else
  8343. InternalError(2021051002);
  8344. end;
  8345. if TargetSize <> MaxSize then
  8346. begin
  8347. { Update the register to its new size }
  8348. setsubreg(ThisReg, TargetSubReg);
  8349. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8350. taicpu(hp1).oper[1]^.reg := ThisReg;
  8351. taicpu(hp1).opsize := TargetSize;
  8352. { Convert the input MOVZX to a MOV if necessary }
  8353. AdjustInitialLoadAndSize;
  8354. if (InstrMax >= 0) then
  8355. begin
  8356. for Index := 0 to InstrMax do
  8357. begin
  8358. { If p_removed is true, then the original MOV/Z was removed
  8359. and removing the AND instruction may not be safe if it
  8360. appears first }
  8361. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8362. InternalError(2020112311);
  8363. if InstrList[Index].oper[0]^.typ = top_reg then
  8364. InstrList[Index].oper[0]^.reg := ThisReg;
  8365. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8366. InstrList[Index].opsize := MinSize;
  8367. end;
  8368. end;
  8369. Result := True;
  8370. end;
  8371. Exit;
  8372. end;
  8373. end;
  8374. A_SETcc:
  8375. begin
  8376. { This allows this Movx optimisation to work through the SETcc instructions
  8377. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8378. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8379. skip over these SETcc instructions). }
  8380. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8381. { Of course, break out if the current register is used }
  8382. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8383. Break
  8384. else
  8385. { We must use Continue so the instruction doesn't get added
  8386. to InstrList }
  8387. Continue;
  8388. end;
  8389. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8390. begin
  8391. if
  8392. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8393. { Has to be an exact match on the register }
  8394. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8395. (
  8396. (
  8397. (taicpu(hp1).oper[0]^.typ = top_const) and
  8398. (
  8399. (
  8400. (taicpu(hp1).opcode = A_SHL) and
  8401. (
  8402. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8403. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8404. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8405. )
  8406. ) or (
  8407. (taicpu(hp1).opcode <> A_SHL) and
  8408. (
  8409. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8410. { Is it in the negative range? }
  8411. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8412. )
  8413. )
  8414. )
  8415. ) or (
  8416. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8417. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8418. )
  8419. ) then
  8420. Break;
  8421. { Only process OR and XOR if there are only bitwise operations,
  8422. since otherwise they can too easily fool the data flow
  8423. analysis (they can cause non-linear behaviour) }
  8424. case taicpu(hp1).opcode of
  8425. A_ADD:
  8426. begin
  8427. if OrXorUsed then
  8428. { Too high a risk of non-linear behaviour that breaks DFA here }
  8429. Break
  8430. else
  8431. BitwiseOnly := False;
  8432. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8433. begin
  8434. TestValMin := TestValMin * 2;
  8435. TestValMax := TestValMax * 2;
  8436. TestValSignedMax := TestValSignedMax * 2;
  8437. end
  8438. else
  8439. begin
  8440. WorkingValue := taicpu(hp1).oper[0]^.val;
  8441. TestValMin := TestValMin + WorkingValue;
  8442. TestValMax := TestValMax + WorkingValue;
  8443. TestValSignedMax := TestValSignedMax + WorkingValue;
  8444. end;
  8445. end;
  8446. A_SUB:
  8447. begin
  8448. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8449. begin
  8450. TestValMin := 0;
  8451. TestValMax := 0;
  8452. TestValSignedMax := 0;
  8453. end
  8454. else
  8455. begin
  8456. if OrXorUsed then
  8457. { Too high a risk of non-linear behaviour that breaks DFA here }
  8458. Break
  8459. else
  8460. BitwiseOnly := False;
  8461. WorkingValue := taicpu(hp1).oper[0]^.val;
  8462. TestValMin := TestValMin - WorkingValue;
  8463. TestValMax := TestValMax - WorkingValue;
  8464. TestValSignedMax := TestValSignedMax - WorkingValue;
  8465. end;
  8466. end;
  8467. A_AND:
  8468. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8469. begin
  8470. { we might be able to go smaller if AND appears first }
  8471. if InstrMax = -1 then
  8472. case MinSize of
  8473. S_B:
  8474. ;
  8475. S_W:
  8476. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8477. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8478. begin
  8479. TryShiftDown := S_B;
  8480. TryShiftDownLimit := $FF;
  8481. end;
  8482. S_L:
  8483. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8484. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8485. begin
  8486. TryShiftDown := S_B;
  8487. TryShiftDownLimit := $FF;
  8488. end
  8489. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8490. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8491. begin
  8492. TryShiftDown := S_W;
  8493. TryShiftDownLimit := $FFFF;
  8494. end;
  8495. else
  8496. InternalError(2020112320);
  8497. end;
  8498. WorkingValue := taicpu(hp1).oper[0]^.val;
  8499. TestValMin := TestValMin and WorkingValue;
  8500. TestValMax := TestValMax and WorkingValue;
  8501. TestValSignedMax := TestValSignedMax and WorkingValue;
  8502. end;
  8503. A_OR:
  8504. begin
  8505. if not BitwiseOnly then
  8506. Break;
  8507. OrXorUsed := True;
  8508. WorkingValue := taicpu(hp1).oper[0]^.val;
  8509. TestValMin := TestValMin or WorkingValue;
  8510. TestValMax := TestValMax or WorkingValue;
  8511. TestValSignedMax := TestValSignedMax or WorkingValue;
  8512. end;
  8513. A_XOR:
  8514. begin
  8515. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8516. begin
  8517. TestValMin := 0;
  8518. TestValMax := 0;
  8519. TestValSignedMax := 0;
  8520. end
  8521. else
  8522. begin
  8523. if not BitwiseOnly then
  8524. Break;
  8525. OrXorUsed := True;
  8526. WorkingValue := taicpu(hp1).oper[0]^.val;
  8527. TestValMin := TestValMin xor WorkingValue;
  8528. TestValMax := TestValMax xor WorkingValue;
  8529. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8530. end;
  8531. end;
  8532. A_SHL:
  8533. begin
  8534. BitwiseOnly := False;
  8535. WorkingValue := taicpu(hp1).oper[0]^.val;
  8536. TestValMin := TestValMin shl WorkingValue;
  8537. TestValMax := TestValMax shl WorkingValue;
  8538. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8539. end;
  8540. A_SHR,
  8541. { The first instruction was MOVZX, so the value won't be negative }
  8542. A_SAR:
  8543. begin
  8544. if InstrMax <> -1 then
  8545. BitwiseOnly := False
  8546. else
  8547. { we might be able to go smaller if SHR appears first }
  8548. case MinSize of
  8549. S_B:
  8550. ;
  8551. S_W:
  8552. if (taicpu(hp1).oper[0]^.val >= 8) then
  8553. begin
  8554. TryShiftDown := S_B;
  8555. TryShiftDownLimit := $FF;
  8556. TryShiftDownSignedLimit := $7F;
  8557. TryShiftDownSignedLimitLower := -128;
  8558. end;
  8559. S_L:
  8560. if (taicpu(hp1).oper[0]^.val >= 24) then
  8561. begin
  8562. TryShiftDown := S_B;
  8563. TryShiftDownLimit := $FF;
  8564. TryShiftDownSignedLimit := $7F;
  8565. TryShiftDownSignedLimitLower := -128;
  8566. end
  8567. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8568. begin
  8569. TryShiftDown := S_W;
  8570. TryShiftDownLimit := $FFFF;
  8571. TryShiftDownSignedLimit := $7FFF;
  8572. TryShiftDownSignedLimitLower := -32768;
  8573. end;
  8574. else
  8575. InternalError(2020112321);
  8576. end;
  8577. WorkingValue := taicpu(hp1).oper[0]^.val;
  8578. if taicpu(hp1).opcode = A_SAR then
  8579. begin
  8580. TestValMin := SarInt64(TestValMin, WorkingValue);
  8581. TestValMax := SarInt64(TestValMax, WorkingValue);
  8582. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8583. end
  8584. else
  8585. begin
  8586. TestValMin := TestValMin shr WorkingValue;
  8587. TestValMax := TestValMax shr WorkingValue;
  8588. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8589. end;
  8590. end;
  8591. else
  8592. InternalError(2020112303);
  8593. end;
  8594. end;
  8595. (*
  8596. A_IMUL:
  8597. case taicpu(hp1).ops of
  8598. 2:
  8599. begin
  8600. if not MatchOpType(hp1, top_reg, top_reg) or
  8601. { Has to be an exact match on the register }
  8602. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8603. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8604. Break;
  8605. TestValMin := TestValMin * TestValMin;
  8606. TestValMax := TestValMax * TestValMax;
  8607. TestValSignedMax := TestValSignedMax * TestValMax;
  8608. end;
  8609. 3:
  8610. begin
  8611. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8612. { Has to be an exact match on the register }
  8613. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8614. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8615. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8616. { Is it in the negative range? }
  8617. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8618. Break;
  8619. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8620. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8621. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8622. end;
  8623. else
  8624. Break;
  8625. end;
  8626. A_IDIV:
  8627. case taicpu(hp1).ops of
  8628. 3:
  8629. begin
  8630. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8631. { Has to be an exact match on the register }
  8632. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8633. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8634. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8635. { Is it in the negative range? }
  8636. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8637. Break;
  8638. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8639. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8640. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8641. end;
  8642. else
  8643. Break;
  8644. end;
  8645. *)
  8646. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8647. begin
  8648. { If there are no instructions in between, then we might be able to make a saving }
  8649. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8650. Break;
  8651. { We have something like:
  8652. movzbw %dl,%dx
  8653. ...
  8654. movswl %dx,%edx
  8655. Change the latter to a zero-extension then enter the
  8656. A_MOVZX case branch.
  8657. }
  8658. {$ifdef x86_64}
  8659. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8660. begin
  8661. { this becomes a zero extension from 32-bit to 64-bit, but
  8662. the upper 32 bits are already zero, so just delete the
  8663. instruction }
  8664. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8665. RemoveInstruction(hp1);
  8666. Result := True;
  8667. Exit;
  8668. end
  8669. else
  8670. {$endif x86_64}
  8671. begin
  8672. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8673. taicpu(hp1).opcode := A_MOVZX;
  8674. {$ifdef x86_64}
  8675. case taicpu(hp1).opsize of
  8676. S_BQ:
  8677. begin
  8678. taicpu(hp1).opsize := S_BL;
  8679. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8680. end;
  8681. S_WQ:
  8682. begin
  8683. taicpu(hp1).opsize := S_WL;
  8684. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8685. end;
  8686. S_LQ:
  8687. begin
  8688. taicpu(hp1).opcode := A_MOV;
  8689. taicpu(hp1).opsize := S_L;
  8690. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8691. { In this instance, we need to break out because the
  8692. instruction is no longer MOVZX or MOVSXD }
  8693. Result := True;
  8694. Exit;
  8695. end;
  8696. else
  8697. ;
  8698. end;
  8699. {$endif x86_64}
  8700. Result := CompressInstructions;
  8701. Exit;
  8702. end;
  8703. end;
  8704. A_MOVZX:
  8705. begin
  8706. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8707. Break;
  8708. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8709. begin
  8710. if (InstrMax = -1) and
  8711. { Will return false if the second parameter isn't ThisReg
  8712. (can happen on -O2 and under) }
  8713. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8714. begin
  8715. { The two MOVZX instructions are adjacent, so remove the first one }
  8716. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8717. RemoveCurrentP(p);
  8718. Result := True;
  8719. Exit;
  8720. end;
  8721. Break;
  8722. end;
  8723. Result := CompressInstructions;
  8724. Exit;
  8725. end;
  8726. else
  8727. { This includes ADC, SBB and IDIV }
  8728. Break;
  8729. end;
  8730. if not CheckOverflowConditions then
  8731. Break;
  8732. { Contains highest index (so instruction count - 1) }
  8733. Inc(InstrMax);
  8734. if InstrMax > High(InstrList) then
  8735. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8736. InstrList[InstrMax] := taicpu(hp1);
  8737. end;
  8738. end;
  8739. {$pop}
  8740. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8741. var
  8742. hp1 : tai;
  8743. begin
  8744. Result:=false;
  8745. if (taicpu(p).ops >= 2) and
  8746. ((taicpu(p).oper[0]^.typ = top_const) or
  8747. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8748. (taicpu(p).oper[1]^.typ = top_reg) and
  8749. ((taicpu(p).ops = 2) or
  8750. ((taicpu(p).oper[2]^.typ = top_reg) and
  8751. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8752. GetLastInstruction(p,hp1) and
  8753. MatchInstruction(hp1,A_MOV,[]) and
  8754. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8755. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8756. begin
  8757. TransferUsedRegs(TmpUsedRegs);
  8758. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8759. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8760. { change
  8761. mov reg1,reg2
  8762. imul y,reg2 to imul y,reg1,reg2 }
  8763. begin
  8764. taicpu(p).ops := 3;
  8765. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8766. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8767. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8768. RemoveInstruction(hp1);
  8769. result:=true;
  8770. end;
  8771. end;
  8772. end;
  8773. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8774. var
  8775. ThisLabel: TAsmLabel;
  8776. begin
  8777. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8778. ThisLabel.decrefs;
  8779. taicpu(p).opcode := A_RET;
  8780. taicpu(p).is_jmp := false;
  8781. taicpu(p).ops := taicpu(ret_p).ops;
  8782. case taicpu(ret_p).ops of
  8783. 0:
  8784. taicpu(p).clearop(0);
  8785. 1:
  8786. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8787. else
  8788. internalerror(2016041301);
  8789. end;
  8790. { If the original label is now dead, it might turn out that the label
  8791. immediately follows p. As a result, everything beyond it, which will
  8792. be just some final register configuration and a RET instruction, is
  8793. now dead code. [Kit] }
  8794. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8795. running RemoveDeadCodeAfterJump for each RET instruction, because
  8796. this optimisation rarely happens and most RETs appear at the end of
  8797. routines where there is nothing that can be stripped. [Kit] }
  8798. if not ThisLabel.is_used then
  8799. RemoveDeadCodeAfterJump(p);
  8800. end;
  8801. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8802. var
  8803. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8804. Unconditional, PotentialModified: Boolean;
  8805. OperPtr: POper;
  8806. NewRef: TReference;
  8807. InstrList: array of taicpu;
  8808. InstrMax, Index: Integer;
  8809. const
  8810. {$ifdef DEBUG_AOPTCPU}
  8811. SNoFlags: shortstring = ' so the flags aren''t modified';
  8812. {$else DEBUG_AOPTCPU}
  8813. SNoFlags = '';
  8814. {$endif DEBUG_AOPTCPU}
  8815. begin
  8816. Result:=false;
  8817. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8818. begin
  8819. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8820. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8821. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8822. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8823. GetNextInstruction(hp1, hp2) and
  8824. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8825. { Change from: To:
  8826. set(C) %reg j(~C) label
  8827. test %reg,%reg/cmp $0,%reg
  8828. je label
  8829. set(C) %reg j(C) label
  8830. test %reg,%reg/cmp $0,%reg
  8831. jne label
  8832. (Also do something similar with sete/setne instead of je/jne)
  8833. }
  8834. begin
  8835. { Before we do anything else, we need to check the instructions
  8836. in between SETcc and TEST to make sure they don't modify the
  8837. FLAGS register - if -O2 or under, there won't be any
  8838. instructions between SET and TEST }
  8839. TransferUsedRegs(TmpUsedRegs);
  8840. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8841. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8842. begin
  8843. next := p;
  8844. SetLength(InstrList, 0);
  8845. InstrMax := -1;
  8846. PotentialModified := False;
  8847. { Make a note of every instruction that modifies the FLAGS
  8848. register }
  8849. while GetNextInstruction(next, next) and (next <> hp1) do
  8850. begin
  8851. if next.typ <> ait_instruction then
  8852. { GetNextInstructionUsingReg should have returned False }
  8853. InternalError(2021051701);
  8854. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8855. begin
  8856. case taicpu(next).opcode of
  8857. A_SETcc,
  8858. A_CMOVcc,
  8859. A_Jcc:
  8860. begin
  8861. if PotentialModified then
  8862. { Not safe because the flags were modified earlier }
  8863. Exit
  8864. else
  8865. { Condition is the same as the initial SETcc, so this is safe
  8866. (don't add to instruction list though) }
  8867. Continue;
  8868. end;
  8869. A_ADD:
  8870. begin
  8871. if (taicpu(next).opsize = S_B) or
  8872. { LEA doesn't support 8-bit operands }
  8873. (taicpu(next).oper[1]^.typ <> top_reg) or
  8874. { Must write to a register }
  8875. (taicpu(next).oper[0]^.typ = top_ref) then
  8876. { Require a constant or a register }
  8877. Exit;
  8878. PotentialModified := True;
  8879. end;
  8880. A_SUB:
  8881. begin
  8882. if (taicpu(next).opsize = S_B) or
  8883. { LEA doesn't support 8-bit operands }
  8884. (taicpu(next).oper[1]^.typ <> top_reg) or
  8885. { Must write to a register }
  8886. (taicpu(next).oper[0]^.typ <> top_const) or
  8887. (taicpu(next).oper[0]^.val = $80000000) then
  8888. { Can't subtract a register with LEA - also
  8889. check that the value isn't -2^31, as this
  8890. can't be negated }
  8891. Exit;
  8892. PotentialModified := True;
  8893. end;
  8894. A_SAL,
  8895. A_SHL:
  8896. begin
  8897. if (taicpu(next).opsize = S_B) or
  8898. { LEA doesn't support 8-bit operands }
  8899. (taicpu(next).oper[1]^.typ <> top_reg) or
  8900. { Must write to a register }
  8901. (taicpu(next).oper[0]^.typ <> top_const) or
  8902. (taicpu(next).oper[0]^.val < 0) or
  8903. (taicpu(next).oper[0]^.val > 3) then
  8904. Exit;
  8905. PotentialModified := True;
  8906. end;
  8907. A_IMUL:
  8908. begin
  8909. if (taicpu(next).ops <> 3) or
  8910. (taicpu(next).oper[1]^.typ <> top_reg) or
  8911. { Must write to a register }
  8912. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8913. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8914. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8915. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8916. Exit
  8917. else
  8918. PotentialModified := True;
  8919. end;
  8920. else
  8921. { Don't know how to change this, so abort }
  8922. Exit;
  8923. end;
  8924. { Contains highest index (so instruction count - 1) }
  8925. Inc(InstrMax);
  8926. if InstrMax > High(InstrList) then
  8927. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8928. InstrList[InstrMax] := taicpu(next);
  8929. end;
  8930. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8931. end;
  8932. if not Assigned(next) or (next <> hp1) then
  8933. { It should be equal to hp1 }
  8934. InternalError(2021051702);
  8935. { Cycle through each instruction and check to see if we can
  8936. change them to versions that don't modify the flags }
  8937. if (InstrMax >= 0) then
  8938. begin
  8939. for Index := 0 to InstrMax do
  8940. case InstrList[Index].opcode of
  8941. A_ADD:
  8942. begin
  8943. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8944. InstrList[Index].opcode := A_LEA;
  8945. reference_reset(NewRef, 1, []);
  8946. NewRef.base := InstrList[Index].oper[1]^.reg;
  8947. if InstrList[Index].oper[0]^.typ = top_reg then
  8948. begin
  8949. NewRef.index := InstrList[Index].oper[0]^.reg;
  8950. NewRef.scalefactor := 1;
  8951. end
  8952. else
  8953. NewRef.offset := InstrList[Index].oper[0]^.val;
  8954. InstrList[Index].loadref(0, NewRef);
  8955. end;
  8956. A_SUB:
  8957. begin
  8958. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8959. InstrList[Index].opcode := A_LEA;
  8960. reference_reset(NewRef, 1, []);
  8961. NewRef.base := InstrList[Index].oper[1]^.reg;
  8962. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8963. InstrList[Index].loadref(0, NewRef);
  8964. end;
  8965. A_SHL,
  8966. A_SAL:
  8967. begin
  8968. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8969. InstrList[Index].opcode := A_LEA;
  8970. reference_reset(NewRef, 1, []);
  8971. NewRef.index := InstrList[Index].oper[1]^.reg;
  8972. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8973. InstrList[Index].loadref(0, NewRef);
  8974. end;
  8975. A_IMUL:
  8976. begin
  8977. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8978. InstrList[Index].opcode := A_LEA;
  8979. reference_reset(NewRef, 1, []);
  8980. NewRef.index := InstrList[Index].oper[1]^.reg;
  8981. case InstrList[Index].oper[0]^.val of
  8982. 2, 4, 8:
  8983. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8984. else {3, 5 and 9}
  8985. begin
  8986. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8987. NewRef.base := InstrList[Index].oper[1]^.reg;
  8988. end;
  8989. end;
  8990. InstrList[Index].loadref(0, NewRef);
  8991. end;
  8992. else
  8993. InternalError(2021051710);
  8994. end;
  8995. end;
  8996. { Mark the FLAGS register as used across this whole block }
  8997. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8998. end;
  8999. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9000. JumpC := taicpu(hp2).condition;
  9001. Unconditional := False;
  9002. if conditions_equal(JumpC, C_E) then
  9003. SetC := inverse_cond(taicpu(p).condition)
  9004. else if conditions_equal(JumpC, C_NE) then
  9005. SetC := taicpu(p).condition
  9006. else
  9007. { We've got something weird here (and inefficent) }
  9008. begin
  9009. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9010. SetC := C_NONE;
  9011. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9012. if condition_in(C_AE, JumpC) then
  9013. Unconditional := True
  9014. else
  9015. { Not sure what to do with this jump - drop out }
  9016. Exit;
  9017. end;
  9018. RemoveInstruction(hp1);
  9019. if Unconditional then
  9020. MakeUnconditional(taicpu(hp2))
  9021. else
  9022. begin
  9023. if SetC = C_NONE then
  9024. InternalError(2018061402);
  9025. taicpu(hp2).SetCondition(SetC);
  9026. end;
  9027. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9028. TmpUsedRegs }
  9029. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9030. begin
  9031. RemoveCurrentp(p, hp2);
  9032. if taicpu(hp2).opcode = A_SETcc then
  9033. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9034. else
  9035. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9036. end
  9037. else
  9038. if taicpu(hp2).opcode = A_SETcc then
  9039. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9040. else
  9041. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9042. Result := True;
  9043. end
  9044. else if
  9045. { Make sure the instructions are adjacent }
  9046. (
  9047. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9048. GetNextInstruction(p, hp1)
  9049. ) and
  9050. MatchInstruction(hp1, A_MOV, [S_B]) and
  9051. { Writing to memory is allowed }
  9052. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9053. begin
  9054. {
  9055. Watch out for sequences such as:
  9056. set(c)b %regb
  9057. movb %regb,(ref)
  9058. movb $0,1(ref)
  9059. movb $0,2(ref)
  9060. movb $0,3(ref)
  9061. Much more efficient to turn it into:
  9062. movl $0,%regl
  9063. set(c)b %regb
  9064. movl %regl,(ref)
  9065. Or:
  9066. set(c)b %regb
  9067. movzbl %regb,%regl
  9068. movl %regl,(ref)
  9069. }
  9070. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9071. GetNextInstruction(hp1, hp2) and
  9072. MatchInstruction(hp2, A_MOV, [S_B]) and
  9073. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9074. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9075. begin
  9076. { Don't do anything else except set Result to True }
  9077. end
  9078. else
  9079. begin
  9080. if taicpu(p).oper[0]^.typ = top_reg then
  9081. begin
  9082. TransferUsedRegs(TmpUsedRegs);
  9083. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9084. end;
  9085. { If it's not a register, it's a memory address }
  9086. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9087. begin
  9088. { Even if the register is still in use, we can minimise the
  9089. pipeline stall by changing the MOV into another SETcc. }
  9090. taicpu(hp1).opcode := A_SETcc;
  9091. taicpu(hp1).condition := taicpu(p).condition;
  9092. if taicpu(hp1).oper[1]^.typ = top_ref then
  9093. begin
  9094. { Swapping the operand pointers like this is probably a
  9095. bit naughty, but it is far faster than using loadoper
  9096. to transfer the reference from oper[1] to oper[0] if
  9097. you take into account the extra procedure calls and
  9098. the memory allocation and deallocation required }
  9099. OperPtr := taicpu(hp1).oper[1];
  9100. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9101. taicpu(hp1).oper[0] := OperPtr;
  9102. end
  9103. else
  9104. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9105. taicpu(hp1).clearop(1);
  9106. taicpu(hp1).ops := 1;
  9107. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9108. end
  9109. else
  9110. begin
  9111. if taicpu(hp1).oper[1]^.typ = top_reg then
  9112. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9113. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9114. RemoveInstruction(hp1);
  9115. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9116. end
  9117. end;
  9118. Result := True;
  9119. end;
  9120. end;
  9121. end;
  9122. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9123. var
  9124. hp1: tai;
  9125. Count: Integer;
  9126. OrigLabel: TAsmLabel;
  9127. begin
  9128. result := False;
  9129. { Sometimes, the optimisations below can permit this }
  9130. RemoveDeadCodeAfterJump(p);
  9131. 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
  9132. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9133. begin
  9134. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9135. { Also a side-effect of optimisations }
  9136. if CollapseZeroDistJump(p, OrigLabel) then
  9137. begin
  9138. Result := True;
  9139. Exit;
  9140. end;
  9141. hp1 := GetLabelWithSym(OrigLabel);
  9142. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9143. begin
  9144. case taicpu(hp1).opcode of
  9145. A_RET:
  9146. {
  9147. change
  9148. jmp .L1
  9149. ...
  9150. .L1:
  9151. ret
  9152. into
  9153. ret
  9154. }
  9155. begin
  9156. ConvertJumpToRET(p, hp1);
  9157. result:=true;
  9158. end;
  9159. { Check any kind of direct assignment instruction }
  9160. A_MOV,
  9161. A_MOVD,
  9162. A_MOVQ,
  9163. A_MOVSX,
  9164. {$ifdef x86_64}
  9165. A_MOVSXD,
  9166. {$endif x86_64}
  9167. A_MOVZX,
  9168. A_MOVAPS,
  9169. A_MOVUPS,
  9170. A_MOVSD,
  9171. A_MOVAPD,
  9172. A_MOVUPD,
  9173. A_MOVDQA,
  9174. A_MOVDQU,
  9175. A_VMOVSS,
  9176. A_VMOVAPS,
  9177. A_VMOVUPS,
  9178. A_VMOVSD,
  9179. A_VMOVAPD,
  9180. A_VMOVUPD,
  9181. A_VMOVDQA,
  9182. A_VMOVDQU:
  9183. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9184. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9185. begin
  9186. Result := True;
  9187. Exit;
  9188. end;
  9189. else
  9190. ;
  9191. end;
  9192. end;
  9193. end;
  9194. end;
  9195. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9196. begin
  9197. CanBeCMOV:=assigned(p) and
  9198. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9199. { we can't use cmov ref,reg because
  9200. ref could be nil and cmov still throws an exception
  9201. if ref=nil but the mov isn't done (FK)
  9202. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9203. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9204. }
  9205. (taicpu(p).oper[1]^.typ = top_reg) and
  9206. (
  9207. (taicpu(p).oper[0]^.typ = top_reg) or
  9208. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9209. it is not expected that this can cause a seg. violation }
  9210. (
  9211. (taicpu(p).oper[0]^.typ = top_ref) and
  9212. IsRefSafe(taicpu(p).oper[0]^.ref)
  9213. )
  9214. );
  9215. end;
  9216. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9217. var
  9218. hp1,hp2: tai;
  9219. {$ifndef i8086}
  9220. hp3,hp4,hpmov2, hp5: tai;
  9221. l : Longint;
  9222. condition : TAsmCond;
  9223. {$endif i8086}
  9224. carryadd_opcode : TAsmOp;
  9225. symbol: TAsmSymbol;
  9226. increg, tmpreg: TRegister;
  9227. begin
  9228. result:=false;
  9229. if GetNextInstruction(p,hp1) then
  9230. begin
  9231. if (hp1.typ=ait_label) then
  9232. begin
  9233. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9234. Exit;
  9235. end
  9236. else if (hp1.typ<>ait_instruction) then
  9237. Exit;
  9238. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9239. if (
  9240. (
  9241. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9242. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9243. (Taicpu(hp1).oper[0]^.val=1)
  9244. ) or
  9245. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9246. ) and
  9247. GetNextInstruction(hp1,hp2) and
  9248. SkipAligns(hp2, hp2) and
  9249. (hp2.typ = ait_label) and
  9250. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9251. { jb @@1 cmc
  9252. inc/dec operand --> adc/sbb operand,0
  9253. @@1:
  9254. ... and ...
  9255. jnb @@1
  9256. inc/dec operand --> adc/sbb operand,0
  9257. @@1: }
  9258. begin
  9259. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9260. begin
  9261. case taicpu(hp1).opcode of
  9262. A_INC,
  9263. A_ADD:
  9264. carryadd_opcode:=A_ADC;
  9265. A_DEC,
  9266. A_SUB:
  9267. carryadd_opcode:=A_SBB;
  9268. else
  9269. InternalError(2021011001);
  9270. end;
  9271. Taicpu(p).clearop(0);
  9272. Taicpu(p).ops:=0;
  9273. Taicpu(p).is_jmp:=false;
  9274. Taicpu(p).opcode:=A_CMC;
  9275. Taicpu(p).condition:=C_NONE;
  9276. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9277. Taicpu(hp1).ops:=2;
  9278. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9279. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9280. else
  9281. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9282. Taicpu(hp1).loadconst(0,0);
  9283. Taicpu(hp1).opcode:=carryadd_opcode;
  9284. result:=true;
  9285. exit;
  9286. end
  9287. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9288. begin
  9289. case taicpu(hp1).opcode of
  9290. A_INC,
  9291. A_ADD:
  9292. carryadd_opcode:=A_ADC;
  9293. A_DEC,
  9294. A_SUB:
  9295. carryadd_opcode:=A_SBB;
  9296. else
  9297. InternalError(2021011002);
  9298. end;
  9299. Taicpu(hp1).ops:=2;
  9300. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9301. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9302. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9303. else
  9304. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9305. Taicpu(hp1).loadconst(0,0);
  9306. Taicpu(hp1).opcode:=carryadd_opcode;
  9307. RemoveCurrentP(p, hp1);
  9308. result:=true;
  9309. exit;
  9310. end
  9311. {
  9312. jcc @@1 setcc tmpreg
  9313. inc/dec/add/sub operand -> (movzx tmpreg)
  9314. @@1: add/sub tmpreg,operand
  9315. While this increases code size slightly, it makes the code much faster if the
  9316. jump is unpredictable
  9317. }
  9318. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9319. begin
  9320. { search for an available register which is volatile }
  9321. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9322. if increg <> NR_NO then
  9323. begin
  9324. { We don't need to check if tmpreg is in hp1 or not, because
  9325. it will be marked as in use at p (if not, this is
  9326. indictive of a compiler bug). }
  9327. TAsmLabel(symbol).decrefs;
  9328. Taicpu(p).clearop(0);
  9329. Taicpu(p).ops:=1;
  9330. Taicpu(p).is_jmp:=false;
  9331. Taicpu(p).opcode:=A_SETcc;
  9332. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9333. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9334. Taicpu(p).loadreg(0,increg);
  9335. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9336. begin
  9337. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9338. R_SUBW:
  9339. begin
  9340. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9341. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9342. end;
  9343. R_SUBD:
  9344. begin
  9345. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9346. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9347. end;
  9348. {$ifdef x86_64}
  9349. R_SUBQ:
  9350. begin
  9351. { MOVZX doesn't have a 64-bit variant, because
  9352. the 32-bit version implicitly zeroes the
  9353. upper 32-bits of the destination register }
  9354. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9355. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9356. setsubreg(tmpreg, R_SUBQ);
  9357. end;
  9358. {$endif x86_64}
  9359. else
  9360. Internalerror(2020030601);
  9361. end;
  9362. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9363. asml.InsertAfter(hp2,p);
  9364. end
  9365. else
  9366. tmpreg := increg;
  9367. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9368. begin
  9369. Taicpu(hp1).ops:=2;
  9370. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9371. end;
  9372. Taicpu(hp1).loadreg(0,tmpreg);
  9373. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9374. Result := True;
  9375. { p is no longer a Jcc instruction, so exit }
  9376. Exit;
  9377. end;
  9378. end;
  9379. end;
  9380. { Detect the following:
  9381. jmp<cond> @Lbl1
  9382. jmp @Lbl2
  9383. ...
  9384. @Lbl1:
  9385. ret
  9386. Change to:
  9387. jmp<inv_cond> @Lbl2
  9388. ret
  9389. }
  9390. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9391. begin
  9392. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9393. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9394. MatchInstruction(hp2,A_RET,[S_NO]) then
  9395. begin
  9396. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9397. { Change label address to that of the unconditional jump }
  9398. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9399. TAsmLabel(symbol).DecRefs;
  9400. taicpu(hp1).opcode := A_RET;
  9401. taicpu(hp1).is_jmp := false;
  9402. taicpu(hp1).ops := taicpu(hp2).ops;
  9403. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9404. case taicpu(hp2).ops of
  9405. 0:
  9406. taicpu(hp1).clearop(0);
  9407. 1:
  9408. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9409. else
  9410. internalerror(2016041302);
  9411. end;
  9412. end;
  9413. {$ifndef i8086}
  9414. end
  9415. {
  9416. convert
  9417. j<c> .L1
  9418. mov 1,reg
  9419. jmp .L2
  9420. .L1
  9421. mov 0,reg
  9422. .L2
  9423. into
  9424. mov 0,reg
  9425. set<not(c)> reg
  9426. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9427. would destroy the flag contents
  9428. }
  9429. else if MatchInstruction(hp1,A_MOV,[]) and
  9430. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9431. {$ifdef i386}
  9432. (
  9433. { Under i386, ESI, EDI, EBP and ESP
  9434. don't have an 8-bit representation }
  9435. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9436. ) and
  9437. {$endif i386}
  9438. (taicpu(hp1).oper[0]^.val=1) and
  9439. GetNextInstruction(hp1,hp2) and
  9440. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9441. GetNextInstruction(hp2,hp3) and
  9442. { skip align }
  9443. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9444. (hp3.typ=ait_label) and
  9445. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9446. (tai_label(hp3).labsym.getrefs=1) and
  9447. GetNextInstruction(hp3,hp4) and
  9448. MatchInstruction(hp4,A_MOV,[]) and
  9449. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9450. (taicpu(hp4).oper[0]^.val=0) and
  9451. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9452. GetNextInstruction(hp4,hp5) and
  9453. (hp5.typ=ait_label) and
  9454. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9455. (tai_label(hp5).labsym.getrefs=1) then
  9456. begin
  9457. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9458. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9459. { remove last label }
  9460. RemoveInstruction(hp5);
  9461. { remove second label }
  9462. RemoveInstruction(hp3);
  9463. { if align is present remove it }
  9464. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9465. RemoveInstruction(hp3);
  9466. { remove jmp }
  9467. RemoveInstruction(hp2);
  9468. if taicpu(hp1).opsize=S_B then
  9469. RemoveInstruction(hp1)
  9470. else
  9471. taicpu(hp1).loadconst(0,0);
  9472. taicpu(hp4).opcode:=A_SETcc;
  9473. taicpu(hp4).opsize:=S_B;
  9474. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9475. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9476. taicpu(hp4).opercnt:=1;
  9477. taicpu(hp4).ops:=1;
  9478. taicpu(hp4).freeop(1);
  9479. RemoveCurrentP(p);
  9480. Result:=true;
  9481. exit;
  9482. end
  9483. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9484. begin
  9485. { check for
  9486. jCC xxx
  9487. <several movs>
  9488. xxx:
  9489. Also spot:
  9490. Jcc xxx
  9491. <several movs>
  9492. jmp xxx
  9493. Change to:
  9494. <several cmovs with inverted condition>
  9495. jmp xxx
  9496. }
  9497. l:=0;
  9498. while assigned(hp1) and
  9499. CanBeCMOV(hp1) and
  9500. { stop on labels }
  9501. not(hp1.typ=ait_label) do
  9502. begin
  9503. inc(l);
  9504. hp5 := hp1;
  9505. GetNextInstruction(hp1,hp1);
  9506. end;
  9507. if assigned(hp1) then
  9508. begin
  9509. TransferUsedRegs(TmpUsedRegs);
  9510. if (
  9511. MatchInstruction(hp1, A_JMP, []) and
  9512. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9513. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9514. ) or
  9515. FindLabel(tasmlabel(symbol),hp1) then
  9516. begin
  9517. if (l<=4) and (l>0) then
  9518. begin
  9519. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9520. condition:=inverse_cond(taicpu(p).condition);
  9521. UpdateUsedRegs(tai(p.next));
  9522. GetNextInstruction(p,hp1);
  9523. repeat
  9524. if not Assigned(hp1) then
  9525. InternalError(2018062900);
  9526. taicpu(hp1).opcode:=A_CMOVcc;
  9527. taicpu(hp1).condition:=condition;
  9528. UpdateUsedRegs(tai(hp1.next));
  9529. GetNextInstruction(hp1,hp1);
  9530. until not(CanBeCMOV(hp1));
  9531. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9532. hp2 := hp1;
  9533. repeat
  9534. if not Assigned(hp2) then
  9535. InternalError(2018062910);
  9536. case hp2.typ of
  9537. ait_label:
  9538. { What we expected - break out of the loop (it won't be a dead label at the top of
  9539. a cluster because that was optimised at an earlier stage) }
  9540. Break;
  9541. ait_align:
  9542. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9543. begin
  9544. hp2 := tai(hp2.Next);
  9545. Continue;
  9546. end;
  9547. ait_instruction:
  9548. begin
  9549. if taicpu(hp2).opcode<>A_JMP then
  9550. InternalError(2018062912);
  9551. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9552. Break;
  9553. end
  9554. else
  9555. begin
  9556. { Might be a comment or temporary allocation entry }
  9557. if not (hp2.typ in SkipInstr) then
  9558. InternalError(2018062911);
  9559. hp2 := tai(hp2.Next);
  9560. Continue;
  9561. end;
  9562. end;
  9563. until False;
  9564. { Now we can safely decrement the reference count }
  9565. tasmlabel(symbol).decrefs;
  9566. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9567. { Remove the original jump }
  9568. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9569. if hp2.typ=ait_instruction then
  9570. begin
  9571. p:=hp2;
  9572. Result:=True;
  9573. end
  9574. else
  9575. begin
  9576. UpdateUsedRegs(tai(hp2.next));
  9577. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9578. { Remove the label if this is its final reference }
  9579. if (tasmlabel(symbol).getrefs=0) then
  9580. StripLabelFast(hp1);
  9581. end;
  9582. exit;
  9583. end;
  9584. end
  9585. else
  9586. begin
  9587. { check further for
  9588. jCC xxx
  9589. <several movs 1>
  9590. jmp yyy
  9591. xxx:
  9592. <several movs 2>
  9593. yyy:
  9594. }
  9595. { hp2 points to jmp yyy }
  9596. hp2:=hp1;
  9597. { skip hp1 to xxx (or an align right before it) }
  9598. GetNextInstruction(hp1, hp1);
  9599. if assigned(hp2) and
  9600. assigned(hp1) and
  9601. (l<=3) and
  9602. (hp2.typ=ait_instruction) and
  9603. (taicpu(hp2).is_jmp) and
  9604. (taicpu(hp2).condition=C_None) and
  9605. { real label and jump, no further references to the
  9606. label are allowed }
  9607. (tasmlabel(symbol).getrefs=1) and
  9608. FindLabel(tasmlabel(symbol),hp1) then
  9609. begin
  9610. l:=0;
  9611. { skip hp1 to <several moves 2> }
  9612. if (hp1.typ = ait_align) then
  9613. GetNextInstruction(hp1, hp1);
  9614. GetNextInstruction(hp1, hpmov2);
  9615. hp1 := hpmov2;
  9616. while assigned(hp1) and
  9617. CanBeCMOV(hp1) do
  9618. begin
  9619. inc(l);
  9620. hp5 := hp1;
  9621. GetNextInstruction(hp1, hp1);
  9622. end;
  9623. { hp1 points to yyy (or an align right before it) }
  9624. hp3 := hp1;
  9625. if assigned(hp1) and
  9626. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9627. begin
  9628. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9629. condition:=inverse_cond(taicpu(p).condition);
  9630. UpdateUsedRegs(tai(p.next));
  9631. GetNextInstruction(p,hp1);
  9632. repeat
  9633. taicpu(hp1).opcode:=A_CMOVcc;
  9634. taicpu(hp1).condition:=condition;
  9635. UpdateUsedRegs(tai(hp1.next));
  9636. GetNextInstruction(hp1,hp1);
  9637. until not(assigned(hp1)) or
  9638. not(CanBeCMOV(hp1));
  9639. condition:=inverse_cond(condition);
  9640. if GetLastInstruction(hpmov2,hp1) then
  9641. UpdateUsedRegs(tai(hp1.next));
  9642. hp1 := hpmov2;
  9643. { hp1 is now at <several movs 2> }
  9644. while Assigned(hp1) and CanBeCMOV(hp1) do
  9645. begin
  9646. taicpu(hp1).opcode:=A_CMOVcc;
  9647. taicpu(hp1).condition:=condition;
  9648. UpdateUsedRegs(tai(hp1.next));
  9649. GetNextInstruction(hp1,hp1);
  9650. end;
  9651. hp1 := p;
  9652. { Get first instruction after label }
  9653. UpdateUsedRegs(tai(hp3.next));
  9654. GetNextInstruction(hp3, p);
  9655. if assigned(p) and (hp3.typ = ait_align) then
  9656. GetNextInstruction(p, p);
  9657. { Don't dereference yet, as doing so will cause
  9658. GetNextInstruction to skip the label and
  9659. optional align marker. [Kit] }
  9660. GetNextInstruction(hp2, hp4);
  9661. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9662. { remove jCC }
  9663. RemoveInstruction(hp1);
  9664. { Now we can safely decrement it }
  9665. tasmlabel(symbol).decrefs;
  9666. { Remove label xxx (it will have a ref of zero due to the initial check }
  9667. StripLabelFast(hp4);
  9668. { remove jmp }
  9669. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9670. RemoveInstruction(hp2);
  9671. { As before, now we can safely decrement it }
  9672. tasmlabel(symbol).decrefs;
  9673. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9674. if tasmlabel(symbol).getrefs = 0 then
  9675. StripLabelFast(hp3);
  9676. if Assigned(p) then
  9677. result:=true;
  9678. exit;
  9679. end;
  9680. end;
  9681. end;
  9682. end;
  9683. {$endif i8086}
  9684. end;
  9685. end;
  9686. end;
  9687. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9688. var
  9689. hp1,hp2,hp3: tai;
  9690. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9691. NewSize: TOpSize;
  9692. NewRegSize: TSubRegister;
  9693. Limit: TCgInt;
  9694. SwapOper: POper;
  9695. begin
  9696. result:=false;
  9697. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9698. GetNextInstruction(p,hp1) and
  9699. (hp1.typ = ait_instruction);
  9700. if reg_and_hp1_is_instr and
  9701. (
  9702. (taicpu(hp1).opcode <> A_LEA) or
  9703. { If the LEA instruction can be converted into an arithmetic instruction,
  9704. it may be possible to then fold it. }
  9705. (
  9706. { If the flags register is in use, don't change the instruction
  9707. to an ADD otherwise this will scramble the flags. [Kit] }
  9708. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9709. ConvertLEA(taicpu(hp1))
  9710. )
  9711. ) and
  9712. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9713. GetNextInstruction(hp1,hp2) and
  9714. MatchInstruction(hp2,A_MOV,[]) and
  9715. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9716. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9717. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9718. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9719. {$ifdef i386}
  9720. { not all registers have byte size sub registers on i386 }
  9721. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9722. {$endif i386}
  9723. (((taicpu(hp1).ops=2) and
  9724. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9725. ((taicpu(hp1).ops=1) and
  9726. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9727. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9728. begin
  9729. { change movsX/movzX reg/ref, reg2
  9730. add/sub/or/... reg3/$const, reg2
  9731. mov reg2 reg/ref
  9732. to add/sub/or/... reg3/$const, reg/ref }
  9733. { by example:
  9734. movswl %si,%eax movswl %si,%eax p
  9735. decl %eax addl %edx,%eax hp1
  9736. movw %ax,%si movw %ax,%si hp2
  9737. ->
  9738. movswl %si,%eax movswl %si,%eax p
  9739. decw %eax addw %edx,%eax hp1
  9740. movw %ax,%si movw %ax,%si hp2
  9741. }
  9742. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9743. {
  9744. ->
  9745. movswl %si,%eax movswl %si,%eax p
  9746. decw %si addw %dx,%si hp1
  9747. movw %ax,%si movw %ax,%si hp2
  9748. }
  9749. case taicpu(hp1).ops of
  9750. 1:
  9751. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9752. 2:
  9753. begin
  9754. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9755. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9756. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9757. end;
  9758. else
  9759. internalerror(2008042702);
  9760. end;
  9761. {
  9762. ->
  9763. decw %si addw %dx,%si p
  9764. }
  9765. DebugMsg(SPeepholeOptimization + 'var3',p);
  9766. RemoveCurrentP(p, hp1);
  9767. RemoveInstruction(hp2);
  9768. Result := True;
  9769. Exit;
  9770. end;
  9771. if reg_and_hp1_is_instr and
  9772. (taicpu(hp1).opcode = A_MOV) and
  9773. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9774. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9775. {$ifdef x86_64}
  9776. { check for implicit extension to 64 bit }
  9777. or
  9778. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9779. (taicpu(hp1).opsize=S_Q) and
  9780. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9781. )
  9782. {$endif x86_64}
  9783. )
  9784. then
  9785. begin
  9786. { change
  9787. movx %reg1,%reg2
  9788. mov %reg2,%reg3
  9789. dealloc %reg2
  9790. into
  9791. movx %reg,%reg3
  9792. }
  9793. TransferUsedRegs(TmpUsedRegs);
  9794. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9795. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9796. begin
  9797. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9798. {$ifdef x86_64}
  9799. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9800. (taicpu(hp1).opsize=S_Q) then
  9801. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9802. else
  9803. {$endif x86_64}
  9804. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9805. RemoveInstruction(hp1);
  9806. Result := True;
  9807. Exit;
  9808. end;
  9809. end;
  9810. if reg_and_hp1_is_instr and
  9811. ((taicpu(hp1).opcode=A_MOV) or
  9812. (taicpu(hp1).opcode=A_ADD) or
  9813. (taicpu(hp1).opcode=A_SUB) or
  9814. (taicpu(hp1).opcode=A_CMP) or
  9815. (taicpu(hp1).opcode=A_OR) or
  9816. (taicpu(hp1).opcode=A_XOR) or
  9817. (taicpu(hp1).opcode=A_AND)
  9818. ) and
  9819. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9820. begin
  9821. AndTest := (taicpu(hp1).opcode=A_AND) and
  9822. GetNextInstruction(hp1, hp2) and
  9823. (hp2.typ = ait_instruction) and
  9824. (
  9825. (
  9826. (taicpu(hp2).opcode=A_TEST) and
  9827. (
  9828. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9829. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9830. (
  9831. { If the AND and TEST instructions share a constant, this is also valid }
  9832. (taicpu(hp1).oper[0]^.typ = top_const) and
  9833. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9834. )
  9835. ) and
  9836. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9837. ) or
  9838. (
  9839. (taicpu(hp2).opcode=A_CMP) and
  9840. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9841. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9842. )
  9843. );
  9844. { change
  9845. movx (oper),%reg2
  9846. and $x,%reg2
  9847. test %reg2,%reg2
  9848. dealloc %reg2
  9849. into
  9850. op %reg1,%reg3
  9851. if the second op accesses only the bits stored in reg1
  9852. }
  9853. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9854. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9855. (taicpu(hp1).oper[0]^.typ = top_const) and
  9856. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9857. AndTest then
  9858. begin
  9859. { Check if the AND constant is in range }
  9860. case taicpu(p).opsize of
  9861. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9862. begin
  9863. NewSize := S_B;
  9864. Limit := $FF;
  9865. end;
  9866. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9867. begin
  9868. NewSize := S_W;
  9869. Limit := $FFFF;
  9870. end;
  9871. {$ifdef x86_64}
  9872. S_LQ:
  9873. begin
  9874. NewSize := S_L;
  9875. Limit := $FFFFFFFF;
  9876. end;
  9877. {$endif x86_64}
  9878. else
  9879. InternalError(2021120303);
  9880. end;
  9881. if (
  9882. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9883. { Check for negative operands }
  9884. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9885. ) and
  9886. GetNextInstruction(hp2,hp3) and
  9887. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9888. (taicpu(hp3).condition in [C_E,C_NE]) then
  9889. begin
  9890. TransferUsedRegs(TmpUsedRegs);
  9891. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9892. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9893. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9894. begin
  9895. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9896. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9897. taicpu(hp1).opcode := A_TEST;
  9898. taicpu(hp1).opsize := NewSize;
  9899. RemoveInstruction(hp2);
  9900. RemoveCurrentP(p, hp1);
  9901. Result:=true;
  9902. exit;
  9903. end;
  9904. end;
  9905. end;
  9906. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9907. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9908. (taicpu(hp1).opsize=S_B)) or
  9909. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9910. (taicpu(hp1).opsize=S_W))
  9911. {$ifdef x86_64}
  9912. or ((taicpu(p).opsize=S_LQ) and
  9913. (taicpu(hp1).opsize=S_L))
  9914. {$endif x86_64}
  9915. ) and
  9916. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9917. begin
  9918. { change
  9919. movx %reg1,%reg2
  9920. op %reg2,%reg3
  9921. dealloc %reg2
  9922. into
  9923. op %reg1,%reg3
  9924. if the second op accesses only the bits stored in reg1
  9925. }
  9926. TransferUsedRegs(TmpUsedRegs);
  9927. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9928. if AndTest then
  9929. begin
  9930. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9931. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9932. end
  9933. else
  9934. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9935. if not RegUsed then
  9936. begin
  9937. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9938. if taicpu(p).oper[0]^.typ=top_reg then
  9939. begin
  9940. case taicpu(hp1).opsize of
  9941. S_B:
  9942. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9943. S_W:
  9944. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9945. S_L:
  9946. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9947. else
  9948. Internalerror(2020102301);
  9949. end;
  9950. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9951. end
  9952. else
  9953. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9954. RemoveCurrentP(p);
  9955. if AndTest then
  9956. RemoveInstruction(hp2);
  9957. result:=true;
  9958. exit;
  9959. end;
  9960. end
  9961. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9962. (
  9963. { Bitwise operations only }
  9964. (taicpu(hp1).opcode=A_AND) or
  9965. (taicpu(hp1).opcode=A_TEST) or
  9966. (
  9967. (taicpu(hp1).oper[0]^.typ = top_const) and
  9968. (
  9969. (taicpu(hp1).opcode=A_OR) or
  9970. (taicpu(hp1).opcode=A_XOR)
  9971. )
  9972. )
  9973. ) and
  9974. (
  9975. (taicpu(hp1).oper[0]^.typ = top_const) or
  9976. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9977. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9978. ) then
  9979. begin
  9980. { change
  9981. movx %reg2,%reg2
  9982. op const,%reg2
  9983. into
  9984. op const,%reg2 (smaller version)
  9985. movx %reg2,%reg2
  9986. also change
  9987. movx %reg1,%reg2
  9988. and/test (oper),%reg2
  9989. dealloc %reg2
  9990. into
  9991. and/test (oper),%reg1
  9992. }
  9993. case taicpu(p).opsize of
  9994. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9995. begin
  9996. NewSize := S_B;
  9997. NewRegSize := R_SUBL;
  9998. Limit := $FF;
  9999. end;
  10000. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10001. begin
  10002. NewSize := S_W;
  10003. NewRegSize := R_SUBW;
  10004. Limit := $FFFF;
  10005. end;
  10006. {$ifdef x86_64}
  10007. S_LQ:
  10008. begin
  10009. NewSize := S_L;
  10010. NewRegSize := R_SUBD;
  10011. Limit := $FFFFFFFF;
  10012. end;
  10013. {$endif x86_64}
  10014. else
  10015. Internalerror(2021120302);
  10016. end;
  10017. TransferUsedRegs(TmpUsedRegs);
  10018. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10019. if AndTest then
  10020. begin
  10021. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10022. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10023. end
  10024. else
  10025. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10026. if
  10027. (
  10028. (taicpu(p).opcode = A_MOVZX) and
  10029. (
  10030. (taicpu(hp1).opcode=A_AND) or
  10031. (taicpu(hp1).opcode=A_TEST)
  10032. ) and
  10033. not (
  10034. { If both are references, then the final instruction will have
  10035. both operands as references, which is not allowed }
  10036. (taicpu(p).oper[0]^.typ = top_ref) and
  10037. (taicpu(hp1).oper[0]^.typ = top_ref)
  10038. ) and
  10039. not RegUsed
  10040. ) or
  10041. (
  10042. (
  10043. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10044. not RegUsed
  10045. ) and
  10046. (taicpu(p).oper[0]^.typ = top_reg) and
  10047. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10048. (taicpu(hp1).oper[0]^.typ = top_const) and
  10049. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10050. ) then
  10051. begin
  10052. {$if defined(i386) or defined(i8086)}
  10053. { If the target size is 8-bit, make sure we can actually encode it }
  10054. 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
  10055. Exit;
  10056. {$endif i386 or i8086}
  10057. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10058. taicpu(hp1).opsize := NewSize;
  10059. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10060. if AndTest then
  10061. begin
  10062. RemoveInstruction(hp2);
  10063. if not RegUsed then
  10064. begin
  10065. taicpu(hp1).opcode := A_TEST;
  10066. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10067. begin
  10068. { Make sure the reference is the second operand }
  10069. SwapOper := taicpu(hp1).oper[0];
  10070. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10071. taicpu(hp1).oper[1] := SwapOper;
  10072. end;
  10073. end;
  10074. end;
  10075. case taicpu(hp1).oper[0]^.typ of
  10076. top_reg:
  10077. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10078. top_const:
  10079. { For the AND/TEST case }
  10080. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10081. else
  10082. ;
  10083. end;
  10084. if RegUsed then
  10085. begin
  10086. AsmL.Remove(p);
  10087. AsmL.InsertAfter(p, hp1);
  10088. p := hp1;
  10089. end
  10090. else
  10091. RemoveCurrentP(p, hp1);
  10092. result:=true;
  10093. exit;
  10094. end;
  10095. end;
  10096. end;
  10097. if reg_and_hp1_is_instr and
  10098. (taicpu(p).oper[0]^.typ = top_reg) and
  10099. (
  10100. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10101. ) and
  10102. (taicpu(hp1).oper[0]^.typ = top_const) and
  10103. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10104. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10105. { Minimum shift value allowed is the bit difference between the sizes }
  10106. (taicpu(hp1).oper[0]^.val >=
  10107. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10108. 8 * (
  10109. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10110. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10111. )
  10112. ) then
  10113. begin
  10114. { For:
  10115. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10116. shl/sal ##, %reg1
  10117. Remove the movsx/movzx instruction if the shift overwrites the
  10118. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10119. }
  10120. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10121. RemoveCurrentP(p, hp1);
  10122. Result := True;
  10123. Exit;
  10124. end
  10125. else if reg_and_hp1_is_instr and
  10126. (taicpu(p).oper[0]^.typ = top_reg) and
  10127. (
  10128. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10129. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10130. ) and
  10131. (taicpu(hp1).oper[0]^.typ = top_const) and
  10132. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10133. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10134. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10135. (taicpu(hp1).oper[0]^.val <
  10136. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10137. 8 * (
  10138. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10139. )
  10140. ) then
  10141. begin
  10142. { For:
  10143. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10144. sar ##, %reg1 shr ##, %reg1
  10145. Move the shift to before the movx instruction if the shift value
  10146. is not too large.
  10147. }
  10148. asml.Remove(hp1);
  10149. asml.InsertBefore(hp1, p);
  10150. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10151. case taicpu(p).opsize of
  10152. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10153. taicpu(hp1).opsize := S_B;
  10154. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10155. taicpu(hp1).opsize := S_W;
  10156. {$ifdef x86_64}
  10157. S_LQ:
  10158. taicpu(hp1).opsize := S_L;
  10159. {$endif}
  10160. else
  10161. InternalError(2020112401);
  10162. end;
  10163. if (taicpu(hp1).opcode = A_SHR) then
  10164. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10165. else
  10166. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10167. Result := True;
  10168. end;
  10169. if reg_and_hp1_is_instr and
  10170. (taicpu(p).oper[0]^.typ = top_reg) and
  10171. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10172. (
  10173. (taicpu(hp1).opcode = taicpu(p).opcode)
  10174. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10175. {$ifdef x86_64}
  10176. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10177. {$endif x86_64}
  10178. ) then
  10179. begin
  10180. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10181. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10182. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10183. begin
  10184. {
  10185. For example:
  10186. movzbw %al,%ax
  10187. movzwl %ax,%eax
  10188. Compress into:
  10189. movzbl %al,%eax
  10190. }
  10191. RegUsed := False;
  10192. case taicpu(p).opsize of
  10193. S_BW:
  10194. case taicpu(hp1).opsize of
  10195. S_WL:
  10196. begin
  10197. taicpu(p).opsize := S_BL;
  10198. RegUsed := True;
  10199. end;
  10200. {$ifdef x86_64}
  10201. S_WQ:
  10202. begin
  10203. if taicpu(p).opcode = A_MOVZX then
  10204. begin
  10205. taicpu(p).opsize := S_BL;
  10206. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10207. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10208. end
  10209. else
  10210. taicpu(p).opsize := S_BQ;
  10211. RegUsed := True;
  10212. end;
  10213. {$endif x86_64}
  10214. else
  10215. ;
  10216. end;
  10217. {$ifdef x86_64}
  10218. S_BL:
  10219. case taicpu(hp1).opsize of
  10220. S_LQ:
  10221. begin
  10222. if taicpu(p).opcode = A_MOVZX then
  10223. begin
  10224. taicpu(p).opsize := S_BL;
  10225. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10226. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10227. end
  10228. else
  10229. taicpu(p).opsize := S_BQ;
  10230. RegUsed := True;
  10231. end;
  10232. else
  10233. ;
  10234. end;
  10235. S_WL:
  10236. case taicpu(hp1).opsize of
  10237. S_LQ:
  10238. begin
  10239. if taicpu(p).opcode = A_MOVZX then
  10240. begin
  10241. taicpu(p).opsize := S_WL;
  10242. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10243. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10244. end
  10245. else
  10246. taicpu(p).opsize := S_WQ;
  10247. RegUsed := True;
  10248. end;
  10249. else
  10250. ;
  10251. end;
  10252. {$endif x86_64}
  10253. else
  10254. ;
  10255. end;
  10256. if RegUsed then
  10257. begin
  10258. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10259. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10260. RemoveInstruction(hp1);
  10261. Result := True;
  10262. Exit;
  10263. end;
  10264. end;
  10265. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10266. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10267. GetNextInstruction(hp1, hp2) and
  10268. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10269. (
  10270. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10271. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10272. {$ifdef x86_64}
  10273. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10274. {$endif x86_64}
  10275. ) and
  10276. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10277. (
  10278. (
  10279. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10280. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10281. ) or
  10282. (
  10283. { Only allow the operands in reverse order for TEST instructions }
  10284. (taicpu(hp2).opcode = A_TEST) and
  10285. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10286. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10287. )
  10288. ) then
  10289. begin
  10290. {
  10291. For example:
  10292. movzbl %al,%eax
  10293. movzbl (ref),%edx
  10294. andl %edx,%eax
  10295. (%edx deallocated)
  10296. Change to:
  10297. andb (ref),%al
  10298. movzbl %al,%eax
  10299. Rules are:
  10300. - First two instructions have the same opcode and opsize
  10301. - First instruction's operands are the same super-register
  10302. - Second instruction operates on a different register
  10303. - Third instruction is AND, OR, XOR or TEST
  10304. - Third instruction's operands are the destination registers of the first two instructions
  10305. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10306. - Second instruction's destination register is deallocated afterwards
  10307. }
  10308. TransferUsedRegs(TmpUsedRegs);
  10309. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10310. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10311. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10312. begin
  10313. case taicpu(p).opsize of
  10314. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10315. NewSize := S_B;
  10316. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10317. NewSize := S_W;
  10318. {$ifdef x86_64}
  10319. S_LQ:
  10320. NewSize := S_L;
  10321. {$endif x86_64}
  10322. else
  10323. InternalError(2021120301);
  10324. end;
  10325. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10326. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10327. taicpu(hp2).opsize := NewSize;
  10328. RemoveInstruction(hp1);
  10329. { With TEST, it's best to keep the MOVX instruction at the top }
  10330. if (taicpu(hp2).opcode <> A_TEST) then
  10331. begin
  10332. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10333. asml.Remove(p);
  10334. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10335. asml.InsertAfter(p, hp2);
  10336. p := hp2;
  10337. end
  10338. else
  10339. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10340. Result := True;
  10341. Exit;
  10342. end;
  10343. end;
  10344. end;
  10345. if taicpu(p).opcode=A_MOVZX then
  10346. begin
  10347. { removes superfluous And's after movzx's }
  10348. if reg_and_hp1_is_instr and
  10349. (taicpu(hp1).opcode = A_AND) and
  10350. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10351. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10352. {$ifdef x86_64}
  10353. { check for implicit extension to 64 bit }
  10354. or
  10355. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10356. (taicpu(hp1).opsize=S_Q) and
  10357. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10358. )
  10359. {$endif x86_64}
  10360. )
  10361. then
  10362. begin
  10363. case taicpu(p).opsize Of
  10364. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10365. if (taicpu(hp1).oper[0]^.val = $ff) then
  10366. begin
  10367. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10368. RemoveInstruction(hp1);
  10369. Result:=true;
  10370. exit;
  10371. end;
  10372. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10373. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10374. begin
  10375. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10376. RemoveInstruction(hp1);
  10377. Result:=true;
  10378. exit;
  10379. end;
  10380. {$ifdef x86_64}
  10381. S_LQ:
  10382. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10383. begin
  10384. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10385. RemoveInstruction(hp1);
  10386. Result:=true;
  10387. exit;
  10388. end;
  10389. {$endif x86_64}
  10390. else
  10391. ;
  10392. end;
  10393. { we cannot get rid of the and, but can we get rid of the movz ?}
  10394. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10395. begin
  10396. case taicpu(p).opsize Of
  10397. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10398. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10399. begin
  10400. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10401. RemoveCurrentP(p,hp1);
  10402. Result:=true;
  10403. exit;
  10404. end;
  10405. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10406. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10407. begin
  10408. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10409. RemoveCurrentP(p,hp1);
  10410. Result:=true;
  10411. exit;
  10412. end;
  10413. {$ifdef x86_64}
  10414. S_LQ:
  10415. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10416. begin
  10417. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10418. RemoveCurrentP(p,hp1);
  10419. Result:=true;
  10420. exit;
  10421. end;
  10422. {$endif x86_64}
  10423. else
  10424. ;
  10425. end;
  10426. end;
  10427. end;
  10428. { changes some movzx constructs to faster synonyms (all examples
  10429. are given with eax/ax, but are also valid for other registers)}
  10430. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10431. begin
  10432. case taicpu(p).opsize of
  10433. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10434. (the machine code is equivalent to movzbl %al,%eax), but the
  10435. code generator still generates that assembler instruction and
  10436. it is silently converted. This should probably be checked.
  10437. [Kit] }
  10438. S_BW:
  10439. begin
  10440. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10441. (
  10442. not IsMOVZXAcceptable
  10443. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10444. or (
  10445. (cs_opt_size in current_settings.optimizerswitches) and
  10446. (taicpu(p).oper[1]^.reg = NR_AX)
  10447. )
  10448. ) then
  10449. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10450. begin
  10451. DebugMsg(SPeepholeOptimization + 'var7',p);
  10452. taicpu(p).opcode := A_AND;
  10453. taicpu(p).changeopsize(S_W);
  10454. taicpu(p).loadConst(0,$ff);
  10455. Result := True;
  10456. end
  10457. else if not IsMOVZXAcceptable and
  10458. GetNextInstruction(p, hp1) and
  10459. (tai(hp1).typ = ait_instruction) and
  10460. (taicpu(hp1).opcode = A_AND) and
  10461. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10462. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10463. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10464. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10465. begin
  10466. DebugMsg(SPeepholeOptimization + 'var8',p);
  10467. taicpu(p).opcode := A_MOV;
  10468. taicpu(p).changeopsize(S_W);
  10469. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10470. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10471. Result := True;
  10472. end;
  10473. end;
  10474. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10475. S_BL:
  10476. begin
  10477. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10478. (
  10479. not IsMOVZXAcceptable
  10480. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10481. or (
  10482. (cs_opt_size in current_settings.optimizerswitches) and
  10483. (taicpu(p).oper[1]^.reg = NR_EAX)
  10484. )
  10485. ) then
  10486. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10487. begin
  10488. DebugMsg(SPeepholeOptimization + 'var9',p);
  10489. taicpu(p).opcode := A_AND;
  10490. taicpu(p).changeopsize(S_L);
  10491. taicpu(p).loadConst(0,$ff);
  10492. Result := True;
  10493. end
  10494. else if not IsMOVZXAcceptable and
  10495. GetNextInstruction(p, hp1) and
  10496. (tai(hp1).typ = ait_instruction) and
  10497. (taicpu(hp1).opcode = A_AND) and
  10498. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10499. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10500. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10501. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10502. begin
  10503. DebugMsg(SPeepholeOptimization + 'var10',p);
  10504. taicpu(p).opcode := A_MOV;
  10505. taicpu(p).changeopsize(S_L);
  10506. { do not use R_SUBWHOLE
  10507. as movl %rdx,%eax
  10508. is invalid in assembler PM }
  10509. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10510. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10511. Result := True;
  10512. end;
  10513. end;
  10514. {$endif i8086}
  10515. S_WL:
  10516. if not IsMOVZXAcceptable then
  10517. begin
  10518. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10519. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10520. begin
  10521. DebugMsg(SPeepholeOptimization + 'var11',p);
  10522. taicpu(p).opcode := A_AND;
  10523. taicpu(p).changeopsize(S_L);
  10524. taicpu(p).loadConst(0,$ffff);
  10525. Result := True;
  10526. end
  10527. else if GetNextInstruction(p, hp1) and
  10528. (tai(hp1).typ = ait_instruction) and
  10529. (taicpu(hp1).opcode = A_AND) and
  10530. (taicpu(hp1).oper[0]^.typ = top_const) and
  10531. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10532. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10533. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10534. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10535. begin
  10536. DebugMsg(SPeepholeOptimization + 'var12',p);
  10537. taicpu(p).opcode := A_MOV;
  10538. taicpu(p).changeopsize(S_L);
  10539. { do not use R_SUBWHOLE
  10540. as movl %rdx,%eax
  10541. is invalid in assembler PM }
  10542. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10543. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10544. Result := True;
  10545. end;
  10546. end;
  10547. else
  10548. InternalError(2017050705);
  10549. end;
  10550. end
  10551. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10552. begin
  10553. if GetNextInstruction(p, hp1) and
  10554. (tai(hp1).typ = ait_instruction) and
  10555. (taicpu(hp1).opcode = A_AND) and
  10556. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10557. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10558. begin
  10559. //taicpu(p).opcode := A_MOV;
  10560. case taicpu(p).opsize Of
  10561. S_BL:
  10562. begin
  10563. DebugMsg(SPeepholeOptimization + 'var13',p);
  10564. taicpu(hp1).changeopsize(S_L);
  10565. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10566. end;
  10567. S_WL:
  10568. begin
  10569. DebugMsg(SPeepholeOptimization + 'var14',p);
  10570. taicpu(hp1).changeopsize(S_L);
  10571. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10572. end;
  10573. S_BW:
  10574. begin
  10575. DebugMsg(SPeepholeOptimization + 'var15',p);
  10576. taicpu(hp1).changeopsize(S_W);
  10577. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10578. end;
  10579. else
  10580. Internalerror(2017050704)
  10581. end;
  10582. Result := True;
  10583. end;
  10584. end;
  10585. end;
  10586. end;
  10587. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10588. var
  10589. hp1, hp2 : tai;
  10590. MaskLength : Cardinal;
  10591. MaskedBits : TCgInt;
  10592. ActiveReg : TRegister;
  10593. begin
  10594. Result:=false;
  10595. { There are no optimisations for reference targets }
  10596. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10597. Exit;
  10598. while GetNextInstruction(p, hp1) and
  10599. (hp1.typ = ait_instruction) do
  10600. begin
  10601. if (taicpu(p).oper[0]^.typ = top_const) then
  10602. begin
  10603. case taicpu(hp1).opcode of
  10604. A_AND:
  10605. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10606. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10607. { the second register must contain the first one, so compare their subreg types }
  10608. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10609. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10610. { change
  10611. and const1, reg
  10612. and const2, reg
  10613. to
  10614. and (const1 and const2), reg
  10615. }
  10616. begin
  10617. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10618. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10619. RemoveCurrentP(p, hp1);
  10620. Result:=true;
  10621. exit;
  10622. end;
  10623. A_CMP:
  10624. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10625. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10626. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10627. { Just check that the condition on the next instruction is compatible }
  10628. GetNextInstruction(hp1, hp2) and
  10629. (hp2.typ = ait_instruction) and
  10630. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10631. then
  10632. { change
  10633. and 2^n, reg
  10634. cmp 2^n, reg
  10635. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10636. to
  10637. and 2^n, reg
  10638. test reg, reg
  10639. j(~c) / set(~c) / cmov(~c)
  10640. }
  10641. begin
  10642. { Keep TEST instruction in, rather than remove it, because
  10643. it may trigger other optimisations such as MovAndTest2Test }
  10644. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10645. taicpu(hp1).opcode := A_TEST;
  10646. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10647. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10648. Result := True;
  10649. Exit;
  10650. end;
  10651. A_MOVZX:
  10652. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10653. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10654. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10655. (
  10656. (
  10657. (taicpu(p).opsize=S_W) and
  10658. (taicpu(hp1).opsize=S_BW)
  10659. ) or
  10660. (
  10661. (taicpu(p).opsize=S_L) and
  10662. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10663. )
  10664. {$ifdef x86_64}
  10665. or
  10666. (
  10667. (taicpu(p).opsize=S_Q) and
  10668. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10669. )
  10670. {$endif x86_64}
  10671. ) then
  10672. begin
  10673. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10674. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10675. ) or
  10676. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10677. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10678. then
  10679. begin
  10680. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10681. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10682. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10683. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10684. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10685. }
  10686. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10687. RemoveInstruction(hp1);
  10688. { See if there are other optimisations possible }
  10689. Continue;
  10690. end;
  10691. end;
  10692. A_SHL:
  10693. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10694. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10695. begin
  10696. {$ifopt R+}
  10697. {$define RANGE_WAS_ON}
  10698. {$R-}
  10699. {$endif}
  10700. { get length of potential and mask }
  10701. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10702. { really a mask? }
  10703. {$ifdef RANGE_WAS_ON}
  10704. {$R+}
  10705. {$endif}
  10706. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10707. { unmasked part shifted out? }
  10708. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10709. begin
  10710. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10711. RemoveCurrentP(p, hp1);
  10712. Result:=true;
  10713. exit;
  10714. end;
  10715. end;
  10716. A_SHR:
  10717. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10718. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10719. (taicpu(hp1).oper[0]^.val <= 63) then
  10720. begin
  10721. { Does SHR combined with the AND cover all the bits?
  10722. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10723. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10724. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10725. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10726. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10727. begin
  10728. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10729. RemoveCurrentP(p, hp1);
  10730. Result := True;
  10731. Exit;
  10732. end;
  10733. end;
  10734. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10735. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10736. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10737. begin
  10738. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10739. (
  10740. (
  10741. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10742. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10743. ) or (
  10744. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10745. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10746. {$ifdef x86_64}
  10747. ) or (
  10748. (taicpu(hp1).opsize = S_LQ) and
  10749. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10750. {$endif x86_64}
  10751. )
  10752. ) then
  10753. begin
  10754. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10755. begin
  10756. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10757. RemoveInstruction(hp1);
  10758. { See if there are other optimisations possible }
  10759. Continue;
  10760. end;
  10761. { The super-registers are the same though.
  10762. Note that this change by itself doesn't improve
  10763. code speed, but it opens up other optimisations. }
  10764. {$ifdef x86_64}
  10765. { Convert 64-bit register to 32-bit }
  10766. case taicpu(hp1).opsize of
  10767. S_BQ:
  10768. begin
  10769. taicpu(hp1).opsize := S_BL;
  10770. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10771. end;
  10772. S_WQ:
  10773. begin
  10774. taicpu(hp1).opsize := S_WL;
  10775. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10776. end
  10777. else
  10778. ;
  10779. end;
  10780. {$endif x86_64}
  10781. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10782. taicpu(hp1).opcode := A_MOVZX;
  10783. { See if there are other optimisations possible }
  10784. Continue;
  10785. end;
  10786. end;
  10787. else
  10788. ;
  10789. end;
  10790. end
  10791. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10792. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10793. begin
  10794. {$ifdef x86_64}
  10795. if (taicpu(p).opsize = S_Q) then
  10796. begin
  10797. { Never necessary }
  10798. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10799. RemoveCurrentP(p, hp1);
  10800. Result := True;
  10801. Exit;
  10802. end;
  10803. {$endif x86_64}
  10804. { Forward check to determine necessity of and %reg,%reg }
  10805. TransferUsedRegs(TmpUsedRegs);
  10806. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10807. { Saves on a bunch of dereferences }
  10808. ActiveReg := taicpu(p).oper[1]^.reg;
  10809. case taicpu(hp1).opcode of
  10810. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10811. if (
  10812. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10813. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10814. ) and
  10815. (
  10816. (taicpu(hp1).opcode <> A_MOV) or
  10817. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10818. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10819. ) and
  10820. not (
  10821. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10822. (taicpu(hp1).opcode = A_MOV) and
  10823. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10824. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10825. ) and
  10826. (
  10827. (
  10828. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10829. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10830. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10831. ) or
  10832. (
  10833. {$ifdef x86_64}
  10834. (
  10835. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10836. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10837. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10838. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10839. ) and
  10840. {$endif x86_64}
  10841. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10842. )
  10843. ) then
  10844. begin
  10845. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10846. RemoveCurrentP(p, hp1);
  10847. Result := True;
  10848. Exit;
  10849. end;
  10850. A_ADD,
  10851. A_AND,
  10852. A_BSF,
  10853. A_BSR,
  10854. A_BTC,
  10855. A_BTR,
  10856. A_BTS,
  10857. A_OR,
  10858. A_SUB,
  10859. A_XOR:
  10860. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10861. if (
  10862. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10863. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10864. ) and
  10865. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10866. begin
  10867. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10868. RemoveCurrentP(p, hp1);
  10869. Result := True;
  10870. Exit;
  10871. end;
  10872. A_CMP,
  10873. A_TEST:
  10874. if (
  10875. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10876. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10877. ) and
  10878. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10879. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10880. begin
  10881. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10882. RemoveCurrentP(p, hp1);
  10883. Result := True;
  10884. Exit;
  10885. end;
  10886. A_BSWAP,
  10887. A_NEG,
  10888. A_NOT:
  10889. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10890. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10891. begin
  10892. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10893. RemoveCurrentP(p, hp1);
  10894. Result := True;
  10895. Exit;
  10896. end;
  10897. else
  10898. ;
  10899. end;
  10900. end;
  10901. if (taicpu(hp1).is_jmp) and
  10902. (taicpu(hp1).opcode<>A_JMP) and
  10903. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10904. begin
  10905. { change
  10906. and x, reg
  10907. jxx
  10908. to
  10909. test x, reg
  10910. jxx
  10911. if reg is deallocated before the
  10912. jump, but only if it's a conditional jump (PFV)
  10913. }
  10914. taicpu(p).opcode := A_TEST;
  10915. Exit;
  10916. end;
  10917. Break;
  10918. end;
  10919. { Lone AND tests }
  10920. if (taicpu(p).oper[0]^.typ = top_const) then
  10921. begin
  10922. {
  10923. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10924. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10925. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10926. }
  10927. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10928. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10929. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10930. begin
  10931. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10932. if taicpu(p).opsize = S_L then
  10933. begin
  10934. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10935. Result := True;
  10936. end;
  10937. end;
  10938. end;
  10939. { Backward check to determine necessity of and %reg,%reg }
  10940. if (taicpu(p).oper[0]^.typ = top_reg) and
  10941. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10942. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10943. GetLastInstruction(p, hp2) and
  10944. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10945. { Check size of adjacent instruction to determine if the AND is
  10946. effectively a null operation }
  10947. (
  10948. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10949. { Note: Don't include S_Q }
  10950. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10951. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10952. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10953. ) then
  10954. begin
  10955. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10956. { If GetNextInstruction returned False, hp1 will be nil }
  10957. RemoveCurrentP(p, hp1);
  10958. Result := True;
  10959. Exit;
  10960. end;
  10961. end;
  10962. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10963. var
  10964. hp1: tai; NewRef: TReference;
  10965. { This entire nested function is used in an if-statement below, but we
  10966. want to avoid all the used reg transfers and GetNextInstruction calls
  10967. until we really have to check }
  10968. function MemRegisterNotUsedLater: Boolean; inline;
  10969. var
  10970. hp2: tai;
  10971. begin
  10972. TransferUsedRegs(TmpUsedRegs);
  10973. hp2 := p;
  10974. repeat
  10975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10976. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10977. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10978. end;
  10979. begin
  10980. Result := False;
  10981. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10982. Exit;
  10983. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10984. begin
  10985. { Change:
  10986. add %reg2,%reg1
  10987. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10988. To:
  10989. mov/s/z #(%reg1,%reg2),%reg1
  10990. }
  10991. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10992. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10993. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10994. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10995. (
  10996. (
  10997. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10998. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10999. { r/esp cannot be an index }
  11000. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11001. ) or (
  11002. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11003. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11004. )
  11005. ) and (
  11006. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11007. (
  11008. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11009. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11010. MemRegisterNotUsedLater
  11011. )
  11012. ) then
  11013. begin
  11014. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11015. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11016. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11017. RemoveCurrentp(p, hp1);
  11018. Result := True;
  11019. Exit;
  11020. end;
  11021. { Change:
  11022. addl/q $x,%reg1
  11023. movl/q %reg1,%reg2
  11024. To:
  11025. leal/q $x(%reg1),%reg2
  11026. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11027. Breaks the dependency chain.
  11028. }
  11029. if MatchOpType(taicpu(p),top_const,top_reg) and
  11030. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11031. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11032. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11033. (
  11034. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11035. not (cs_opt_size in current_settings.optimizerswitches) or
  11036. (
  11037. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11038. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11039. )
  11040. ) then
  11041. begin
  11042. { Change the MOV instruction to a LEA instruction, and update the
  11043. first operand }
  11044. reference_reset(NewRef, 1, []);
  11045. NewRef.base := taicpu(p).oper[1]^.reg;
  11046. NewRef.scalefactor := 1;
  11047. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11048. taicpu(hp1).opcode := A_LEA;
  11049. taicpu(hp1).loadref(0, NewRef);
  11050. TransferUsedRegs(TmpUsedRegs);
  11051. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11052. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11053. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11054. begin
  11055. { Move what is now the LEA instruction to before the SUB instruction }
  11056. Asml.Remove(hp1);
  11057. Asml.InsertBefore(hp1, p);
  11058. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11059. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11060. p := hp1;
  11061. end
  11062. else
  11063. begin
  11064. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11065. RemoveCurrentP(p, hp1);
  11066. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11067. end;
  11068. Result := True;
  11069. end;
  11070. end;
  11071. end;
  11072. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11073. var
  11074. SubReg: TSubRegister;
  11075. begin
  11076. Result:=false;
  11077. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11078. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11079. with taicpu(p).oper[0]^.ref^ do
  11080. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11081. begin
  11082. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11083. begin
  11084. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11085. taicpu(p).opcode := A_ADD;
  11086. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11087. Result := True;
  11088. end
  11089. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11090. begin
  11091. if (base <> NR_NO) then
  11092. begin
  11093. if (scalefactor <= 1) then
  11094. begin
  11095. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11096. taicpu(p).opcode := A_ADD;
  11097. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11098. Result := True;
  11099. end;
  11100. end
  11101. else
  11102. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11103. if (scalefactor in [2, 4, 8]) then
  11104. begin
  11105. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11106. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11107. taicpu(p).opcode := A_SHL;
  11108. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11109. Result := True;
  11110. end;
  11111. end;
  11112. end;
  11113. end;
  11114. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11115. var
  11116. hp1: tai; NewRef: TReference;
  11117. begin
  11118. { Change:
  11119. subl/q $x,%reg1
  11120. movl/q %reg1,%reg2
  11121. To:
  11122. leal/q $-x(%reg1),%reg2
  11123. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11124. Breaks the dependency chain and potentially permits the removal of
  11125. a CMP instruction if one follows.
  11126. }
  11127. Result := False;
  11128. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11129. MatchOpType(taicpu(p),top_const,top_reg) and
  11130. GetNextInstruction(p, hp1) and
  11131. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11132. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11133. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11134. (
  11135. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11136. not (cs_opt_size in current_settings.optimizerswitches) or
  11137. (
  11138. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11139. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11140. )
  11141. ) then
  11142. begin
  11143. { Change the MOV instruction to a LEA instruction, and update the
  11144. first operand }
  11145. reference_reset(NewRef, 1, []);
  11146. NewRef.base := taicpu(p).oper[1]^.reg;
  11147. NewRef.scalefactor := 1;
  11148. NewRef.offset := -taicpu(p).oper[0]^.val;
  11149. taicpu(hp1).opcode := A_LEA;
  11150. taicpu(hp1).loadref(0, NewRef);
  11151. TransferUsedRegs(TmpUsedRegs);
  11152. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11153. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11154. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11155. begin
  11156. { Move what is now the LEA instruction to before the SUB instruction }
  11157. Asml.Remove(hp1);
  11158. Asml.InsertBefore(hp1, p);
  11159. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11160. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11161. p := hp1;
  11162. end
  11163. else
  11164. begin
  11165. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11166. RemoveCurrentP(p, hp1);
  11167. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11168. end;
  11169. Result := True;
  11170. end;
  11171. end;
  11172. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11173. begin
  11174. { we can skip all instructions not messing with the stack pointer }
  11175. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11176. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11177. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11178. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11179. ({(taicpu(hp1).ops=0) or }
  11180. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11181. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11182. ) and }
  11183. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11184. )
  11185. ) do
  11186. GetNextInstruction(hp1,hp1);
  11187. Result:=assigned(hp1);
  11188. end;
  11189. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11190. var
  11191. hp1, hp2, hp3, hp4, hp5: tai;
  11192. begin
  11193. Result:=false;
  11194. hp5:=nil;
  11195. { replace
  11196. leal(q) x(<stackpointer>),<stackpointer>
  11197. call procname
  11198. leal(q) -x(<stackpointer>),<stackpointer>
  11199. ret
  11200. by
  11201. jmp procname
  11202. but do it only on level 4 because it destroys stack back traces
  11203. }
  11204. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11205. MatchOpType(taicpu(p),top_ref,top_reg) and
  11206. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11207. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11208. { the -8 or -24 are not required, but bail out early if possible,
  11209. higher values are unlikely }
  11210. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11211. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11212. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11213. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11214. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11215. GetNextInstruction(p, hp1) and
  11216. { Take a copy of hp1 }
  11217. SetAndTest(hp1, hp4) and
  11218. { trick to skip label }
  11219. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11220. SkipSimpleInstructions(hp1) and
  11221. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11222. GetNextInstruction(hp1, hp2) and
  11223. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11224. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11225. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11226. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11227. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11228. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11229. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11230. { Segment register will be NR_NO }
  11231. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11232. GetNextInstruction(hp2, hp3) and
  11233. { trick to skip label }
  11234. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11235. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11236. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11237. SetAndTest(hp3,hp5) and
  11238. GetNextInstruction(hp3,hp3) and
  11239. MatchInstruction(hp3,A_RET,[S_NO])
  11240. )
  11241. ) and
  11242. (taicpu(hp3).ops=0) then
  11243. begin
  11244. taicpu(hp1).opcode := A_JMP;
  11245. taicpu(hp1).is_jmp := true;
  11246. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11247. RemoveCurrentP(p, hp4);
  11248. RemoveInstruction(hp2);
  11249. RemoveInstruction(hp3);
  11250. if Assigned(hp5) then
  11251. begin
  11252. AsmL.Remove(hp5);
  11253. ASmL.InsertBefore(hp5,hp1)
  11254. end;
  11255. Result:=true;
  11256. end;
  11257. end;
  11258. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11259. {$ifdef x86_64}
  11260. var
  11261. hp1, hp2, hp3, hp4, hp5: tai;
  11262. {$endif x86_64}
  11263. begin
  11264. Result:=false;
  11265. {$ifdef x86_64}
  11266. hp5:=nil;
  11267. { replace
  11268. push %rax
  11269. call procname
  11270. pop %rcx
  11271. ret
  11272. by
  11273. jmp procname
  11274. but do it only on level 4 because it destroys stack back traces
  11275. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11276. for all supported calling conventions
  11277. }
  11278. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11279. MatchOpType(taicpu(p),top_reg) and
  11280. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11281. GetNextInstruction(p, hp1) and
  11282. { Take a copy of hp1 }
  11283. SetAndTest(hp1, hp4) and
  11284. { trick to skip label }
  11285. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11286. SkipSimpleInstructions(hp1) and
  11287. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11288. GetNextInstruction(hp1, hp2) and
  11289. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11290. MatchOpType(taicpu(hp2),top_reg) and
  11291. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11292. GetNextInstruction(hp2, hp3) and
  11293. { trick to skip label }
  11294. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11295. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11296. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11297. SetAndTest(hp3,hp5) and
  11298. GetNextInstruction(hp3,hp3) and
  11299. MatchInstruction(hp3,A_RET,[S_NO])
  11300. )
  11301. ) and
  11302. (taicpu(hp3).ops=0) then
  11303. begin
  11304. taicpu(hp1).opcode := A_JMP;
  11305. taicpu(hp1).is_jmp := true;
  11306. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11307. RemoveCurrentP(p, hp4);
  11308. RemoveInstruction(hp2);
  11309. RemoveInstruction(hp3);
  11310. if Assigned(hp5) then
  11311. begin
  11312. AsmL.Remove(hp5);
  11313. ASmL.InsertBefore(hp5,hp1)
  11314. end;
  11315. Result:=true;
  11316. end;
  11317. {$endif x86_64}
  11318. end;
  11319. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11320. var
  11321. Value, RegName: string;
  11322. begin
  11323. Result:=false;
  11324. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11325. begin
  11326. case taicpu(p).oper[0]^.val of
  11327. 0:
  11328. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11329. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11330. begin
  11331. { change "mov $0,%reg" into "xor %reg,%reg" }
  11332. taicpu(p).opcode := A_XOR;
  11333. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11334. Result := True;
  11335. {$ifdef x86_64}
  11336. end
  11337. else if (taicpu(p).opsize = S_Q) then
  11338. begin
  11339. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11340. { The actual optimization }
  11341. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11342. taicpu(p).changeopsize(S_L);
  11343. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11344. Result := True;
  11345. end;
  11346. $1..$FFFFFFFF:
  11347. begin
  11348. { Code size reduction by J. Gareth "Kit" Moreton }
  11349. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11350. case taicpu(p).opsize of
  11351. S_Q:
  11352. begin
  11353. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11354. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11355. { The actual optimization }
  11356. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11357. taicpu(p).changeopsize(S_L);
  11358. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11359. Result := True;
  11360. end;
  11361. else
  11362. { Do nothing };
  11363. end;
  11364. {$endif x86_64}
  11365. end;
  11366. -1:
  11367. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11368. if (cs_opt_size in current_settings.optimizerswitches) and
  11369. (taicpu(p).opsize <> S_B) and
  11370. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11371. begin
  11372. { change "mov $-1,%reg" into "or $-1,%reg" }
  11373. { NOTES:
  11374. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11375. - This operation creates a false dependency on the register, so only do it when optimising for size
  11376. - 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
  11377. }
  11378. taicpu(p).opcode := A_OR;
  11379. Result := True;
  11380. end;
  11381. else
  11382. { Do nothing };
  11383. end;
  11384. end;
  11385. end;
  11386. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11387. var
  11388. hp1: tai;
  11389. begin
  11390. { Detect:
  11391. andw x, %ax (0 <= x < $8000)
  11392. ...
  11393. movzwl %ax,%eax
  11394. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11395. }
  11396. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11397. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11398. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11399. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11400. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11401. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11402. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11403. begin
  11404. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11405. taicpu(hp1).opcode := A_CWDE;
  11406. taicpu(hp1).clearop(0);
  11407. taicpu(hp1).clearop(1);
  11408. taicpu(hp1).ops := 0;
  11409. { A change was made, but not with p, so move forward 1 }
  11410. p := tai(p.Next);
  11411. Result := True;
  11412. end;
  11413. end;
  11414. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11415. begin
  11416. Result := False;
  11417. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11418. Exit;
  11419. { Convert:
  11420. movswl %ax,%eax -> cwtl
  11421. movslq %eax,%rax -> cdqe
  11422. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11423. refer to the same opcode and depends only on the assembler's
  11424. current operand-size attribute. [Kit]
  11425. }
  11426. with taicpu(p) do
  11427. case opsize of
  11428. S_WL:
  11429. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11430. begin
  11431. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11432. opcode := A_CWDE;
  11433. clearop(0);
  11434. clearop(1);
  11435. ops := 0;
  11436. Result := True;
  11437. end;
  11438. {$ifdef x86_64}
  11439. S_LQ:
  11440. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11441. begin
  11442. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11443. opcode := A_CDQE;
  11444. clearop(0);
  11445. clearop(1);
  11446. ops := 0;
  11447. Result := True;
  11448. end;
  11449. {$endif x86_64}
  11450. else
  11451. ;
  11452. end;
  11453. end;
  11454. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11455. var
  11456. hp1: tai;
  11457. begin
  11458. { Detect:
  11459. shr x, %ax (x > 0)
  11460. ...
  11461. movzwl %ax,%eax
  11462. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11463. }
  11464. Result := False;
  11465. if MatchOpType(taicpu(p), top_const, top_reg) and
  11466. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11467. (taicpu(p).oper[0]^.val > 0) and
  11468. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11469. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11470. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11471. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11472. begin
  11473. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11474. taicpu(hp1).opcode := A_CWDE;
  11475. taicpu(hp1).clearop(0);
  11476. taicpu(hp1).clearop(1);
  11477. taicpu(hp1).ops := 0;
  11478. { A change was made, but not with p, so move forward 1 }
  11479. p := tai(p.Next);
  11480. Result := True;
  11481. end;
  11482. end;
  11483. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11484. var
  11485. hp1, hp2: tai;
  11486. Opposite, SecondOpposite: TAsmOp;
  11487. NewCond: TAsmCond;
  11488. begin
  11489. Result := False;
  11490. { Change:
  11491. add/sub 128,(dest)
  11492. To:
  11493. sub/add -128,(dest)
  11494. This generaally takes fewer bytes to encode because -128 can be stored
  11495. in a signed byte, whereas +128 cannot.
  11496. }
  11497. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11498. begin
  11499. if taicpu(p).opcode = A_ADD then
  11500. Opposite := A_SUB
  11501. else
  11502. Opposite := A_ADD;
  11503. { Be careful if the flags are in use, because the CF flag inverts
  11504. when changing from ADD to SUB and vice versa }
  11505. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11506. GetNextInstruction(p, hp1) then
  11507. begin
  11508. TransferUsedRegs(TmpUsedRegs);
  11509. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11510. hp2 := hp1;
  11511. { Scan ahead to check if everything's safe }
  11512. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11513. begin
  11514. if (hp1.typ <> ait_instruction) then
  11515. { Probably unsafe since the flags are still in use }
  11516. Exit;
  11517. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11518. { Stop searching at an unconditional jump }
  11519. Break;
  11520. if not
  11521. (
  11522. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11523. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11524. ) and
  11525. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11526. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11527. Exit;
  11528. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11529. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11530. { Move to the next instruction }
  11531. GetNextInstruction(hp1, hp1);
  11532. end;
  11533. while Assigned(hp2) and (hp2 <> hp1) do
  11534. begin
  11535. NewCond := C_None;
  11536. case taicpu(hp2).condition of
  11537. C_A, C_NBE:
  11538. NewCond := C_BE;
  11539. C_B, C_C, C_NAE:
  11540. NewCond := C_AE;
  11541. C_AE, C_NB, C_NC:
  11542. NewCond := C_B;
  11543. C_BE, C_NA:
  11544. NewCond := C_A;
  11545. else
  11546. { No change needed };
  11547. end;
  11548. if NewCond <> C_None then
  11549. begin
  11550. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11551. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11552. taicpu(hp2).condition := NewCond;
  11553. end
  11554. else
  11555. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11556. begin
  11557. { Because of the flipping of the carry bit, to ensure
  11558. the operation remains equivalent, ADC becomes SBB
  11559. and vice versa, and the constant is not-inverted.
  11560. If multiple ADCs or SBBs appear in a row, each one
  11561. changed causes the carry bit to invert, so they all
  11562. need to be flipped }
  11563. if taicpu(hp2).opcode = A_ADC then
  11564. SecondOpposite := A_SBB
  11565. else
  11566. SecondOpposite := A_ADC;
  11567. if taicpu(hp2).oper[0]^.typ <> top_const then
  11568. { Should have broken out of this optimisation already }
  11569. InternalError(2021112901);
  11570. 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]^) + ' -> ' +
  11571. 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);
  11572. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11573. taicpu(hp2).opcode := SecondOpposite;
  11574. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11575. end;
  11576. { Move to the next instruction }
  11577. GetNextInstruction(hp2, hp2);
  11578. end;
  11579. if (hp2 <> hp1) then
  11580. InternalError(2021111501);
  11581. end;
  11582. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11583. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11584. taicpu(p).opcode := Opposite;
  11585. taicpu(p).oper[0]^.val := -128;
  11586. { No further optimisations can be made on this instruction, so move
  11587. onto the next one to save time }
  11588. p := tai(p.Next);
  11589. UpdateUsedRegs(p);
  11590. Result := True;
  11591. Exit;
  11592. end;
  11593. { Detect:
  11594. add/sub %reg2,(dest)
  11595. add/sub x, (dest)
  11596. (dest can be a register or a reference)
  11597. Swap the instructions to minimise a pipeline stall. This reverses the
  11598. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11599. optimisations could be made.
  11600. }
  11601. if (taicpu(p).oper[0]^.typ = top_reg) and
  11602. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11603. (
  11604. (
  11605. (taicpu(p).oper[1]^.typ = top_reg) and
  11606. { We can try searching further ahead if we're writing to a register }
  11607. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11608. ) or
  11609. (
  11610. (taicpu(p).oper[1]^.typ = top_ref) and
  11611. GetNextInstruction(p, hp1)
  11612. )
  11613. ) and
  11614. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11615. (taicpu(hp1).oper[0]^.typ = top_const) and
  11616. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11617. begin
  11618. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11619. TransferUsedRegs(TmpUsedRegs);
  11620. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11621. hp2 := p;
  11622. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11623. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11624. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11625. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11626. begin
  11627. asml.remove(hp1);
  11628. asml.InsertBefore(hp1, p);
  11629. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11630. Result := True;
  11631. end;
  11632. end;
  11633. end;
  11634. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11635. begin
  11636. Result:=false;
  11637. { change "cmp $0, %reg" to "test %reg, %reg" }
  11638. if MatchOpType(taicpu(p),top_const,top_reg) and
  11639. (taicpu(p).oper[0]^.val = 0) then
  11640. begin
  11641. taicpu(p).opcode := A_TEST;
  11642. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11643. Result:=true;
  11644. end;
  11645. end;
  11646. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11647. var
  11648. IsTestConstX : Boolean;
  11649. hp1,hp2 : tai;
  11650. begin
  11651. Result:=false;
  11652. { removes the line marked with (x) from the sequence
  11653. and/or/xor/add/sub/... $x, %y
  11654. test/or %y, %y | test $-1, %y (x)
  11655. j(n)z _Label
  11656. as the first instruction already adjusts the ZF
  11657. %y operand may also be a reference }
  11658. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11659. MatchOperand(taicpu(p).oper[0]^,-1);
  11660. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11661. GetLastInstruction(p, hp1) and
  11662. (tai(hp1).typ = ait_instruction) and
  11663. GetNextInstruction(p,hp2) and
  11664. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11665. case taicpu(hp1).opcode Of
  11666. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11667. { These two instructions set the zero flag if the result is zero }
  11668. A_POPCNT, A_LZCNT:
  11669. begin
  11670. if (
  11671. { With POPCNT, an input of zero will set the zero flag
  11672. because the population count of zero is zero }
  11673. (taicpu(hp1).opcode = A_POPCNT) and
  11674. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11675. (
  11676. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11677. { Faster than going through the second half of the 'or'
  11678. condition below }
  11679. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11680. )
  11681. ) or (
  11682. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11683. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11684. { and in case of carry for A(E)/B(E)/C/NC }
  11685. (
  11686. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11687. (
  11688. (taicpu(hp1).opcode <> A_ADD) and
  11689. (taicpu(hp1).opcode <> A_SUB) and
  11690. (taicpu(hp1).opcode <> A_LZCNT)
  11691. )
  11692. )
  11693. ) then
  11694. begin
  11695. RemoveCurrentP(p, hp2);
  11696. Result:=true;
  11697. Exit;
  11698. end;
  11699. end;
  11700. A_SHL, A_SAL, A_SHR, A_SAR:
  11701. begin
  11702. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11703. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11704. { therefore, it's only safe to do this optimization for }
  11705. { shifts by a (nonzero) constant }
  11706. (taicpu(hp1).oper[0]^.typ = top_const) and
  11707. (taicpu(hp1).oper[0]^.val <> 0) and
  11708. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11709. { and in case of carry for A(E)/B(E)/C/NC }
  11710. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11711. begin
  11712. RemoveCurrentP(p, hp2);
  11713. Result:=true;
  11714. Exit;
  11715. end;
  11716. end;
  11717. A_DEC, A_INC, A_NEG:
  11718. begin
  11719. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11720. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11721. { and in case of carry for A(E)/B(E)/C/NC }
  11722. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11723. begin
  11724. RemoveCurrentP(p, hp2);
  11725. Result:=true;
  11726. Exit;
  11727. end;
  11728. end
  11729. else
  11730. ;
  11731. end; { case }
  11732. { change "test $-1,%reg" into "test %reg,%reg" }
  11733. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11734. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11735. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11736. if MatchInstruction(p, A_OR, []) and
  11737. { Can only match if they're both registers }
  11738. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11739. begin
  11740. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11741. taicpu(p).opcode := A_TEST;
  11742. { No need to set Result to True, as we've done all the optimisations we can }
  11743. end;
  11744. end;
  11745. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11746. var
  11747. hp1,hp3 : tai;
  11748. {$ifndef x86_64}
  11749. hp2 : taicpu;
  11750. {$endif x86_64}
  11751. begin
  11752. Result:=false;
  11753. hp3:=nil;
  11754. {$ifndef x86_64}
  11755. { don't do this on modern CPUs, this really hurts them due to
  11756. broken call/ret pairing }
  11757. if (current_settings.optimizecputype < cpu_Pentium2) and
  11758. not(cs_create_pic in current_settings.moduleswitches) and
  11759. GetNextInstruction(p, hp1) and
  11760. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11761. MatchOpType(taicpu(hp1),top_ref) and
  11762. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11763. begin
  11764. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11765. InsertLLItem(p.previous, p, hp2);
  11766. taicpu(p).opcode := A_JMP;
  11767. taicpu(p).is_jmp := true;
  11768. RemoveInstruction(hp1);
  11769. Result:=true;
  11770. end
  11771. else
  11772. {$endif x86_64}
  11773. { replace
  11774. call procname
  11775. ret
  11776. by
  11777. jmp procname
  11778. but do it only on level 4 because it destroys stack back traces
  11779. else if the subroutine is marked as no return, remove the ret
  11780. }
  11781. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11782. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11783. GetNextInstruction(p, hp1) and
  11784. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11785. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11786. SetAndTest(hp1,hp3) and
  11787. GetNextInstruction(hp1,hp1) and
  11788. MatchInstruction(hp1,A_RET,[S_NO])
  11789. )
  11790. ) and
  11791. (taicpu(hp1).ops=0) then
  11792. begin
  11793. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11794. { we might destroy stack alignment here if we do not do a call }
  11795. (target_info.stackalign<=sizeof(SizeUInt)) then
  11796. begin
  11797. taicpu(p).opcode := A_JMP;
  11798. taicpu(p).is_jmp := true;
  11799. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11800. end
  11801. else
  11802. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11803. RemoveInstruction(hp1);
  11804. if Assigned(hp3) then
  11805. begin
  11806. AsmL.Remove(hp3);
  11807. AsmL.InsertBefore(hp3,p)
  11808. end;
  11809. Result:=true;
  11810. end;
  11811. end;
  11812. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11813. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11814. begin
  11815. case OpSize of
  11816. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11817. Result := (Val <= $FF) and (Val >= -128);
  11818. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11819. Result := (Val <= $FFFF) and (Val >= -32768);
  11820. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11821. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11822. else
  11823. Result := True;
  11824. end;
  11825. end;
  11826. var
  11827. hp1, hp2 : tai;
  11828. SizeChange: Boolean;
  11829. PreMessage: string;
  11830. begin
  11831. Result := False;
  11832. if (taicpu(p).oper[0]^.typ = top_reg) and
  11833. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11834. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11835. begin
  11836. { Change (using movzbl %al,%eax as an example):
  11837. movzbl %al, %eax movzbl %al, %eax
  11838. cmpl x, %eax testl %eax,%eax
  11839. To:
  11840. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11841. movzbl %al, %eax movzbl %al, %eax
  11842. Smaller instruction and minimises pipeline stall as the CPU
  11843. doesn't have to wait for the register to get zero-extended. [Kit]
  11844. Also allow if the smaller of the two registers is being checked,
  11845. as this still removes the false dependency.
  11846. }
  11847. if
  11848. (
  11849. (
  11850. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11851. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11852. ) or (
  11853. { If MatchOperand returns True, they must both be registers }
  11854. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11855. )
  11856. ) and
  11857. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11858. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11859. begin
  11860. 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);
  11861. asml.Remove(hp1);
  11862. asml.InsertBefore(hp1, p);
  11863. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11864. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11865. begin
  11866. taicpu(hp1).opcode := A_TEST;
  11867. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11868. end;
  11869. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11870. case taicpu(p).opsize of
  11871. S_BW, S_BL:
  11872. begin
  11873. SizeChange := taicpu(hp1).opsize <> S_B;
  11874. taicpu(hp1).changeopsize(S_B);
  11875. end;
  11876. S_WL:
  11877. begin
  11878. SizeChange := taicpu(hp1).opsize <> S_W;
  11879. taicpu(hp1).changeopsize(S_W);
  11880. end
  11881. else
  11882. InternalError(2020112701);
  11883. end;
  11884. UpdateUsedRegs(tai(p.Next));
  11885. { Check if the register is used aferwards - if not, we can
  11886. remove the movzx instruction completely }
  11887. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11888. begin
  11889. { Hp1 is a better position than p for debugging purposes }
  11890. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11891. RemoveCurrentp(p, hp1);
  11892. Result := True;
  11893. end;
  11894. if SizeChange then
  11895. DebugMsg(SPeepholeOptimization + PreMessage +
  11896. 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)
  11897. else
  11898. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11899. Exit;
  11900. end;
  11901. { Change (using movzwl %ax,%eax as an example):
  11902. movzwl %ax, %eax
  11903. movb %al, (dest) (Register is smaller than read register in movz)
  11904. To:
  11905. movb %al, (dest) (Move one back to avoid a false dependency)
  11906. movzwl %ax, %eax
  11907. }
  11908. if (taicpu(hp1).opcode = A_MOV) and
  11909. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11910. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11911. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11912. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11913. begin
  11914. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11915. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11916. asml.Remove(hp1);
  11917. asml.InsertBefore(hp1, p);
  11918. if taicpu(hp1).oper[1]^.typ = top_reg then
  11919. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11920. { Check if the register is used aferwards - if not, we can
  11921. remove the movzx instruction completely }
  11922. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11923. begin
  11924. { Hp1 is a better position than p for debugging purposes }
  11925. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11926. RemoveCurrentp(p, hp1);
  11927. Result := True;
  11928. end;
  11929. Exit;
  11930. end;
  11931. end;
  11932. end;
  11933. {$ifdef x86_64}
  11934. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11935. var
  11936. PreMessage, RegName: string;
  11937. begin
  11938. { Code size reduction by J. Gareth "Kit" Moreton }
  11939. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11940. as this removes the REX prefix }
  11941. Result := False;
  11942. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11943. Exit;
  11944. if taicpu(p).oper[0]^.typ <> top_reg then
  11945. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11946. InternalError(2018011500);
  11947. case taicpu(p).opsize of
  11948. S_Q:
  11949. begin
  11950. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11951. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11952. { The actual optimization }
  11953. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11954. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11955. taicpu(p).changeopsize(S_L);
  11956. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11957. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11958. end;
  11959. else
  11960. ;
  11961. end;
  11962. end;
  11963. {$endif}
  11964. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11965. var
  11966. XReg: TRegister;
  11967. begin
  11968. Result := False;
  11969. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11970. Smaller encoding and slightly faster on some platforms (also works for
  11971. ZMM-sized registers) }
  11972. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11973. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11974. begin
  11975. XReg := taicpu(p).oper[0]^.reg;
  11976. if (taicpu(p).oper[1]^.reg = XReg) then
  11977. begin
  11978. taicpu(p).changeopsize(S_XMM);
  11979. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11980. if (cs_opt_size in current_settings.optimizerswitches) then
  11981. begin
  11982. { Change input registers to %xmm0 to reduce size. Note that
  11983. there's a risk of a false dependency doing this, so only
  11984. optimise for size here }
  11985. XReg := NR_XMM0;
  11986. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11987. end
  11988. else
  11989. begin
  11990. setsubreg(XReg, R_SUBMMX);
  11991. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11992. end;
  11993. taicpu(p).oper[0]^.reg := XReg;
  11994. taicpu(p).oper[1]^.reg := XReg;
  11995. Result := True;
  11996. end;
  11997. end;
  11998. end;
  11999. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12000. var
  12001. OperIdx: Integer;
  12002. begin
  12003. for OperIdx := 0 to p.ops - 1 do
  12004. if p.oper[OperIdx]^.typ = top_ref then
  12005. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12006. end;
  12007. end.