aoptx86.pas 545 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747
  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. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  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. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  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. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  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 PrePeepholeOptSxx(var p : tai) : boolean;
  108. function PrePeepholeOptIMUL(var p : tai) : boolean;
  109. function PrePeepholeOptAND(var p : tai) : boolean;
  110. function OptPass1Test(var p: tai): boolean;
  111. function OptPass1Add(var p: tai): boolean;
  112. function OptPass1AND(var p : tai) : boolean;
  113. function OptPass1_V_MOVAP(var p : tai) : boolean;
  114. function OptPass1VOP(var p : tai) : boolean;
  115. function OptPass1MOV(var p : tai) : boolean;
  116. function OptPass1Movx(var p : tai) : boolean;
  117. function OptPass1MOVXX(var p : tai) : boolean;
  118. function OptPass1OP(var p : tai) : boolean;
  119. function OptPass1LEA(var p : tai) : boolean;
  120. function OptPass1Sub(var p : tai) : boolean;
  121. function OptPass1SHLSAL(var p : tai) : boolean;
  122. function OptPass1FSTP(var p : tai) : boolean;
  123. function OptPass1FLD(var p : tai) : boolean;
  124. function OptPass1Cmp(var p : tai) : boolean;
  125. function OptPass1PXor(var p : tai) : boolean;
  126. function OptPass1VPXor(var p: tai): boolean;
  127. function OptPass1Imul(var p : tai) : boolean;
  128. function OptPass1Jcc(var p : tai) : boolean;
  129. function OptPass1SHXX(var p: tai): boolean;
  130. function OptPass1VMOVDQ(var p: tai): Boolean;
  131. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  132. function OptPass2Movx(var p : tai): Boolean;
  133. function OptPass2MOV(var p : tai) : boolean;
  134. function OptPass2Imul(var p : tai) : boolean;
  135. function OptPass2Jmp(var p : tai) : boolean;
  136. function OptPass2Jcc(var p : tai) : boolean;
  137. function OptPass2Lea(var p: tai): Boolean;
  138. function OptPass2SUB(var p: tai): Boolean;
  139. function OptPass2ADD(var p : tai): Boolean;
  140. function OptPass2SETcc(var p : tai) : boolean;
  141. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  142. function PostPeepholeOptMov(var p : tai) : Boolean;
  143. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  144. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  145. function PostPeepholeOptXor(var p : tai) : Boolean;
  146. {$endif x86_64}
  147. function PostPeepholeOptAnd(var p : tai) : boolean;
  148. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  149. function PostPeepholeOptCmp(var p : tai) : Boolean;
  150. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  151. function PostPeepholeOptCall(var p : tai) : Boolean;
  152. function PostPeepholeOptLea(var p : tai) : Boolean;
  153. function PostPeepholeOptPush(var p: tai): Boolean;
  154. function PostPeepholeOptShr(var p : tai) : boolean;
  155. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  156. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  157. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  158. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  159. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  160. { Processor-dependent reference optimisation }
  161. class procedure OptimizeRefs(var p: taicpu); static;
  162. end;
  163. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  164. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  167. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  168. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  169. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  170. {$if max_operands>2}
  171. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  172. {$endif max_operands>2}
  173. function RefsEqual(const r1, r2: treference): boolean;
  174. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  175. { returns true, if ref is a reference using only the registers passed as base and index
  176. and having an offset }
  177. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  178. implementation
  179. uses
  180. cutils,verbose,
  181. systems,
  182. globals,
  183. cpuinfo,
  184. procinfo,
  185. paramgr,
  186. aasmbase,
  187. aoptbase,aoptutils,
  188. symconst,symsym,
  189. cgx86,
  190. itcpugas;
  191. {$ifdef DEBUG_AOPTCPU}
  192. const
  193. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  194. {$else DEBUG_AOPTCPU}
  195. { Empty strings help the optimizer to remove string concatenations that won't
  196. ever appear to the user on release builds. [Kit] }
  197. const
  198. SPeepholeOptimization = '';
  199. {$endif DEBUG_AOPTCPU}
  200. LIST_STEP_SIZE = 4;
  201. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. (taicpu(instr).opcode = op) and
  206. ((opsize = []) or (taicpu(instr).opsize in opsize));
  207. end;
  208. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  209. begin
  210. result :=
  211. (instr.typ = ait_instruction) and
  212. ((taicpu(instr).opcode = op1) or
  213. (taicpu(instr).opcode = op2)
  214. ) and
  215. ((opsize = []) or (taicpu(instr).opsize in opsize));
  216. end;
  217. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  218. begin
  219. result :=
  220. (instr.typ = ait_instruction) and
  221. ((taicpu(instr).opcode = op1) or
  222. (taicpu(instr).opcode = op2) or
  223. (taicpu(instr).opcode = op3)
  224. ) and
  225. ((opsize = []) or (taicpu(instr).opsize in opsize));
  226. end;
  227. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  228. const opsize : topsizes) : boolean;
  229. var
  230. op : TAsmOp;
  231. begin
  232. result:=false;
  233. if (instr.typ <> ait_instruction) or
  234. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  235. exit;
  236. for op in ops do
  237. begin
  238. if taicpu(instr).opcode = op then
  239. begin
  240. result:=true;
  241. exit;
  242. end;
  243. end;
  244. end;
  245. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  246. begin
  247. result := (oper.typ = top_reg) and (oper.reg = reg);
  248. end;
  249. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  250. begin
  251. result := (oper.typ = top_const) and (oper.val = a);
  252. end;
  253. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  254. begin
  255. result := oper1.typ = oper2.typ;
  256. if result then
  257. case oper1.typ of
  258. top_const:
  259. Result:=oper1.val = oper2.val;
  260. top_reg:
  261. Result:=oper1.reg = oper2.reg;
  262. top_ref:
  263. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  264. else
  265. internalerror(2013102801);
  266. end
  267. end;
  268. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  269. begin
  270. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  271. if result then
  272. case oper1.typ of
  273. top_const:
  274. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  275. top_reg:
  276. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  277. top_ref:
  278. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  279. else
  280. internalerror(2020052401);
  281. end
  282. end;
  283. function RefsEqual(const r1, r2: treference): boolean;
  284. begin
  285. RefsEqual :=
  286. (r1.offset = r2.offset) and
  287. (r1.segment = r2.segment) and (r1.base = r2.base) and
  288. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  289. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  290. (r1.relsymbol = r2.relsymbol) and
  291. (r1.volatility=[]) and
  292. (r2.volatility=[]);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  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);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  960. Result := NR_NO;
  961. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  962. for CurrentSuperReg in RegSet do
  963. begin
  964. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  965. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  966. {$if defined(i386) or defined(i8086)}
  967. { If the target size is 8-bit, make sure we can actually encode it }
  968. and (
  969. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  970. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  971. )
  972. {$endif i386 or i8086}
  973. then
  974. begin
  975. Currentp := p;
  976. Breakout := False;
  977. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  978. begin
  979. case Currentp.typ of
  980. ait_instruction:
  981. begin
  982. if RegInInstruction(CurrentReg, Currentp) then
  983. begin
  984. Breakout := True;
  985. Break;
  986. end;
  987. { Cannot allocate across an unconditional jump }
  988. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  989. Exit;
  990. end;
  991. ait_marker:
  992. { Don't try anything more if a marker is hit }
  993. Exit;
  994. ait_regalloc:
  995. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  996. begin
  997. Breakout := True;
  998. Break;
  999. end;
  1000. else
  1001. ;
  1002. end;
  1003. end;
  1004. if Breakout then
  1005. { Try the next register }
  1006. Continue;
  1007. { We have a free register available }
  1008. Result := CurrentReg;
  1009. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1010. Exit;
  1011. end;
  1012. end;
  1013. end;
  1014. { Attempts to allocate a volatile MM register for use between p and hp,
  1015. using AUsedRegs for the current register usage information. Returns NR_NO
  1016. if no free register could be found }
  1017. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1018. var
  1019. RegSet: TCPURegisterSet;
  1020. CurrentSuperReg: Integer;
  1021. CurrentReg: TRegister;
  1022. Currentp: tai;
  1023. Breakout: Boolean;
  1024. begin
  1025. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1026. Result := NR_NO;
  1027. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1028. for CurrentSuperReg in RegSet do
  1029. begin
  1030. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1031. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1032. begin
  1033. Currentp := p;
  1034. Breakout := False;
  1035. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1036. begin
  1037. case Currentp.typ of
  1038. ait_instruction:
  1039. begin
  1040. if RegInInstruction(CurrentReg, Currentp) then
  1041. begin
  1042. Breakout := True;
  1043. Break;
  1044. end;
  1045. { Cannot allocate across an unconditional jump }
  1046. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1047. Exit;
  1048. end;
  1049. ait_marker:
  1050. { Don't try anything more if a marker is hit }
  1051. Exit;
  1052. ait_regalloc:
  1053. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1054. begin
  1055. Breakout := True;
  1056. Break;
  1057. end;
  1058. else
  1059. ;
  1060. end;
  1061. end;
  1062. if Breakout then
  1063. { Try the next register }
  1064. Continue;
  1065. { We have a free register available }
  1066. Result := CurrentReg;
  1067. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1068. Exit;
  1069. end;
  1070. end;
  1071. end;
  1072. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1073. begin
  1074. if not SuperRegistersEqual(reg1,reg2) then
  1075. exit(false);
  1076. if getregtype(reg1)<>R_INTREGISTER then
  1077. exit(true); {because SuperRegisterEqual is true}
  1078. case getsubreg(reg1) of
  1079. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1080. higher, it preserves the high bits, so the new value depends on
  1081. reg2's previous value. In other words, it is equivalent to doing:
  1082. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1083. R_SUBL:
  1084. exit(getsubreg(reg2)=R_SUBL);
  1085. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1086. higher, it actually does a:
  1087. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1088. R_SUBH:
  1089. exit(getsubreg(reg2)=R_SUBH);
  1090. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1091. bits of reg2:
  1092. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1093. R_SUBW:
  1094. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1095. { a write to R_SUBD always overwrites every other subregister,
  1096. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1097. R_SUBD,
  1098. R_SUBQ:
  1099. exit(true);
  1100. else
  1101. internalerror(2017042801);
  1102. end;
  1103. end;
  1104. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1105. begin
  1106. if not SuperRegistersEqual(reg1,reg2) then
  1107. exit(false);
  1108. if getregtype(reg1)<>R_INTREGISTER then
  1109. exit(true); {because SuperRegisterEqual is true}
  1110. case getsubreg(reg1) of
  1111. R_SUBL:
  1112. exit(getsubreg(reg2)<>R_SUBH);
  1113. R_SUBH:
  1114. exit(getsubreg(reg2)<>R_SUBL);
  1115. R_SUBW,
  1116. R_SUBD,
  1117. R_SUBQ:
  1118. exit(true);
  1119. else
  1120. internalerror(2017042802);
  1121. end;
  1122. end;
  1123. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1124. var
  1125. hp1 : tai;
  1126. l : TCGInt;
  1127. begin
  1128. result:=false;
  1129. { changes the code sequence
  1130. shr/sar const1, x
  1131. shl const2, x
  1132. to
  1133. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1134. if GetNextInstruction(p, hp1) and
  1135. MatchInstruction(hp1,A_SHL,[]) and
  1136. (taicpu(p).oper[0]^.typ = top_const) and
  1137. (taicpu(hp1).oper[0]^.typ = top_const) and
  1138. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1139. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1140. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1141. begin
  1142. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1143. not(cs_opt_size in current_settings.optimizerswitches) then
  1144. begin
  1145. { shr/sar const1, %reg
  1146. shl const2, %reg
  1147. with const1 > const2 }
  1148. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1149. taicpu(hp1).opcode := A_AND;
  1150. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1151. case taicpu(p).opsize Of
  1152. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1153. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1154. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1155. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1156. else
  1157. Internalerror(2017050703)
  1158. end;
  1159. end
  1160. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1161. not(cs_opt_size in current_settings.optimizerswitches) then
  1162. begin
  1163. { shr/sar const1, %reg
  1164. shl const2, %reg
  1165. with const1 < const2 }
  1166. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1167. taicpu(p).opcode := A_AND;
  1168. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1169. case taicpu(p).opsize Of
  1170. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1171. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1172. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1173. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1174. else
  1175. Internalerror(2017050702)
  1176. end;
  1177. end
  1178. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1179. begin
  1180. { shr/sar const1, %reg
  1181. shl const2, %reg
  1182. with const1 = const2 }
  1183. taicpu(p).opcode := A_AND;
  1184. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1185. case taicpu(p).opsize Of
  1186. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1187. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1188. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1189. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1190. else
  1191. Internalerror(2017050701)
  1192. end;
  1193. RemoveInstruction(hp1);
  1194. end;
  1195. end;
  1196. end;
  1197. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1198. var
  1199. opsize : topsize;
  1200. hp1 : tai;
  1201. tmpref : treference;
  1202. ShiftValue : Cardinal;
  1203. BaseValue : TCGInt;
  1204. begin
  1205. result:=false;
  1206. opsize:=taicpu(p).opsize;
  1207. { changes certain "imul const, %reg"'s to lea sequences }
  1208. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1209. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1210. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1211. if (taicpu(p).oper[0]^.val = 1) then
  1212. if (taicpu(p).ops = 2) then
  1213. { remove "imul $1, reg" }
  1214. begin
  1215. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1216. Result := RemoveCurrentP(p);
  1217. end
  1218. else
  1219. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1220. begin
  1221. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1222. InsertLLItem(p.previous, p.next, hp1);
  1223. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1224. p.free;
  1225. p := hp1;
  1226. end
  1227. else if ((taicpu(p).ops <= 2) or
  1228. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1229. not(cs_opt_size in current_settings.optimizerswitches) and
  1230. (not(GetNextInstruction(p, hp1)) or
  1231. not((tai(hp1).typ = ait_instruction) and
  1232. ((taicpu(hp1).opcode=A_Jcc) and
  1233. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1234. begin
  1235. {
  1236. imul X, reg1, reg2 to
  1237. lea (reg1,reg1,Y), reg2
  1238. shl ZZ,reg2
  1239. imul XX, reg1 to
  1240. lea (reg1,reg1,YY), reg1
  1241. shl ZZ,reg2
  1242. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1243. it does not exist as a separate optimization target in FPC though.
  1244. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1245. at most two zeros
  1246. }
  1247. reference_reset(tmpref,1,[]);
  1248. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1249. begin
  1250. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1251. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1252. TmpRef.base := taicpu(p).oper[1]^.reg;
  1253. TmpRef.index := taicpu(p).oper[1]^.reg;
  1254. if not(BaseValue in [3,5,9]) then
  1255. Internalerror(2018110101);
  1256. TmpRef.ScaleFactor := BaseValue-1;
  1257. if (taicpu(p).ops = 2) then
  1258. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1259. else
  1260. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1261. AsmL.InsertAfter(hp1,p);
  1262. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1263. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1264. RemoveCurrentP(p, hp1);
  1265. if ShiftValue>0 then
  1266. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1267. end;
  1268. end;
  1269. end;
  1270. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1271. begin
  1272. Result := False;
  1273. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1274. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1275. begin
  1276. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1277. taicpu(p).opcode := A_MOV;
  1278. Result := True;
  1279. end;
  1280. end;
  1281. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1282. var
  1283. p: taicpu absolute hp;
  1284. i: Integer;
  1285. begin
  1286. Result := False;
  1287. if not assigned(hp) or
  1288. (hp.typ <> ait_instruction) then
  1289. Exit;
  1290. // p := taicpu(hp);
  1291. Prefetch(insprop[p.opcode]);
  1292. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1293. with insprop[p.opcode] do
  1294. begin
  1295. case getsubreg(reg) of
  1296. R_SUBW,R_SUBD,R_SUBQ:
  1297. Result:=
  1298. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1299. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1300. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1301. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1302. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1303. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1304. R_SUBFLAGCARRY:
  1305. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1306. R_SUBFLAGPARITY:
  1307. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1308. R_SUBFLAGAUXILIARY:
  1309. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1310. R_SUBFLAGZERO:
  1311. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1312. R_SUBFLAGSIGN:
  1313. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1314. R_SUBFLAGOVERFLOW:
  1315. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1316. R_SUBFLAGINTERRUPT:
  1317. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1318. R_SUBFLAGDIRECTION:
  1319. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1320. else
  1321. begin
  1322. writeln(getsubreg(reg));
  1323. internalerror(2017050501);
  1324. end;
  1325. end;
  1326. exit;
  1327. end;
  1328. { Handle special cases first }
  1329. case p.opcode of
  1330. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1331. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1332. begin
  1333. Result :=
  1334. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1335. (p.oper[1]^.typ = top_reg) and
  1336. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1337. (
  1338. (p.oper[0]^.typ = top_const) or
  1339. (
  1340. (p.oper[0]^.typ = top_reg) and
  1341. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1342. ) or (
  1343. (p.oper[0]^.typ = top_ref) and
  1344. not RegInRef(reg,p.oper[0]^.ref^)
  1345. )
  1346. );
  1347. end;
  1348. A_MUL, A_IMUL:
  1349. Result :=
  1350. (
  1351. (p.ops=3) and { IMUL only }
  1352. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1353. (
  1354. (
  1355. (p.oper[1]^.typ=top_reg) and
  1356. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1357. ) or (
  1358. (p.oper[1]^.typ=top_ref) and
  1359. not RegInRef(reg,p.oper[1]^.ref^)
  1360. )
  1361. )
  1362. ) or (
  1363. (
  1364. (p.ops=1) and
  1365. (
  1366. (
  1367. (
  1368. (p.oper[0]^.typ=top_reg) and
  1369. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1370. )
  1371. ) or (
  1372. (p.oper[0]^.typ=top_ref) and
  1373. not RegInRef(reg,p.oper[0]^.ref^)
  1374. )
  1375. ) and (
  1376. (
  1377. (p.opsize=S_B) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1379. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1380. ) or (
  1381. (p.opsize=S_W) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1383. ) or (
  1384. (p.opsize=S_L) and
  1385. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1386. {$ifdef x86_64}
  1387. ) or (
  1388. (p.opsize=S_Q) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1390. {$endif x86_64}
  1391. )
  1392. )
  1393. )
  1394. );
  1395. A_CBW:
  1396. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1397. {$ifndef x86_64}
  1398. A_LDS:
  1399. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LES:
  1401. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1402. {$endif not x86_64}
  1403. A_LFS:
  1404. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LGS:
  1406. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. A_LSS:
  1408. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1410. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1411. A_LODSB:
  1412. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1413. A_LODSW:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1415. {$ifdef x86_64}
  1416. A_LODSQ:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1418. {$endif x86_64}
  1419. A_LODSD:
  1420. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1421. A_FSTSW, A_FNSTSW:
  1422. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1423. else
  1424. begin
  1425. with insprop[p.opcode] do
  1426. begin
  1427. if (
  1428. { xor %reg,%reg etc. is classed as a new value }
  1429. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1430. MatchOpType(p, top_reg, top_reg) and
  1431. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1432. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1433. ) then
  1434. begin
  1435. Result := True;
  1436. Exit;
  1437. end;
  1438. { Make sure the entire register is overwritten }
  1439. if (getregtype(reg) = R_INTREGISTER) then
  1440. begin
  1441. if (p.ops > 0) then
  1442. begin
  1443. if RegInOp(reg, p.oper[0]^) then
  1444. begin
  1445. if (p.oper[0]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[0]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[0]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp1]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 1) then
  1473. begin
  1474. if RegInOp(reg, p.oper[1]^) then
  1475. begin
  1476. if (p.oper[1]^.typ = top_ref) then
  1477. begin
  1478. if RegInRef(reg, p.oper[1]^.ref^) then
  1479. begin
  1480. Result := False;
  1481. Exit;
  1482. end;
  1483. end
  1484. else if (p.oper[1]^.typ = top_reg) then
  1485. begin
  1486. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end
  1491. else if ([Ch_WOp2]*Ch<>[]) then
  1492. begin
  1493. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1494. Result := True
  1495. else
  1496. begin
  1497. Result := False;
  1498. Exit;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. if (p.ops > 2) then
  1504. begin
  1505. if RegInOp(reg, p.oper[2]^) then
  1506. begin
  1507. if (p.oper[2]^.typ = top_ref) then
  1508. begin
  1509. if RegInRef(reg, p.oper[2]^.ref^) then
  1510. begin
  1511. Result := False;
  1512. Exit;
  1513. end;
  1514. end
  1515. else if (p.oper[2]^.typ = top_reg) then
  1516. begin
  1517. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end
  1522. else if ([Ch_WOp3]*Ch<>[]) then
  1523. begin
  1524. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1525. Result := True
  1526. else
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end;
  1531. end;
  1532. end;
  1533. end;
  1534. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1535. begin
  1536. if (p.oper[3]^.typ = top_ref) then
  1537. begin
  1538. if RegInRef(reg, p.oper[3]^.ref^) then
  1539. begin
  1540. Result := False;
  1541. Exit;
  1542. end;
  1543. end
  1544. else if (p.oper[3]^.typ = top_reg) then
  1545. begin
  1546. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end
  1551. else if ([Ch_WOp4]*Ch<>[]) then
  1552. begin
  1553. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1554. Result := True
  1555. else
  1556. begin
  1557. Result := False;
  1558. Exit;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. end;
  1566. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1567. case getsupreg(reg) of
  1568. RS_EAX:
  1569. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1570. begin
  1571. Result := True;
  1572. Exit;
  1573. end;
  1574. RS_ECX:
  1575. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1576. begin
  1577. Result := True;
  1578. Exit;
  1579. end;
  1580. RS_EDX:
  1581. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1582. begin
  1583. Result := True;
  1584. Exit;
  1585. end;
  1586. RS_EBX:
  1587. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1588. begin
  1589. Result := True;
  1590. Exit;
  1591. end;
  1592. RS_ESP:
  1593. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1594. begin
  1595. Result := True;
  1596. Exit;
  1597. end;
  1598. RS_EBP:
  1599. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1600. begin
  1601. Result := True;
  1602. Exit;
  1603. end;
  1604. RS_ESI:
  1605. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1606. begin
  1607. Result := True;
  1608. Exit;
  1609. end;
  1610. RS_EDI:
  1611. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1612. begin
  1613. Result := True;
  1614. Exit;
  1615. end;
  1616. else
  1617. ;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. end;
  1624. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1625. var
  1626. hp2,hp3 : tai;
  1627. begin
  1628. { some x86-64 issue a NOP before the real exit code }
  1629. if MatchInstruction(p,A_NOP,[]) then
  1630. GetNextInstruction(p,p);
  1631. result:=assigned(p) and (p.typ=ait_instruction) and
  1632. ((taicpu(p).opcode = A_RET) or
  1633. ((taicpu(p).opcode=A_LEAVE) and
  1634. GetNextInstruction(p,hp2) and
  1635. MatchInstruction(hp2,A_RET,[S_NO])
  1636. ) or
  1637. (((taicpu(p).opcode=A_LEA) and
  1638. MatchOpType(taicpu(p),top_ref,top_reg) and
  1639. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1640. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1641. ) and
  1642. GetNextInstruction(p,hp2) and
  1643. MatchInstruction(hp2,A_RET,[S_NO])
  1644. ) or
  1645. ((((taicpu(p).opcode=A_MOV) and
  1646. MatchOpType(taicpu(p),top_reg,top_reg) and
  1647. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1648. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1649. ((taicpu(p).opcode=A_LEA) and
  1650. MatchOpType(taicpu(p),top_ref,top_reg) and
  1651. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1653. )
  1654. ) and
  1655. GetNextInstruction(p,hp2) and
  1656. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1657. MatchOpType(taicpu(hp2),top_reg) and
  1658. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1659. GetNextInstruction(hp2,hp3) and
  1660. MatchInstruction(hp3,A_RET,[S_NO])
  1661. )
  1662. );
  1663. end;
  1664. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1665. begin
  1666. isFoldableArithOp := False;
  1667. case hp1.opcode of
  1668. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1669. isFoldableArithOp :=
  1670. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1671. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1672. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1673. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1674. (taicpu(hp1).oper[1]^.reg = reg);
  1675. A_INC,A_DEC,A_NEG,A_NOT:
  1676. isFoldableArithOp :=
  1677. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[0]^.reg = reg);
  1679. else
  1680. ;
  1681. end;
  1682. end;
  1683. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1684. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1685. var
  1686. hp2: tai;
  1687. begin
  1688. hp2 := p;
  1689. repeat
  1690. hp2 := tai(hp2.previous);
  1691. if assigned(hp2) and
  1692. (hp2.typ = ait_regalloc) and
  1693. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1694. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1695. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1696. begin
  1697. RemoveInstruction(hp2);
  1698. break;
  1699. end;
  1700. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1701. end;
  1702. begin
  1703. case current_procinfo.procdef.returndef.typ of
  1704. arraydef,recorddef,pointerdef,
  1705. stringdef,enumdef,procdef,objectdef,errordef,
  1706. filedef,setdef,procvardef,
  1707. classrefdef,forwarddef:
  1708. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1709. orddef:
  1710. if current_procinfo.procdef.returndef.size <> 0 then
  1711. begin
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. { for int64/qword }
  1714. if current_procinfo.procdef.returndef.size = 8 then
  1715. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1716. end;
  1717. else
  1718. ;
  1719. end;
  1720. end;
  1721. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1722. var
  1723. hp1,hp2 : tai;
  1724. begin
  1725. result:=false;
  1726. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1727. begin
  1728. { vmova* reg1,reg1
  1729. =>
  1730. <nop> }
  1731. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1732. begin
  1733. RemoveCurrentP(p);
  1734. result:=true;
  1735. exit;
  1736. end
  1737. else if GetNextInstruction(p,hp1) then
  1738. begin
  1739. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1740. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1741. begin
  1742. { vmova* reg1,reg2
  1743. vmova* reg2,reg3
  1744. dealloc reg2
  1745. =>
  1746. vmova* reg1,reg3 }
  1747. TransferUsedRegs(TmpUsedRegs);
  1748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1749. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1750. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1751. begin
  1752. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1754. RemoveInstruction(hp1);
  1755. result:=true;
  1756. exit;
  1757. end
  1758. { special case:
  1759. vmova* reg1,<op>
  1760. vmova* <op>,reg1
  1761. =>
  1762. vmova* reg1,<op> }
  1763. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1764. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1765. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1766. ) then
  1767. begin
  1768. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1769. RemoveInstruction(hp1);
  1770. result:=true;
  1771. exit;
  1772. end
  1773. end
  1774. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1775. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1776. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1777. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1778. ) and
  1779. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1780. begin
  1781. { vmova* reg1,reg2
  1782. vmovs* reg2,<op>
  1783. dealloc reg2
  1784. =>
  1785. vmovs* reg1,reg3 }
  1786. TransferUsedRegs(TmpUsedRegs);
  1787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1789. begin
  1790. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1791. taicpu(p).opcode:=taicpu(hp1).opcode;
  1792. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1793. RemoveInstruction(hp1);
  1794. result:=true;
  1795. exit;
  1796. end
  1797. end;
  1798. end;
  1799. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1800. begin
  1801. if MatchInstruction(hp1,[A_VFMADDPD,
  1802. A_VFMADD132PD,
  1803. A_VFMADD132PS,
  1804. A_VFMADD132SD,
  1805. A_VFMADD132SS,
  1806. A_VFMADD213PD,
  1807. A_VFMADD213PS,
  1808. A_VFMADD213SD,
  1809. A_VFMADD213SS,
  1810. A_VFMADD231PD,
  1811. A_VFMADD231PS,
  1812. A_VFMADD231SD,
  1813. A_VFMADD231SS,
  1814. A_VFMADDSUB132PD,
  1815. A_VFMADDSUB132PS,
  1816. A_VFMADDSUB213PD,
  1817. A_VFMADDSUB213PS,
  1818. A_VFMADDSUB231PD,
  1819. A_VFMADDSUB231PS,
  1820. A_VFMSUB132PD,
  1821. A_VFMSUB132PS,
  1822. A_VFMSUB132SD,
  1823. A_VFMSUB132SS,
  1824. A_VFMSUB213PD,
  1825. A_VFMSUB213PS,
  1826. A_VFMSUB213SD,
  1827. A_VFMSUB213SS,
  1828. A_VFMSUB231PD,
  1829. A_VFMSUB231PS,
  1830. A_VFMSUB231SD,
  1831. A_VFMSUB231SS,
  1832. A_VFMSUBADD132PD,
  1833. A_VFMSUBADD132PS,
  1834. A_VFMSUBADD213PD,
  1835. A_VFMSUBADD213PS,
  1836. A_VFMSUBADD231PD,
  1837. A_VFMSUBADD231PS,
  1838. A_VFNMADD132PD,
  1839. A_VFNMADD132PS,
  1840. A_VFNMADD132SD,
  1841. A_VFNMADD132SS,
  1842. A_VFNMADD213PD,
  1843. A_VFNMADD213PS,
  1844. A_VFNMADD213SD,
  1845. A_VFNMADD213SS,
  1846. A_VFNMADD231PD,
  1847. A_VFNMADD231PS,
  1848. A_VFNMADD231SD,
  1849. A_VFNMADD231SS,
  1850. A_VFNMSUB132PD,
  1851. A_VFNMSUB132PS,
  1852. A_VFNMSUB132SD,
  1853. A_VFNMSUB132SS,
  1854. A_VFNMSUB213PD,
  1855. A_VFNMSUB213PS,
  1856. A_VFNMSUB213SD,
  1857. A_VFNMSUB213SS,
  1858. A_VFNMSUB231PD,
  1859. A_VFNMSUB231PS,
  1860. A_VFNMSUB231SD,
  1861. A_VFNMSUB231SS],[S_NO]) and
  1862. { we mix single and double opperations here because we assume that the compiler
  1863. generates vmovapd only after double operations and vmovaps only after single operations }
  1864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1865. GetNextInstruction(hp1,hp2) and
  1866. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1867. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1868. begin
  1869. TransferUsedRegs(TmpUsedRegs);
  1870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1873. begin
  1874. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1875. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1876. RemoveInstruction(hp2);
  1877. end;
  1878. end
  1879. else if (hp1.typ = ait_instruction) and
  1880. GetNextInstruction(hp1, hp2) and
  1881. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1882. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1883. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1884. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1885. (((taicpu(p).opcode=A_MOVAPS) and
  1886. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1887. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1888. ((taicpu(p).opcode=A_MOVAPD) and
  1889. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1890. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1891. ) then
  1892. { change
  1893. movapX reg,reg2
  1894. addsX/subsX/... reg3, reg2
  1895. movapX reg2,reg
  1896. to
  1897. addsX/subsX/... reg3,reg
  1898. }
  1899. begin
  1900. TransferUsedRegs(TmpUsedRegs);
  1901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1904. begin
  1905. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1906. debug_op2str(taicpu(p).opcode)+' '+
  1907. debug_op2str(taicpu(hp1).opcode)+' '+
  1908. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1909. { we cannot eliminate the first move if
  1910. the operations uses the same register for source and dest }
  1911. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1912. RemoveCurrentP(p, nil);
  1913. p:=hp1;
  1914. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1915. RemoveInstruction(hp2);
  1916. result:=true;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1923. var
  1924. hp1 : tai;
  1925. begin
  1926. result:=false;
  1927. { replace
  1928. V<Op>X %mreg1,%mreg2,%mreg3
  1929. VMovX %mreg3,%mreg4
  1930. dealloc %mreg3
  1931. by
  1932. V<Op>X %mreg1,%mreg2,%mreg4
  1933. ?
  1934. }
  1935. if GetNextInstruction(p,hp1) and
  1936. { we mix single and double operations here because we assume that the compiler
  1937. generates vmovapd only after double operations and vmovaps only after single operations }
  1938. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1939. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1940. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1941. begin
  1942. TransferUsedRegs(TmpUsedRegs);
  1943. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1944. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1945. begin
  1946. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1947. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1948. RemoveInstruction(hp1);
  1949. result:=true;
  1950. end;
  1951. end;
  1952. end;
  1953. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1954. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1955. begin
  1956. Result := False;
  1957. { For safety reasons, only check for exact register matches }
  1958. { Check base register }
  1959. if (ref.base = AOldReg) then
  1960. begin
  1961. ref.base := ANewReg;
  1962. Result := True;
  1963. end;
  1964. { Check index register }
  1965. if (ref.index = AOldReg) then
  1966. begin
  1967. ref.index := ANewReg;
  1968. Result := True;
  1969. end;
  1970. end;
  1971. { Replaces all references to AOldReg in an operand to ANewReg }
  1972. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1973. var
  1974. OldSupReg, NewSupReg: TSuperRegister;
  1975. OldSubReg, NewSubReg: TSubRegister;
  1976. OldRegType: TRegisterType;
  1977. ThisOper: POper;
  1978. begin
  1979. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1980. Result := False;
  1981. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1982. InternalError(2020011801);
  1983. OldSupReg := getsupreg(AOldReg);
  1984. OldSubReg := getsubreg(AOldReg);
  1985. OldRegType := getregtype(AOldReg);
  1986. NewSupReg := getsupreg(ANewReg);
  1987. NewSubReg := getsubreg(ANewReg);
  1988. if OldRegType <> getregtype(ANewReg) then
  1989. InternalError(2020011802);
  1990. if OldSubReg <> NewSubReg then
  1991. InternalError(2020011803);
  1992. case ThisOper^.typ of
  1993. top_reg:
  1994. if (
  1995. (ThisOper^.reg = AOldReg) or
  1996. (
  1997. (OldRegType = R_INTREGISTER) and
  1998. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1999. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2000. (
  2001. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2002. {$ifndef x86_64}
  2003. and (
  2004. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2005. don't have an 8-bit representation }
  2006. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2007. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2008. )
  2009. {$endif x86_64}
  2010. )
  2011. )
  2012. ) then
  2013. begin
  2014. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2015. Result := True;
  2016. end;
  2017. top_ref:
  2018. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2019. Result := True;
  2020. else
  2021. ;
  2022. end;
  2023. end;
  2024. { Replaces all references to AOldReg in an instruction to ANewReg }
  2025. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2026. const
  2027. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2028. var
  2029. OperIdx: Integer;
  2030. begin
  2031. Result := False;
  2032. for OperIdx := 0 to p.ops - 1 do
  2033. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2034. begin
  2035. { The shift and rotate instructions can only use CL }
  2036. if not (
  2037. (OperIdx = 0) and
  2038. { This second condition just helps to avoid unnecessarily
  2039. calling MatchInstruction for 10 different opcodes }
  2040. (p.oper[0]^.reg = NR_CL) and
  2041. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2042. ) then
  2043. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2044. end
  2045. else if p.oper[OperIdx]^.typ = top_ref then
  2046. { It's okay to replace registers in references that get written to }
  2047. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2048. end;
  2049. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2050. begin
  2051. with ref^ do
  2052. Result :=
  2053. (index = NR_NO) and
  2054. (
  2055. {$ifdef x86_64}
  2056. (
  2057. (base = NR_RIP) and
  2058. (refaddr in [addr_pic, addr_pic_no_got])
  2059. ) or
  2060. {$endif x86_64}
  2061. (base = NR_STACK_POINTER_REG) or
  2062. (base = current_procinfo.framepointer)
  2063. );
  2064. end;
  2065. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2066. var
  2067. l: asizeint;
  2068. begin
  2069. Result := False;
  2070. { Should have been checked previously }
  2071. if p.opcode <> A_LEA then
  2072. InternalError(2020072501);
  2073. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2074. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2075. not(cs_opt_size in current_settings.optimizerswitches) then
  2076. exit;
  2077. with p.oper[0]^.ref^ do
  2078. begin
  2079. if (base <> p.oper[1]^.reg) or
  2080. (index <> NR_NO) or
  2081. assigned(symbol) then
  2082. exit;
  2083. l:=offset;
  2084. if (l=1) and UseIncDec then
  2085. begin
  2086. p.opcode:=A_INC;
  2087. p.loadreg(0,p.oper[1]^.reg);
  2088. p.ops:=1;
  2089. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2090. end
  2091. else if (l=-1) and UseIncDec then
  2092. begin
  2093. p.opcode:=A_DEC;
  2094. p.loadreg(0,p.oper[1]^.reg);
  2095. p.ops:=1;
  2096. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2097. end
  2098. else
  2099. begin
  2100. if (l<0) and (l<>-2147483648) then
  2101. begin
  2102. p.opcode:=A_SUB;
  2103. p.loadConst(0,-l);
  2104. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2105. end
  2106. else
  2107. begin
  2108. p.opcode:=A_ADD;
  2109. p.loadConst(0,l);
  2110. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2111. end;
  2112. end;
  2113. end;
  2114. Result := True;
  2115. end;
  2116. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2117. var
  2118. CurrentReg, ReplaceReg: TRegister;
  2119. begin
  2120. Result := False;
  2121. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2122. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2123. case hp.opcode of
  2124. A_FSTSW, A_FNSTSW,
  2125. A_IN, A_INS, A_OUT, A_OUTS,
  2126. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2127. { These routines have explicit operands, but they are restricted in
  2128. what they can be (e.g. IN and OUT can only read from AL, AX or
  2129. EAX. }
  2130. Exit;
  2131. A_IMUL:
  2132. begin
  2133. { The 1-operand version writes to implicit registers
  2134. The 2-operand version reads from the first operator, and reads
  2135. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2136. the 3-operand version reads from a register that it doesn't write to
  2137. }
  2138. case hp.ops of
  2139. 1:
  2140. if (
  2141. (
  2142. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2143. ) or
  2144. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2145. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2146. begin
  2147. Result := True;
  2148. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2149. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2150. end;
  2151. 2:
  2152. { Only modify the first parameter }
  2153. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2154. begin
  2155. Result := True;
  2156. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2157. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2158. end;
  2159. 3:
  2160. { Only modify the second parameter }
  2161. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2162. begin
  2163. Result := True;
  2164. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2165. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2166. end;
  2167. else
  2168. InternalError(2020012901);
  2169. end;
  2170. end;
  2171. else
  2172. if (hp.ops > 0) and
  2173. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2174. begin
  2175. Result := True;
  2176. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2177. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2178. end;
  2179. end;
  2180. end;
  2181. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2182. var
  2183. hp1, hp2, hp3: tai;
  2184. DoOptimisation, TempBool: Boolean;
  2185. {$ifdef x86_64}
  2186. NewConst: TCGInt;
  2187. {$endif x86_64}
  2188. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2189. begin
  2190. if taicpu(hp1).opcode = signed_movop then
  2191. begin
  2192. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2193. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2194. end
  2195. else
  2196. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2197. end;
  2198. function TryConstMerge(var p1, p2: tai): Boolean;
  2199. var
  2200. ThisRef: TReference;
  2201. begin
  2202. Result := False;
  2203. ThisRef := taicpu(p2).oper[1]^.ref^;
  2204. { Only permit writes to the stack, since we can guarantee alignment with that }
  2205. if (ThisRef.index = NR_NO) and
  2206. (
  2207. (ThisRef.base = NR_STACK_POINTER_REG) or
  2208. (ThisRef.base = current_procinfo.framepointer)
  2209. ) then
  2210. begin
  2211. case taicpu(p).opsize of
  2212. S_B:
  2213. begin
  2214. { Word writes must be on a 2-byte boundary }
  2215. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2216. begin
  2217. { Reduce offset of second reference to see if it is sequential with the first }
  2218. Dec(ThisRef.offset, 1);
  2219. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2220. begin
  2221. { Make sure the constants aren't represented as a
  2222. negative number, as these won't merge properly }
  2223. taicpu(p1).opsize := S_W;
  2224. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2225. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2226. RemoveInstruction(p2);
  2227. Result := True;
  2228. end;
  2229. end;
  2230. end;
  2231. S_W:
  2232. begin
  2233. { Longword writes must be on a 4-byte boundary }
  2234. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2235. begin
  2236. { Reduce offset of second reference to see if it is sequential with the first }
  2237. Dec(ThisRef.offset, 2);
  2238. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2239. begin
  2240. { Make sure the constants aren't represented as a
  2241. negative number, as these won't merge properly }
  2242. taicpu(p1).opsize := S_L;
  2243. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2244. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2245. RemoveInstruction(p2);
  2246. Result := True;
  2247. end;
  2248. end;
  2249. end;
  2250. {$ifdef x86_64}
  2251. S_L:
  2252. begin
  2253. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2254. see if the constants can be encoded this way. }
  2255. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2256. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2257. { Quadword writes must be on an 8-byte boundary }
  2258. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2259. begin
  2260. { Reduce offset of second reference to see if it is sequential with the first }
  2261. Dec(ThisRef.offset, 4);
  2262. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2263. begin
  2264. { Make sure the constants aren't represented as a
  2265. negative number, as these won't merge properly }
  2266. taicpu(p1).opsize := S_Q;
  2267. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2268. taicpu(p1).oper[0]^.val := NewConst;
  2269. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2270. RemoveInstruction(p2);
  2271. Result := True;
  2272. end;
  2273. end;
  2274. end;
  2275. {$endif x86_64}
  2276. else
  2277. ;
  2278. end;
  2279. end;
  2280. end;
  2281. var
  2282. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2283. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2284. NewSize: topsize;
  2285. CurrentReg, ActiveReg: TRegister;
  2286. SourceRef, TargetRef: TReference;
  2287. MovAligned, MovUnaligned: TAsmOp;
  2288. begin
  2289. Result:=false;
  2290. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2291. { remove mov reg1,reg1? }
  2292. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2293. then
  2294. begin
  2295. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2296. { take care of the register (de)allocs following p }
  2297. RemoveCurrentP(p, hp1);
  2298. Result:=true;
  2299. exit;
  2300. end;
  2301. { All the next optimisations require a next instruction }
  2302. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2303. Exit;
  2304. { Look for:
  2305. mov %reg1,%reg2
  2306. ??? %reg2,r/m
  2307. Change to:
  2308. mov %reg1,%reg2
  2309. ??? %reg1,r/m
  2310. }
  2311. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2312. begin
  2313. CurrentReg := taicpu(p).oper[1]^.reg;
  2314. if RegReadByInstruction(CurrentReg, hp1) and
  2315. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2316. begin
  2317. { A change has occurred, just not in p }
  2318. Result := True;
  2319. TransferUsedRegs(TmpUsedRegs);
  2320. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2321. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2322. { Just in case something didn't get modified (e.g. an
  2323. implicit register) }
  2324. not RegReadByInstruction(CurrentReg, hp1) then
  2325. begin
  2326. { We can remove the original MOV }
  2327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2328. RemoveCurrentp(p, hp1);
  2329. { UsedRegs got updated by RemoveCurrentp }
  2330. Result := True;
  2331. Exit;
  2332. end;
  2333. { If we know a MOV instruction has become a null operation, we might as well
  2334. get rid of it now to save time. }
  2335. if (taicpu(hp1).opcode = A_MOV) and
  2336. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2337. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2338. { Just being a register is enough to confirm it's a null operation }
  2339. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2340. begin
  2341. Result := True;
  2342. { Speed-up to reduce a pipeline stall... if we had something like...
  2343. movl %eax,%edx
  2344. movw %dx,%ax
  2345. ... the second instruction would change to movw %ax,%ax, but
  2346. given that it is now %ax that's active rather than %eax,
  2347. penalties might occur due to a partial register write, so instead,
  2348. change it to a MOVZX instruction when optimising for speed.
  2349. }
  2350. if not (cs_opt_size in current_settings.optimizerswitches) and
  2351. IsMOVZXAcceptable and
  2352. (taicpu(hp1).opsize < taicpu(p).opsize)
  2353. {$ifdef x86_64}
  2354. { operations already implicitly set the upper 64 bits to zero }
  2355. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2356. {$endif x86_64}
  2357. then
  2358. begin
  2359. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2360. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2361. case taicpu(p).opsize of
  2362. S_W:
  2363. if taicpu(hp1).opsize = S_B then
  2364. taicpu(hp1).opsize := S_BL
  2365. else
  2366. InternalError(2020012911);
  2367. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2368. case taicpu(hp1).opsize of
  2369. S_B:
  2370. taicpu(hp1).opsize := S_BL;
  2371. S_W:
  2372. taicpu(hp1).opsize := S_WL;
  2373. else
  2374. InternalError(2020012912);
  2375. end;
  2376. else
  2377. InternalError(2020012910);
  2378. end;
  2379. taicpu(hp1).opcode := A_MOVZX;
  2380. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2381. end
  2382. else
  2383. begin
  2384. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2385. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2386. RemoveInstruction(hp1);
  2387. { The instruction after what was hp1 is now the immediate next instruction,
  2388. so we can continue to make optimisations if it's present }
  2389. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2390. Exit;
  2391. hp1 := hp2;
  2392. end;
  2393. end;
  2394. end;
  2395. end;
  2396. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2397. overwrites the original destination register. e.g.
  2398. movl ###,%reg2d
  2399. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2400. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2401. }
  2402. if (taicpu(p).oper[1]^.typ = top_reg) and
  2403. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2404. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2405. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2406. begin
  2407. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2408. begin
  2409. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2410. case taicpu(p).oper[0]^.typ of
  2411. top_const:
  2412. { We have something like:
  2413. movb $x, %regb
  2414. movzbl %regb,%regd
  2415. Change to:
  2416. movl $x, %regd
  2417. }
  2418. begin
  2419. case taicpu(hp1).opsize of
  2420. S_BW:
  2421. begin
  2422. convert_mov_value(A_MOVSX, $FF);
  2423. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2424. taicpu(p).opsize := S_W;
  2425. end;
  2426. S_BL:
  2427. begin
  2428. convert_mov_value(A_MOVSX, $FF);
  2429. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2430. taicpu(p).opsize := S_L;
  2431. end;
  2432. S_WL:
  2433. begin
  2434. convert_mov_value(A_MOVSX, $FFFF);
  2435. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2436. taicpu(p).opsize := S_L;
  2437. end;
  2438. {$ifdef x86_64}
  2439. S_BQ:
  2440. begin
  2441. convert_mov_value(A_MOVSX, $FF);
  2442. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2443. taicpu(p).opsize := S_Q;
  2444. end;
  2445. S_WQ:
  2446. begin
  2447. convert_mov_value(A_MOVSX, $FFFF);
  2448. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2449. taicpu(p).opsize := S_Q;
  2450. end;
  2451. S_LQ:
  2452. begin
  2453. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2454. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2455. taicpu(p).opsize := S_Q;
  2456. end;
  2457. {$endif x86_64}
  2458. else
  2459. { If hp1 was a MOV instruction, it should have been
  2460. optimised already }
  2461. InternalError(2020021001);
  2462. end;
  2463. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2464. RemoveInstruction(hp1);
  2465. Result := True;
  2466. Exit;
  2467. end;
  2468. top_ref:
  2469. { We have something like:
  2470. movb mem, %regb
  2471. movzbl %regb,%regd
  2472. Change to:
  2473. movzbl mem, %regd
  2474. }
  2475. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2476. begin
  2477. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2478. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2479. RemoveCurrentP(p, hp1);
  2480. Result:=True;
  2481. Exit;
  2482. end;
  2483. else
  2484. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2485. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2486. Exit;
  2487. end;
  2488. end
  2489. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2490. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2491. optimised }
  2492. else
  2493. begin
  2494. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2495. RemoveCurrentP(p, hp1);
  2496. Result := True;
  2497. Exit;
  2498. end;
  2499. end;
  2500. if (taicpu(hp1).opcode = A_AND) and
  2501. (taicpu(p).oper[1]^.typ = top_reg) and
  2502. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2503. begin
  2504. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2505. begin
  2506. case taicpu(p).opsize of
  2507. S_L:
  2508. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2509. begin
  2510. { Optimize out:
  2511. mov x, %reg
  2512. and ffffffffh, %reg
  2513. }
  2514. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2515. RemoveInstruction(hp1);
  2516. Result:=true;
  2517. exit;
  2518. end;
  2519. S_Q: { TODO: Confirm if this is even possible }
  2520. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2521. begin
  2522. { Optimize out:
  2523. mov x, %reg
  2524. and ffffffffffffffffh, %reg
  2525. }
  2526. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2527. RemoveInstruction(hp1);
  2528. Result:=true;
  2529. exit;
  2530. end;
  2531. else
  2532. ;
  2533. end;
  2534. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2535. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2536. GetNextInstruction(hp1,hp2) and
  2537. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2538. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2539. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2540. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2541. GetNextInstruction(hp2,hp3) and
  2542. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2543. (taicpu(hp3).condition in [C_E,C_NE]) then
  2544. begin
  2545. TransferUsedRegs(TmpUsedRegs);
  2546. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2547. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2548. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2549. begin
  2550. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2551. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2552. taicpu(hp1).opcode:=A_TEST;
  2553. RemoveInstruction(hp2);
  2554. RemoveCurrentP(p, hp1);
  2555. Result:=true;
  2556. exit;
  2557. end;
  2558. end;
  2559. end
  2560. else if IsMOVZXAcceptable and
  2561. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2562. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2563. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2564. then
  2565. begin
  2566. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2567. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2568. case taicpu(p).opsize of
  2569. S_B:
  2570. if (taicpu(hp1).oper[0]^.val = $ff) then
  2571. begin
  2572. { Convert:
  2573. movb x, %regl movb x, %regl
  2574. andw ffh, %regw andl ffh, %regd
  2575. To:
  2576. movzbw x, %regd movzbl x, %regd
  2577. (Identical registers, just different sizes)
  2578. }
  2579. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2580. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2581. case taicpu(hp1).opsize of
  2582. S_W: NewSize := S_BW;
  2583. S_L: NewSize := S_BL;
  2584. {$ifdef x86_64}
  2585. S_Q: NewSize := S_BQ;
  2586. {$endif x86_64}
  2587. else
  2588. InternalError(2018011510);
  2589. end;
  2590. end
  2591. else
  2592. NewSize := S_NO;
  2593. S_W:
  2594. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2595. begin
  2596. { Convert:
  2597. movw x, %regw
  2598. andl ffffh, %regd
  2599. To:
  2600. movzwl x, %regd
  2601. (Identical registers, just different sizes)
  2602. }
  2603. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2604. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2605. case taicpu(hp1).opsize of
  2606. S_L: NewSize := S_WL;
  2607. {$ifdef x86_64}
  2608. S_Q: NewSize := S_WQ;
  2609. {$endif x86_64}
  2610. else
  2611. InternalError(2018011511);
  2612. end;
  2613. end
  2614. else
  2615. NewSize := S_NO;
  2616. else
  2617. NewSize := S_NO;
  2618. end;
  2619. if NewSize <> S_NO then
  2620. begin
  2621. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2622. { The actual optimization }
  2623. taicpu(p).opcode := A_MOVZX;
  2624. taicpu(p).changeopsize(NewSize);
  2625. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2626. { Safeguard if "and" is followed by a conditional command }
  2627. TransferUsedRegs(TmpUsedRegs);
  2628. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2629. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2630. begin
  2631. { At this point, the "and" command is effectively equivalent to
  2632. "test %reg,%reg". This will be handled separately by the
  2633. Peephole Optimizer. [Kit] }
  2634. DebugMsg(SPeepholeOptimization + PreMessage +
  2635. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2636. end
  2637. else
  2638. begin
  2639. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2640. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2641. RemoveInstruction(hp1);
  2642. end;
  2643. Result := True;
  2644. Exit;
  2645. end;
  2646. end;
  2647. end;
  2648. if (taicpu(hp1).opcode = A_OR) and
  2649. (taicpu(p).oper[1]^.typ = top_reg) and
  2650. MatchOperand(taicpu(p).oper[0]^, 0) and
  2651. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2652. begin
  2653. { mov 0, %reg
  2654. or ###,%reg
  2655. Change to (only if the flags are not used):
  2656. mov ###,%reg
  2657. }
  2658. TransferUsedRegs(TmpUsedRegs);
  2659. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2660. DoOptimisation := True;
  2661. { Even if the flags are used, we might be able to do the optimisation
  2662. if the conditions are predictable }
  2663. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2664. begin
  2665. { Only perform if ### = %reg (the same register) or equal to 0,
  2666. so %reg is guaranteed to still have a value of zero }
  2667. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2668. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2669. begin
  2670. hp2 := hp1;
  2671. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2672. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2673. GetNextInstruction(hp2, hp3) do
  2674. begin
  2675. { Don't continue modifying if the flags state is getting changed }
  2676. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2677. Break;
  2678. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2679. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2680. begin
  2681. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2682. begin
  2683. { Condition is always true }
  2684. case taicpu(hp3).opcode of
  2685. A_Jcc:
  2686. begin
  2687. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2688. { Check for jump shortcuts before we destroy the condition }
  2689. DoJumpOptimizations(hp3, TempBool);
  2690. MakeUnconditional(taicpu(hp3));
  2691. Result := True;
  2692. end;
  2693. A_CMOVcc:
  2694. begin
  2695. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2696. taicpu(hp3).opcode := A_MOV;
  2697. taicpu(hp3).condition := C_None;
  2698. Result := True;
  2699. end;
  2700. A_SETcc:
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2703. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2704. taicpu(hp3).opcode := A_MOV;
  2705. taicpu(hp3).ops := 2;
  2706. taicpu(hp3).condition := C_None;
  2707. taicpu(hp3).opsize := S_B;
  2708. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2709. taicpu(hp3).loadconst(0, 1);
  2710. Result := True;
  2711. end;
  2712. else
  2713. InternalError(2021090701);
  2714. end;
  2715. end
  2716. 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
  2717. begin
  2718. { Condition is always false }
  2719. case taicpu(hp3).opcode of
  2720. A_Jcc:
  2721. begin
  2722. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2723. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2724. RemoveInstruction(hp3);
  2725. Result := True;
  2726. { Since hp3 was deleted, hp2 must not be updated }
  2727. Continue;
  2728. end;
  2729. A_CMOVcc:
  2730. begin
  2731. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2732. RemoveInstruction(hp3);
  2733. Result := True;
  2734. { Since hp3 was deleted, hp2 must not be updated }
  2735. Continue;
  2736. end;
  2737. A_SETcc:
  2738. begin
  2739. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2740. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2741. taicpu(hp3).opcode := A_MOV;
  2742. taicpu(hp3).ops := 2;
  2743. taicpu(hp3).condition := C_None;
  2744. taicpu(hp3).opsize := S_B;
  2745. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2746. taicpu(hp3).loadconst(0, 0);
  2747. Result := True;
  2748. end;
  2749. else
  2750. InternalError(2021090702);
  2751. end;
  2752. end
  2753. else
  2754. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2755. DoOptimisation := False;
  2756. end;
  2757. hp2 := hp3;
  2758. end;
  2759. { Flags are still in use - don't optimise }
  2760. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2761. DoOptimisation := False;
  2762. end
  2763. else
  2764. DoOptimisation := False;
  2765. end;
  2766. if DoOptimisation then
  2767. begin
  2768. {$ifdef x86_64}
  2769. { OR only supports 32-bit sign-extended constants for 64-bit
  2770. instructions, so compensate for this if the constant is
  2771. encoded as a value greater than or equal to 2^31 }
  2772. if (taicpu(hp1).opsize = S_Q) and
  2773. (taicpu(hp1).oper[0]^.typ = top_const) and
  2774. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2775. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2776. {$endif x86_64}
  2777. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2778. taicpu(hp1).opcode := A_MOV;
  2779. RemoveCurrentP(p, hp1);
  2780. Result := True;
  2781. Exit;
  2782. end;
  2783. end;
  2784. { Next instruction is also a MOV ? }
  2785. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2786. begin
  2787. if MatchOpType(taicpu(p), top_const, top_ref) and
  2788. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2789. TryConstMerge(p, hp1) then
  2790. begin
  2791. Result := True;
  2792. { In case we have four byte writes in a row, check for 2 more
  2793. right now so we don't have to wait for another iteration of
  2794. pass 1
  2795. }
  2796. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2797. case taicpu(p).opsize of
  2798. S_W:
  2799. begin
  2800. if GetNextInstruction(p, hp1) and
  2801. MatchInstruction(hp1, A_MOV, [S_B]) and
  2802. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2803. GetNextInstruction(hp1, hp2) and
  2804. MatchInstruction(hp2, A_MOV, [S_B]) and
  2805. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2806. { Try to merge the two bytes }
  2807. TryConstMerge(hp1, hp2) then
  2808. { Now try to merge the two words (hp2 will get deleted) }
  2809. TryConstMerge(p, hp1);
  2810. end;
  2811. S_L:
  2812. begin
  2813. { Though this only really benefits x86_64 and not i386, it
  2814. gets a potential optimisation done faster and hence
  2815. reduces the number of times OptPass1MOV is entered }
  2816. if GetNextInstruction(p, hp1) and
  2817. MatchInstruction(hp1, A_MOV, [S_W]) and
  2818. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2819. GetNextInstruction(hp1, hp2) and
  2820. MatchInstruction(hp2, A_MOV, [S_W]) and
  2821. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2822. { Try to merge the two words }
  2823. TryConstMerge(hp1, hp2) then
  2824. { This will always fail on i386, so don't bother
  2825. calling it unless we're doing x86_64 }
  2826. {$ifdef x86_64}
  2827. { Now try to merge the two longwords (hp2 will get deleted) }
  2828. TryConstMerge(p, hp1)
  2829. {$endif x86_64}
  2830. ;
  2831. end;
  2832. else
  2833. ;
  2834. end;
  2835. Exit;
  2836. end;
  2837. if (taicpu(p).oper[1]^.typ = top_reg) and
  2838. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2839. begin
  2840. CurrentReg := taicpu(p).oper[1]^.reg;
  2841. TransferUsedRegs(TmpUsedRegs);
  2842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2843. { we have
  2844. mov x, %treg
  2845. mov %treg, y
  2846. }
  2847. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2848. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2849. { we've got
  2850. mov x, %treg
  2851. mov %treg, y
  2852. with %treg is not used after }
  2853. case taicpu(p).oper[0]^.typ Of
  2854. { top_reg is covered by DeepMOVOpt }
  2855. top_const:
  2856. begin
  2857. { change
  2858. mov const, %treg
  2859. mov %treg, y
  2860. to
  2861. mov const, y
  2862. }
  2863. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2864. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2865. begin
  2866. if taicpu(hp1).oper[1]^.typ=top_reg then
  2867. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2868. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2869. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2870. RemoveInstruction(hp1);
  2871. Result:=true;
  2872. Exit;
  2873. end;
  2874. end;
  2875. top_ref:
  2876. case taicpu(hp1).oper[1]^.typ of
  2877. top_reg:
  2878. begin
  2879. { change
  2880. mov mem, %treg
  2881. mov %treg, %reg
  2882. to
  2883. mov mem, %reg"
  2884. }
  2885. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2886. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2887. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2888. RemoveInstruction(hp1);
  2889. Result:=true;
  2890. Exit;
  2891. end;
  2892. top_ref:
  2893. begin
  2894. {$ifdef x86_64}
  2895. { Look for the following to simplify:
  2896. mov x(mem1), %reg
  2897. mov %reg, y(mem2)
  2898. mov x+8(mem1), %reg
  2899. mov %reg, y+8(mem2)
  2900. Change to:
  2901. movdqu x(mem1), %xmmreg
  2902. movdqu %xmmreg, y(mem2)
  2903. }
  2904. SourceRef := taicpu(p).oper[0]^.ref^;
  2905. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2906. if (taicpu(p).opsize = S_Q) and
  2907. GetNextInstruction(hp1, hp2) and
  2908. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2909. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2910. begin
  2911. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2912. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2913. Inc(SourceRef.offset, 8);
  2914. if UseAVX then
  2915. begin
  2916. MovAligned := A_VMOVDQA;
  2917. MovUnaligned := A_VMOVDQU;
  2918. end
  2919. else
  2920. begin
  2921. MovAligned := A_MOVDQA;
  2922. MovUnaligned := A_MOVDQU;
  2923. end;
  2924. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2925. begin
  2926. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2927. Inc(TargetRef.offset, 8);
  2928. if GetNextInstruction(hp2, hp3) and
  2929. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2930. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2931. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2932. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2933. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2934. begin
  2935. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2936. if CurrentReg <> NR_NO then
  2937. begin
  2938. { Remember that the offsets are 8 ahead }
  2939. if ((SourceRef.offset mod 16) = 8) and
  2940. (
  2941. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2942. (SourceRef.base = current_procinfo.framepointer) or
  2943. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2944. ) then
  2945. taicpu(p).opcode := MovAligned
  2946. else
  2947. taicpu(p).opcode := MovUnaligned;
  2948. taicpu(p).opsize := S_XMM;
  2949. taicpu(p).oper[1]^.reg := CurrentReg;
  2950. if ((TargetRef.offset mod 16) = 8) and
  2951. (
  2952. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2953. (TargetRef.base = current_procinfo.framepointer) or
  2954. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2955. ) then
  2956. taicpu(hp1).opcode := MovAligned
  2957. else
  2958. taicpu(hp1).opcode := MovUnaligned;
  2959. taicpu(hp1).opsize := S_XMM;
  2960. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2961. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2962. RemoveInstruction(hp2);
  2963. RemoveInstruction(hp3);
  2964. Result := True;
  2965. Exit;
  2966. end;
  2967. end;
  2968. end
  2969. else
  2970. begin
  2971. { See if the next references are 8 less rather than 8 greater }
  2972. Dec(SourceRef.offset, 16); { -8 the other way }
  2973. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2974. begin
  2975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2976. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2977. if GetNextInstruction(hp2, hp3) and
  2978. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2979. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2980. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2981. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2982. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2983. begin
  2984. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2985. if CurrentReg <> NR_NO then
  2986. begin
  2987. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  2988. if ((SourceRef.offset mod 16) = 0) and
  2989. (
  2990. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2991. (SourceRef.base = current_procinfo.framepointer) or
  2992. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2993. ) then
  2994. taicpu(hp2).opcode := MovAligned
  2995. else
  2996. taicpu(hp2).opcode := MovUnaligned;
  2997. taicpu(hp2).opsize := S_XMM;
  2998. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2999. if ((TargetRef.offset mod 16) = 0) and
  3000. (
  3001. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3002. (TargetRef.base = current_procinfo.framepointer) or
  3003. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3004. ) then
  3005. taicpu(hp3).opcode := MovAligned
  3006. else
  3007. taicpu(hp3).opcode := MovUnaligned;
  3008. taicpu(hp3).opsize := S_XMM;
  3009. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3010. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3011. RemoveInstruction(hp1);
  3012. RemoveCurrentP(p, hp2);
  3013. Result := True;
  3014. Exit;
  3015. end;
  3016. end;
  3017. end;
  3018. end;
  3019. end;
  3020. {$endif x86_64}
  3021. end;
  3022. else
  3023. { The write target should be a reg or a ref }
  3024. InternalError(2021091601);
  3025. end;
  3026. else
  3027. ;
  3028. end
  3029. else
  3030. { %treg is used afterwards, but all eventualities
  3031. other than the first MOV instruction being a constant
  3032. are covered by DeepMOVOpt, so only check for that }
  3033. if (taicpu(p).oper[0]^.typ = top_const) and
  3034. (
  3035. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3036. not (cs_opt_size in current_settings.optimizerswitches) or
  3037. (taicpu(hp1).opsize = S_B)
  3038. ) and
  3039. (
  3040. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3041. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3042. ) then
  3043. begin
  3044. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3045. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3046. end;
  3047. end;
  3048. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3049. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3050. { mov reg1, mem1 or mov mem1, reg1
  3051. mov mem2, reg2 mov reg2, mem2}
  3052. begin
  3053. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3054. { mov reg1, mem1 or mov mem1, reg1
  3055. mov mem2, reg1 mov reg2, mem1}
  3056. begin
  3057. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3058. { Removes the second statement from
  3059. mov reg1, mem1/reg2
  3060. mov mem1/reg2, reg1 }
  3061. begin
  3062. if taicpu(p).oper[0]^.typ=top_reg then
  3063. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3064. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3065. RemoveInstruction(hp1);
  3066. Result:=true;
  3067. exit;
  3068. end
  3069. else
  3070. begin
  3071. TransferUsedRegs(TmpUsedRegs);
  3072. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3073. if (taicpu(p).oper[1]^.typ = top_ref) and
  3074. { mov reg1, mem1
  3075. mov mem2, reg1 }
  3076. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3077. GetNextInstruction(hp1, hp2) and
  3078. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3079. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3080. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3081. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3082. { change to
  3083. mov reg1, mem1 mov reg1, mem1
  3084. mov mem2, reg1 cmp reg1, mem2
  3085. cmp mem1, reg1
  3086. }
  3087. begin
  3088. RemoveInstruction(hp2);
  3089. taicpu(hp1).opcode := A_CMP;
  3090. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3091. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3092. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3093. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3094. end;
  3095. end;
  3096. end
  3097. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3098. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3099. begin
  3100. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3101. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3102. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3103. end
  3104. else
  3105. begin
  3106. TransferUsedRegs(TmpUsedRegs);
  3107. if GetNextInstruction(hp1, hp2) and
  3108. MatchOpType(taicpu(p),top_ref,top_reg) and
  3109. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3110. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3111. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3112. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3113. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3114. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3115. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3116. { mov mem1, %reg1
  3117. mov %reg1, mem2
  3118. mov mem2, reg2
  3119. to:
  3120. mov mem1, reg2
  3121. mov reg2, mem2}
  3122. begin
  3123. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3124. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3125. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3126. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3127. RemoveInstruction(hp2);
  3128. Result := True;
  3129. end
  3130. {$ifdef i386}
  3131. { this is enabled for i386 only, as the rules to create the reg sets below
  3132. are too complicated for x86-64, so this makes this code too error prone
  3133. on x86-64
  3134. }
  3135. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3136. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3137. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3138. { mov mem1, reg1 mov mem1, reg1
  3139. mov reg1, mem2 mov reg1, mem2
  3140. mov mem2, reg2 mov mem2, reg1
  3141. to: to:
  3142. mov mem1, reg1 mov mem1, reg1
  3143. mov mem1, reg2 mov reg1, mem2
  3144. mov reg1, mem2
  3145. or (if mem1 depends on reg1
  3146. and/or if mem2 depends on reg2)
  3147. to:
  3148. mov mem1, reg1
  3149. mov reg1, mem2
  3150. mov reg1, reg2
  3151. }
  3152. begin
  3153. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3154. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3155. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3156. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3157. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3158. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3159. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3160. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3161. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3162. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3163. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3164. end
  3165. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3166. begin
  3167. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3168. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3169. end
  3170. else
  3171. begin
  3172. RemoveInstruction(hp2);
  3173. end
  3174. {$endif i386}
  3175. ;
  3176. end;
  3177. end
  3178. { movl [mem1],reg1
  3179. movl [mem1],reg2
  3180. to
  3181. movl [mem1],reg1
  3182. movl reg1,reg2
  3183. }
  3184. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3185. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3186. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3187. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3188. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3189. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3190. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3191. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3192. begin
  3193. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3194. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3195. end;
  3196. { movl const1,[mem1]
  3197. movl [mem1],reg1
  3198. to
  3199. movl const1,reg1
  3200. movl reg1,[mem1]
  3201. }
  3202. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3203. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3204. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3205. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3206. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3207. begin
  3208. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3209. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3210. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3211. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3212. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3213. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3214. Result:=true;
  3215. exit;
  3216. end;
  3217. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3218. end;
  3219. { search further than the next instruction for a mov (as long as it's not a jump) }
  3220. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3221. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3222. (taicpu(p).oper[1]^.typ = top_reg) and
  3223. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3224. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3225. begin
  3226. { we work with hp2 here, so hp1 can be still used later on when
  3227. checking for GetNextInstruction_p }
  3228. hp3 := hp1;
  3229. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3230. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3231. { Saves on a large number of dereferences }
  3232. ActiveReg := taicpu(p).oper[1]^.reg;
  3233. TransferUsedRegs(TmpUsedRegs);
  3234. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3235. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3236. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3237. (hp2.typ=ait_instruction) do
  3238. begin
  3239. case taicpu(hp2).opcode of
  3240. A_POP:
  3241. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3242. begin
  3243. if not CrossJump and
  3244. not RegUsedBetween(ActiveReg, p, hp2) then
  3245. begin
  3246. { We can remove the original MOV since the register
  3247. wasn't used between it and its popping from the stack }
  3248. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3249. RemoveCurrentp(p, hp1);
  3250. Result := True;
  3251. Exit;
  3252. end;
  3253. { Can't go any further }
  3254. Break;
  3255. end;
  3256. A_MOV:
  3257. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3258. ((taicpu(p).oper[0]^.typ=top_const) or
  3259. ((taicpu(p).oper[0]^.typ=top_reg) and
  3260. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3261. )
  3262. ) then
  3263. begin
  3264. { we have
  3265. mov x, %treg
  3266. mov %treg, y
  3267. }
  3268. { We don't need to call UpdateUsedRegs for every instruction between
  3269. p and hp2 because the register we're concerned about will not
  3270. become deallocated (otherwise GetNextInstructionUsingReg would
  3271. have stopped at an earlier instruction). [Kit] }
  3272. TempRegUsed :=
  3273. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3274. RegReadByInstruction(ActiveReg, hp3) or
  3275. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3276. case taicpu(p).oper[0]^.typ Of
  3277. top_reg:
  3278. begin
  3279. { change
  3280. mov %reg, %treg
  3281. mov %treg, y
  3282. to
  3283. mov %reg, y
  3284. }
  3285. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3286. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3287. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3288. begin
  3289. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3290. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3291. if TempRegUsed then
  3292. begin
  3293. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3294. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3295. { Set the start of the next GetNextInstructionUsingRegCond search
  3296. to start at the entry right before hp2 (which is about to be removed) }
  3297. hp3 := tai(hp2.Previous);
  3298. RemoveInstruction(hp2);
  3299. { See if there's more we can optimise }
  3300. Continue;
  3301. end
  3302. else
  3303. begin
  3304. RemoveInstruction(hp2);
  3305. { We can remove the original MOV too }
  3306. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3307. RemoveCurrentP(p, hp1);
  3308. Result:=true;
  3309. Exit;
  3310. end;
  3311. end
  3312. else
  3313. begin
  3314. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3315. taicpu(hp2).loadReg(0, CurrentReg);
  3316. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3317. { Check to see if the register also appears in the reference }
  3318. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3319. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3320. { Don't remove the first instruction if the temporary register is in use }
  3321. if not TempRegUsed and
  3322. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3323. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3324. begin
  3325. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3326. RemoveCurrentP(p, hp1);
  3327. Result:=true;
  3328. Exit;
  3329. end;
  3330. { No need to set Result to True here. If there's another instruction later
  3331. on that can be optimised, it will be detected when the main Pass 1 loop
  3332. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3333. end;
  3334. end;
  3335. top_const:
  3336. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3337. begin
  3338. { change
  3339. mov const, %treg
  3340. mov %treg, y
  3341. to
  3342. mov const, y
  3343. }
  3344. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3345. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3346. begin
  3347. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3348. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3349. if TempRegUsed then
  3350. begin
  3351. { Don't remove the first instruction if the temporary register is in use }
  3352. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3353. { No need to set Result to True. If there's another instruction later on
  3354. that can be optimised, it will be detected when the main Pass 1 loop
  3355. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3356. end
  3357. else
  3358. begin
  3359. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3360. RemoveCurrentP(p, hp1);
  3361. Result:=true;
  3362. Exit;
  3363. end;
  3364. end;
  3365. end;
  3366. else
  3367. Internalerror(2019103001);
  3368. end;
  3369. end
  3370. else
  3371. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3372. begin
  3373. if not CrossJump and
  3374. not RegUsedBetween(ActiveReg, p, hp2) and
  3375. not RegReadByInstruction(ActiveReg, hp2) then
  3376. begin
  3377. { Register is not used before it is overwritten }
  3378. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3379. RemoveCurrentp(p, hp1);
  3380. Result := True;
  3381. Exit;
  3382. end;
  3383. if (taicpu(p).oper[0]^.typ = top_const) and
  3384. (taicpu(hp2).oper[0]^.typ = top_const) then
  3385. begin
  3386. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3387. begin
  3388. { Same value - register hasn't changed }
  3389. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3390. RemoveInstruction(hp2);
  3391. Result := True;
  3392. { See if there's more we can optimise }
  3393. Continue;
  3394. end;
  3395. end;
  3396. end;
  3397. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3398. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3399. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3400. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3401. begin
  3402. {
  3403. Change from:
  3404. mov ###, %reg
  3405. ...
  3406. movs/z %reg,%reg (Same register, just different sizes)
  3407. To:
  3408. movs/z ###, %reg (Longer version)
  3409. ...
  3410. (remove)
  3411. }
  3412. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3413. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3414. { Keep the first instruction as mov if ### is a constant }
  3415. if taicpu(p).oper[0]^.typ = top_const then
  3416. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3417. else
  3418. begin
  3419. taicpu(p).opcode := taicpu(hp2).opcode;
  3420. taicpu(p).opsize := taicpu(hp2).opsize;
  3421. end;
  3422. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3423. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3424. RemoveInstruction(hp2);
  3425. Result := True;
  3426. Exit;
  3427. end;
  3428. else
  3429. { Move down to the MatchOpType if-block below };
  3430. end;
  3431. { Also catches MOV/S/Z instructions that aren't modified }
  3432. if taicpu(p).oper[0]^.typ = top_reg then
  3433. begin
  3434. CurrentReg := taicpu(p).oper[0]^.reg;
  3435. if
  3436. not RegModifiedByInstruction(CurrentReg, hp3) and
  3437. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3438. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3439. begin
  3440. Result := True;
  3441. { Just in case something didn't get modified (e.g. an
  3442. implicit register). Also, if it does read from this
  3443. register, then there's no longer an advantage to
  3444. changing the register on subsequent instructions.}
  3445. if not RegReadByInstruction(ActiveReg, hp2) then
  3446. begin
  3447. { If a conditional jump was crossed, do not delete
  3448. the original MOV no matter what }
  3449. if not CrossJump and
  3450. { RegEndOfLife returns True if the register is
  3451. deallocated before the next instruction or has
  3452. been loaded with a new value }
  3453. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3454. begin
  3455. { We can remove the original MOV }
  3456. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3457. RemoveCurrentp(p, hp1);
  3458. Exit;
  3459. end;
  3460. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3461. begin
  3462. { See if there's more we can optimise }
  3463. hp3 := hp2;
  3464. Continue;
  3465. end;
  3466. end;
  3467. end;
  3468. end;
  3469. { Break out of the while loop under normal circumstances }
  3470. Break;
  3471. end;
  3472. end;
  3473. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3474. (taicpu(p).oper[1]^.typ = top_reg) and
  3475. (taicpu(p).opsize = S_L) and
  3476. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3477. (taicpu(hp2).opcode = A_AND) and
  3478. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3479. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3480. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3481. ) then
  3482. begin
  3483. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3484. begin
  3485. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3486. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3487. begin
  3488. { Optimize out:
  3489. mov x, %reg
  3490. and ffffffffh, %reg
  3491. }
  3492. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3493. RemoveInstruction(hp2);
  3494. Result:=true;
  3495. exit;
  3496. end;
  3497. end;
  3498. end;
  3499. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3500. x >= RetOffset) as it doesn't do anything (it writes either to a
  3501. parameter or to the temporary storage room for the function
  3502. result)
  3503. }
  3504. if IsExitCode(hp1) and
  3505. (taicpu(p).oper[1]^.typ = top_ref) and
  3506. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3507. (
  3508. (
  3509. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3510. not (
  3511. assigned(current_procinfo.procdef.funcretsym) and
  3512. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3513. )
  3514. ) or
  3515. { Also discard writes to the stack that are below the base pointer,
  3516. as this is temporary storage rather than a function result on the
  3517. stack, say. }
  3518. (
  3519. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3520. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3521. )
  3522. ) then
  3523. begin
  3524. RemoveCurrentp(p, hp1);
  3525. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3526. RemoveLastDeallocForFuncRes(p);
  3527. Result:=true;
  3528. exit;
  3529. end;
  3530. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3531. begin
  3532. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3533. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3534. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3535. begin
  3536. { change
  3537. mov reg1, mem1
  3538. test/cmp x, mem1
  3539. to
  3540. mov reg1, mem1
  3541. test/cmp x, reg1
  3542. }
  3543. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3544. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3545. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3546. Result := True;
  3547. Exit;
  3548. end;
  3549. if DoMovCmpMemOpt(p, hp1, True) then
  3550. begin
  3551. Result := True;
  3552. Exit;
  3553. end;
  3554. end;
  3555. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3556. { If the flags register is in use, don't change the instruction to an
  3557. ADD otherwise this will scramble the flags. [Kit] }
  3558. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3559. begin
  3560. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3561. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3562. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3563. ) or
  3564. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3565. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3566. )
  3567. ) then
  3568. { mov reg1,ref
  3569. lea reg2,[reg1,reg2]
  3570. to
  3571. add reg2,ref}
  3572. begin
  3573. TransferUsedRegs(TmpUsedRegs);
  3574. { reg1 may not be used afterwards }
  3575. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3576. begin
  3577. Taicpu(hp1).opcode:=A_ADD;
  3578. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3579. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3580. RemoveCurrentp(p, hp1);
  3581. result:=true;
  3582. exit;
  3583. end;
  3584. end;
  3585. { If the LEA instruction can be converted into an arithmetic instruction,
  3586. it may be possible to then fold it in the next optimisation, otherwise
  3587. there's nothing more that can be optimised here. }
  3588. if not ConvertLEA(taicpu(hp1)) then
  3589. Exit;
  3590. end;
  3591. if (taicpu(p).oper[1]^.typ = top_reg) and
  3592. (hp1.typ = ait_instruction) and
  3593. GetNextInstruction(hp1, hp2) and
  3594. MatchInstruction(hp2,A_MOV,[]) and
  3595. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3596. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3597. (
  3598. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3599. {$ifdef x86_64}
  3600. or
  3601. (
  3602. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3603. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3604. )
  3605. {$endif x86_64}
  3606. ) then
  3607. begin
  3608. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3609. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3610. { change movsX/movzX reg/ref, reg2
  3611. add/sub/or/... reg3/$const, reg2
  3612. mov reg2 reg/ref
  3613. dealloc reg2
  3614. to
  3615. add/sub/or/... reg3/$const, reg/ref }
  3616. begin
  3617. TransferUsedRegs(TmpUsedRegs);
  3618. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3619. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3620. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3621. begin
  3622. { by example:
  3623. movswl %si,%eax movswl %si,%eax p
  3624. decl %eax addl %edx,%eax hp1
  3625. movw %ax,%si movw %ax,%si hp2
  3626. ->
  3627. movswl %si,%eax movswl %si,%eax p
  3628. decw %eax addw %edx,%eax hp1
  3629. movw %ax,%si movw %ax,%si hp2
  3630. }
  3631. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3632. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3633. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3634. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3635. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3636. {
  3637. ->
  3638. movswl %si,%eax movswl %si,%eax p
  3639. decw %si addw %dx,%si hp1
  3640. movw %ax,%si movw %ax,%si hp2
  3641. }
  3642. case taicpu(hp1).ops of
  3643. 1:
  3644. begin
  3645. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3646. if taicpu(hp1).oper[0]^.typ=top_reg then
  3647. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3648. end;
  3649. 2:
  3650. begin
  3651. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3652. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3653. (taicpu(hp1).opcode<>A_SHL) and
  3654. (taicpu(hp1).opcode<>A_SHR) and
  3655. (taicpu(hp1).opcode<>A_SAR) then
  3656. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3657. end;
  3658. else
  3659. internalerror(2008042701);
  3660. end;
  3661. {
  3662. ->
  3663. decw %si addw %dx,%si p
  3664. }
  3665. RemoveInstruction(hp2);
  3666. RemoveCurrentP(p, hp1);
  3667. Result:=True;
  3668. Exit;
  3669. end;
  3670. end;
  3671. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3672. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3673. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3674. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3675. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3676. )
  3677. {$ifdef i386}
  3678. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3679. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3680. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3681. {$endif i386}
  3682. then
  3683. { change movsX/movzX reg/ref, reg2
  3684. add/sub/or/... regX/$const, reg2
  3685. mov reg2, reg3
  3686. dealloc reg2
  3687. to
  3688. movsX/movzX reg/ref, reg3
  3689. add/sub/or/... reg3/$const, reg3
  3690. }
  3691. begin
  3692. TransferUsedRegs(TmpUsedRegs);
  3693. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3694. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3695. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3696. begin
  3697. { by example:
  3698. movswl %si,%eax movswl %si,%eax p
  3699. decl %eax addl %edx,%eax hp1
  3700. movw %ax,%si movw %ax,%si hp2
  3701. ->
  3702. movswl %si,%eax movswl %si,%eax p
  3703. decw %eax addw %edx,%eax hp1
  3704. movw %ax,%si movw %ax,%si hp2
  3705. }
  3706. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3707. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3708. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3709. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3710. { limit size of constants as well to avoid assembler errors, but
  3711. check opsize to avoid overflow when left shifting the 1 }
  3712. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3713. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3714. {$ifdef x86_64}
  3715. { Be careful of, for example:
  3716. movl %reg1,%reg2
  3717. addl %reg3,%reg2
  3718. movq %reg2,%reg4
  3719. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3720. }
  3721. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3722. begin
  3723. taicpu(hp2).changeopsize(S_L);
  3724. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3725. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3726. end;
  3727. {$endif x86_64}
  3728. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3729. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3730. if taicpu(p).oper[0]^.typ=top_reg then
  3731. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3732. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3733. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3734. {
  3735. ->
  3736. movswl %si,%eax movswl %si,%eax p
  3737. decw %si addw %dx,%si hp1
  3738. movw %ax,%si movw %ax,%si hp2
  3739. }
  3740. case taicpu(hp1).ops of
  3741. 1:
  3742. begin
  3743. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3744. if taicpu(hp1).oper[0]^.typ=top_reg then
  3745. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3746. end;
  3747. 2:
  3748. begin
  3749. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3750. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3751. (taicpu(hp1).opcode<>A_SHL) and
  3752. (taicpu(hp1).opcode<>A_SHR) and
  3753. (taicpu(hp1).opcode<>A_SAR) then
  3754. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3755. end;
  3756. else
  3757. internalerror(2018111801);
  3758. end;
  3759. {
  3760. ->
  3761. decw %si addw %dx,%si p
  3762. }
  3763. RemoveInstruction(hp2);
  3764. end;
  3765. end;
  3766. end;
  3767. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3768. GetNextInstruction(hp1, hp2) and
  3769. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3770. MatchOperand(Taicpu(p).oper[0]^,0) and
  3771. (Taicpu(p).oper[1]^.typ = top_reg) and
  3772. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3773. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3774. { mov reg1,0
  3775. bts reg1,operand1 --> mov reg1,operand2
  3776. or reg1,operand2 bts reg1,operand1}
  3777. begin
  3778. Taicpu(hp2).opcode:=A_MOV;
  3779. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3780. asml.remove(hp1);
  3781. insertllitem(hp2,hp2.next,hp1);
  3782. RemoveCurrentp(p, hp1);
  3783. Result:=true;
  3784. exit;
  3785. end;
  3786. {
  3787. mov ref,reg0
  3788. <op> reg0,reg1
  3789. dealloc reg0
  3790. to
  3791. <op> ref,reg1
  3792. }
  3793. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3794. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3795. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3796. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3797. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3798. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3799. begin
  3800. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3801. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3802. RemoveCurrentp(p, hp1);
  3803. Result:=true;
  3804. exit;
  3805. end;
  3806. {$ifdef x86_64}
  3807. { Convert:
  3808. movq x(ref),%reg64
  3809. shrq y,%reg64
  3810. To:
  3811. movl x+4(ref),%reg32
  3812. shrl y-32,%reg32 (Remove if y = 32)
  3813. }
  3814. if (taicpu(p).opsize = S_Q) and
  3815. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3816. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3817. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3818. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3819. (taicpu(hp1).oper[0]^.val >= 32) and
  3820. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3821. begin
  3822. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3823. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3824. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3825. { Convert to 32-bit }
  3826. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3827. taicpu(p).opsize := S_L;
  3828. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3829. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3830. if (taicpu(hp1).oper[0]^.val = 32) then
  3831. begin
  3832. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3833. RemoveInstruction(hp1);
  3834. end
  3835. else
  3836. begin
  3837. { This will potentially open up more arithmetic operations since
  3838. the peephole optimizer now has a big hint that only the lower
  3839. 32 bits are currently in use (and opcodes are smaller in size) }
  3840. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3841. taicpu(hp1).opsize := S_L;
  3842. Dec(taicpu(hp1).oper[0]^.val, 32);
  3843. DebugMsg(SPeepholeOptimization + PreMessage +
  3844. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3845. end;
  3846. Result := True;
  3847. Exit;
  3848. end;
  3849. {$endif x86_64}
  3850. { Backward optimisation. If we have:
  3851. func. %reg1,%reg2
  3852. mov %reg2,%reg3
  3853. (dealloc %reg2)
  3854. Change to:
  3855. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3856. }
  3857. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3858. begin
  3859. CurrentReg := taicpu(p).oper[0]^.reg;
  3860. ActiveReg := taicpu(p).oper[1]^.reg;
  3861. TransferUsedRegs(TmpUsedRegs);
  3862. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3863. GetLastInstruction(p, hp2) and
  3864. (hp2.typ = ait_instruction) and
  3865. { Have to make sure it's an instruction that only reads from
  3866. operand 1 and only writes (not reads or modifies) from operand 2;
  3867. in essence, a one-operand pure function such as BSR or POPCNT }
  3868. (taicpu(hp2).ops = 2) and
  3869. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3870. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3871. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_FSTSW, A_FNSTSW,
  3875. A_IN, A_INS, A_OUT, A_OUTS,
  3876. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3877. { These routines have explicit operands, but they are restricted in
  3878. what they can be (e.g. IN and OUT can only read from AL, AX or
  3879. EAX. }
  3880. A_CMOVcc:
  3881. { CMOV is not valid either because then CurrentReg will depend
  3882. on an unknown value if the condition is False and hence is
  3883. not a pure write }
  3884. ;
  3885. else
  3886. begin
  3887. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3888. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3889. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3890. RemoveCurrentp(p, hp1);
  3891. Result := True;
  3892. Exit;
  3893. end;
  3894. end;
  3895. end;
  3896. end;
  3897. end;
  3898. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3899. var
  3900. hp1 : tai;
  3901. begin
  3902. Result:=false;
  3903. if taicpu(p).ops <> 2 then
  3904. exit;
  3905. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  3906. GetNextInstruction(p,hp1) then
  3907. begin
  3908. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3909. (taicpu(hp1).ops = 2) then
  3910. begin
  3911. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3912. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3913. { movXX reg1, mem1 or movXX mem1, reg1
  3914. movXX mem2, reg2 movXX reg2, mem2}
  3915. begin
  3916. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3917. { movXX reg1, mem1 or movXX mem1, reg1
  3918. movXX mem2, reg1 movXX reg2, mem1}
  3919. begin
  3920. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3921. begin
  3922. { Removes the second statement from
  3923. movXX reg1, mem1/reg2
  3924. movXX mem1/reg2, reg1
  3925. }
  3926. if taicpu(p).oper[0]^.typ=top_reg then
  3927. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3928. { Removes the second statement from
  3929. movXX mem1/reg1, reg2
  3930. movXX reg2, mem1/reg1
  3931. }
  3932. if (taicpu(p).oper[1]^.typ=top_reg) and
  3933. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3934. begin
  3935. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3936. RemoveInstruction(hp1);
  3937. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3938. Result:=true;
  3939. exit;
  3940. end
  3941. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  3942. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  3943. begin
  3944. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3945. RemoveInstruction(hp1);
  3946. Result:=true;
  3947. exit;
  3948. end;
  3949. end
  3950. end;
  3951. end;
  3952. end;
  3953. end;
  3954. end;
  3955. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3956. var
  3957. hp1 : tai;
  3958. begin
  3959. result:=false;
  3960. { replace
  3961. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3962. MovX %mreg2,%mreg1
  3963. dealloc %mreg2
  3964. by
  3965. <Op>X %mreg2,%mreg1
  3966. ?
  3967. }
  3968. if GetNextInstruction(p,hp1) and
  3969. { we mix single and double opperations here because we assume that the compiler
  3970. generates vmovapd only after double operations and vmovaps only after single operations }
  3971. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3973. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3974. (taicpu(p).oper[0]^.typ=top_reg) then
  3975. begin
  3976. TransferUsedRegs(TmpUsedRegs);
  3977. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3978. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3979. begin
  3980. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3981. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3982. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3983. RemoveInstruction(hp1);
  3984. result:=true;
  3985. end;
  3986. end;
  3987. end;
  3988. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3989. var
  3990. hp1, p_label, p_dist, hp1_dist: tai;
  3991. JumpLabel, JumpLabel_dist: TAsmLabel;
  3992. FirstValue, SecondValue: TCGInt;
  3993. begin
  3994. Result := False;
  3995. if (taicpu(p).oper[0]^.typ = top_const) and
  3996. (taicpu(p).oper[0]^.val <> -1) then
  3997. begin
  3998. { Convert unsigned maximum constants to -1 to aid optimisation }
  3999. case taicpu(p).opsize of
  4000. S_B:
  4001. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4002. begin
  4003. taicpu(p).oper[0]^.val := -1;
  4004. Result := True;
  4005. Exit;
  4006. end;
  4007. S_W:
  4008. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4009. begin
  4010. taicpu(p).oper[0]^.val := -1;
  4011. Result := True;
  4012. Exit;
  4013. end;
  4014. S_L:
  4015. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4016. begin
  4017. taicpu(p).oper[0]^.val := -1;
  4018. Result := True;
  4019. Exit;
  4020. end;
  4021. {$ifdef x86_64}
  4022. S_Q:
  4023. { Storing anything greater than $7FFFFFFF is not possible so do
  4024. nothing };
  4025. {$endif x86_64}
  4026. else
  4027. InternalError(2021121001);
  4028. end;
  4029. end;
  4030. if GetNextInstruction(p, hp1) and
  4031. TrySwapMovCmp(p, hp1) then
  4032. begin
  4033. Result := True;
  4034. Exit;
  4035. end;
  4036. { Search for:
  4037. test $x,(reg/ref)
  4038. jne @lbl1
  4039. test $y,(reg/ref) (same register or reference)
  4040. jne @lbl1
  4041. Change to:
  4042. test $(x or y),(reg/ref)
  4043. jne @lbl1
  4044. (Note, this doesn't work with je instead of jne)
  4045. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4046. Also search for:
  4047. test $x,(reg/ref)
  4048. je @lbl1
  4049. test $y,(reg/ref)
  4050. je/jne @lbl2
  4051. If (x or y) = x, then the second jump is deterministic
  4052. }
  4053. if (
  4054. (
  4055. (taicpu(p).oper[0]^.typ = top_const) or
  4056. (
  4057. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4058. (taicpu(p).oper[0]^.typ = top_reg) and
  4059. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4060. )
  4061. ) and
  4062. MatchInstruction(hp1, A_JCC, [])
  4063. ) then
  4064. begin
  4065. if (taicpu(p).oper[0]^.typ = top_reg) and
  4066. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4067. FirstValue := -1
  4068. else
  4069. FirstValue := taicpu(p).oper[0]^.val;
  4070. { If we have several test/jne's in a row, it might be the case that
  4071. the second label doesn't go to the same location, but the one
  4072. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4073. so accommodate for this with a while loop.
  4074. }
  4075. hp1_dist := hp1;
  4076. if GetNextInstruction(hp1, p_dist) and
  4077. (p_dist.typ = ait_instruction) and
  4078. (
  4079. (
  4080. (taicpu(p_dist).opcode = A_TEST) and
  4081. (
  4082. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4083. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4084. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4085. )
  4086. ) or
  4087. (
  4088. { cmp 0,%reg = test %reg,%reg }
  4089. (taicpu(p_dist).opcode = A_CMP) and
  4090. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4091. )
  4092. ) and
  4093. { Make sure the destination operands are actually the same }
  4094. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4095. GetNextInstruction(p_dist, hp1_dist) and
  4096. MatchInstruction(hp1_dist, A_JCC, []) then
  4097. begin
  4098. if
  4099. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4100. (
  4101. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4102. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4103. ) then
  4104. SecondValue := -1
  4105. else
  4106. SecondValue := taicpu(p_dist).oper[0]^.val;
  4107. { If both of the TEST constants are identical, delete the second
  4108. TEST that is unnecessary. }
  4109. if (FirstValue = SecondValue) then
  4110. begin
  4111. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4112. RemoveInstruction(p_dist);
  4113. { Don't let the flags register become deallocated and reallocated between the jumps }
  4114. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4115. Result := True;
  4116. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4117. begin
  4118. { Since the second jump's condition is a subset of the first, we
  4119. know it will never branch because the first jump dominates it.
  4120. Get it out of the way now rather than wait for the jump
  4121. optimisations for a speed boost. }
  4122. if IsJumpToLabel(taicpu(hp1_dist)) then
  4123. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4124. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4125. RemoveInstruction(hp1_dist);
  4126. end
  4127. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4128. begin
  4129. { If the inverse of the first condition is a subset of the second,
  4130. the second one will definitely branch if the first one doesn't }
  4131. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4132. MakeUnconditional(taicpu(hp1_dist));
  4133. RemoveDeadCodeAfterJump(hp1_dist);
  4134. end;
  4135. Exit;
  4136. end;
  4137. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4138. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4139. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4140. then the second jump will never branch, so it can also be
  4141. removed regardless of where it goes }
  4142. (
  4143. (FirstValue = -1) or
  4144. (SecondValue = -1) or
  4145. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4146. ) then
  4147. begin
  4148. { Same jump location... can be a register since nothing's changed }
  4149. { If any of the entries are equivalent to test %reg,%reg, then the
  4150. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4151. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4152. if IsJumpToLabel(taicpu(hp1_dist)) then
  4153. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4154. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4155. RemoveInstruction(hp1_dist);
  4156. { Only remove the second test if no jumps or other conditional instructions follow }
  4157. TransferUsedRegs(TmpUsedRegs);
  4158. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4159. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4160. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4161. RemoveInstruction(p_dist);
  4162. Result := True;
  4163. Exit;
  4164. end;
  4165. end;
  4166. end;
  4167. { Search for:
  4168. test %reg,%reg
  4169. j(c1) @lbl1
  4170. ...
  4171. @lbl:
  4172. test %reg,%reg (same register)
  4173. j(c2) @lbl2
  4174. If c2 is a subset of c1, change to:
  4175. test %reg,%reg
  4176. j(c1) @lbl2
  4177. (@lbl1 may become a dead label as a result)
  4178. }
  4179. if (taicpu(p).oper[1]^.typ = top_reg) and
  4180. (taicpu(p).oper[0]^.typ = top_reg) and
  4181. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4182. MatchInstruction(hp1, A_JCC, []) and
  4183. IsJumpToLabel(taicpu(hp1)) then
  4184. begin
  4185. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4186. p_label := nil;
  4187. if Assigned(JumpLabel) then
  4188. p_label := getlabelwithsym(JumpLabel);
  4189. if Assigned(p_label) and
  4190. GetNextInstruction(p_label, p_dist) and
  4191. MatchInstruction(p_dist, A_TEST, []) and
  4192. { It's fine if the second test uses smaller sub-registers }
  4193. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4194. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4195. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4196. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4197. GetNextInstruction(p_dist, hp1_dist) and
  4198. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4199. begin
  4200. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4201. if JumpLabel = JumpLabel_dist then
  4202. { This is an infinite loop }
  4203. Exit;
  4204. { Best optimisation when the first condition is a subset (or equal) of the second }
  4205. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4206. begin
  4207. { Any registers used here will already be allocated }
  4208. if Assigned(JumpLabel_dist) then
  4209. JumpLabel_dist.IncRefs;
  4210. if Assigned(JumpLabel) then
  4211. JumpLabel.DecRefs;
  4212. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4213. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4214. Result := True;
  4215. Exit;
  4216. end;
  4217. end;
  4218. end;
  4219. end;
  4220. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4221. var
  4222. hp1, hp2: tai;
  4223. ActiveReg: TRegister;
  4224. OldOffset: asizeint;
  4225. ThisConst: TCGInt;
  4226. function RegDeallocated: Boolean;
  4227. begin
  4228. TransferUsedRegs(TmpUsedRegs);
  4229. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4230. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4231. end;
  4232. begin
  4233. result:=false;
  4234. hp1 := nil;
  4235. { replace
  4236. addX const,%reg1
  4237. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4238. dealloc %reg1
  4239. by
  4240. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4241. }
  4242. if MatchOpType(taicpu(p),top_const,top_reg) then
  4243. begin
  4244. ActiveReg := taicpu(p).oper[1]^.reg;
  4245. { Ensures the entire register was updated }
  4246. if (taicpu(p).opsize >= S_L) and
  4247. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4248. MatchInstruction(hp1,A_LEA,[]) and
  4249. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4250. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4251. (
  4252. { Cover the case where the register in the reference is also the destination register }
  4253. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4254. (
  4255. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4256. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4257. RegDeallocated
  4258. )
  4259. ) then
  4260. begin
  4261. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4262. {$push}
  4263. {$R-}{$Q-}
  4264. { Explicitly disable overflow checking for these offset calculation
  4265. as those do not matter for the final result }
  4266. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4267. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4268. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4269. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4270. {$pop}
  4271. {$ifdef x86_64}
  4272. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4273. begin
  4274. { Overflow; abort }
  4275. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4276. end
  4277. else
  4278. {$endif x86_64}
  4279. begin
  4280. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4281. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4282. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4283. RemoveCurrentP(p, hp1)
  4284. else
  4285. RemoveCurrentP(p);
  4286. result:=true;
  4287. Exit;
  4288. end;
  4289. end;
  4290. if (
  4291. { Save calling GetNextInstructionUsingReg again }
  4292. Assigned(hp1) or
  4293. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4294. ) and
  4295. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4296. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4297. begin
  4298. if taicpu(hp1).oper[0]^.typ = top_const then
  4299. begin
  4300. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4301. if taicpu(hp1).opcode = A_ADD then
  4302. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4303. else
  4304. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4305. Result := True;
  4306. { Handle any overflows }
  4307. case taicpu(p).opsize of
  4308. S_B:
  4309. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4310. S_W:
  4311. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4312. S_L:
  4313. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4314. {$ifdef x86_64}
  4315. S_Q:
  4316. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4317. { Overflow; abort }
  4318. Result := False
  4319. else
  4320. taicpu(p).oper[0]^.val := ThisConst;
  4321. {$endif x86_64}
  4322. else
  4323. InternalError(2021102610);
  4324. end;
  4325. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4326. if Result then
  4327. begin
  4328. if (taicpu(p).oper[0]^.val < 0) and
  4329. (
  4330. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4331. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4332. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4333. ) then
  4334. begin
  4335. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4336. taicpu(p).opcode := A_SUB;
  4337. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4338. end
  4339. else
  4340. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4341. RemoveInstruction(hp1);
  4342. end;
  4343. end
  4344. else
  4345. begin
  4346. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4347. TransferUsedRegs(TmpUsedRegs);
  4348. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4349. hp2 := p;
  4350. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4351. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4352. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4353. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4354. begin
  4355. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4356. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4357. Asml.Remove(p);
  4358. Asml.InsertAfter(p, hp1);
  4359. p := hp1;
  4360. Result := True;
  4361. end;
  4362. end;
  4363. end;
  4364. end;
  4365. end;
  4366. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4367. var
  4368. hp1: tai;
  4369. ref: Integer;
  4370. saveref: treference;
  4371. TempReg: TRegister;
  4372. Multiple: TCGInt;
  4373. begin
  4374. Result:=false;
  4375. { removes seg register prefixes from LEA operations, as they
  4376. don't do anything}
  4377. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  4378. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4379. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4380. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4381. (
  4382. { do not mess with leas accessing the stack pointer
  4383. unless it's a null operation }
  4384. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4385. (
  4386. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4387. (taicpu(p).oper[0]^.ref^.offset = 0)
  4388. )
  4389. ) and
  4390. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4391. begin
  4392. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4393. begin
  4394. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4395. begin
  4396. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4397. taicpu(p).oper[1]^.reg);
  4398. InsertLLItem(p.previous,p.next, hp1);
  4399. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4400. p.free;
  4401. p:=hp1;
  4402. end
  4403. else
  4404. begin
  4405. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4406. RemoveCurrentP(p);
  4407. end;
  4408. Result:=true;
  4409. exit;
  4410. end
  4411. else if (
  4412. { continue to use lea to adjust the stack pointer,
  4413. it is the recommended way, but only if not optimizing for size }
  4414. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4415. (cs_opt_size in current_settings.optimizerswitches)
  4416. ) and
  4417. { If the flags register is in use, don't change the instruction
  4418. to an ADD otherwise this will scramble the flags. [Kit] }
  4419. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4420. ConvertLEA(taicpu(p)) then
  4421. begin
  4422. Result:=true;
  4423. exit;
  4424. end;
  4425. end;
  4426. if GetNextInstruction(p,hp1) and
  4427. (hp1.typ=ait_instruction) then
  4428. begin
  4429. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4430. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4431. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4432. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4433. begin
  4434. TransferUsedRegs(TmpUsedRegs);
  4435. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4436. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4437. begin
  4438. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4439. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4440. RemoveInstruction(hp1);
  4441. result:=true;
  4442. exit;
  4443. end;
  4444. end;
  4445. { changes
  4446. lea <ref1>, reg1
  4447. <op> ...,<ref. with reg1>,...
  4448. to
  4449. <op> ...,<ref1>,... }
  4450. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4451. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4452. not(MatchInstruction(hp1,A_LEA,[])) then
  4453. begin
  4454. { find a reference which uses reg1 }
  4455. 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
  4456. ref:=0
  4457. 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
  4458. ref:=1
  4459. else
  4460. ref:=-1;
  4461. if (ref<>-1) and
  4462. { reg1 must be either the base or the index }
  4463. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4464. begin
  4465. { reg1 can be removed from the reference }
  4466. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4467. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4468. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4469. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4470. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4471. else
  4472. Internalerror(2019111201);
  4473. { check if the can insert all data of the lea into the second instruction }
  4474. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4475. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4476. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4477. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4478. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4479. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4480. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4481. {$ifdef x86_64}
  4482. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4483. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4484. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4485. )
  4486. {$endif x86_64}
  4487. then
  4488. begin
  4489. { reg1 might not used by the second instruction after it is remove from the reference }
  4490. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4491. begin
  4492. TransferUsedRegs(TmpUsedRegs);
  4493. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4494. { reg1 is not updated so it might not be used afterwards }
  4495. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4496. begin
  4497. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4498. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4499. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4500. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4501. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4502. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4503. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4504. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4505. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4506. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4507. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4508. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4509. RemoveCurrentP(p, hp1);
  4510. result:=true;
  4511. exit;
  4512. end
  4513. end;
  4514. end;
  4515. { recover }
  4516. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4517. end;
  4518. end;
  4519. end;
  4520. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4521. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4522. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4523. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4524. begin
  4525. { Check common LEA/LEA conditions }
  4526. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4527. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4528. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4529. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4530. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4531. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4532. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4533. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4534. (
  4535. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4536. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4537. ) and (
  4538. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4539. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4540. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4541. ) then
  4542. begin
  4543. { changes
  4544. lea (regX,scale), reg1
  4545. lea offset(reg1,reg1), reg1
  4546. to
  4547. lea offset(regX,scale*2), reg1
  4548. and
  4549. lea (regX,scale1), reg1
  4550. lea offset(reg1,scale2), reg1
  4551. to
  4552. lea offset(regX,scale1*scale2), reg1
  4553. ... so long as the final scale does not exceed 8
  4554. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4555. }
  4556. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4557. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4558. (
  4559. (
  4560. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4561. ) or (
  4562. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4563. (
  4564. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4565. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4566. )
  4567. )
  4568. ) and (
  4569. (
  4570. { lea (reg1,scale2), reg1 variant }
  4571. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4572. (
  4573. (
  4574. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4575. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4576. ) or (
  4577. { lea (regX,regX), reg1 variant }
  4578. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4579. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4580. )
  4581. )
  4582. ) or (
  4583. { lea (reg1,reg1), reg1 variant }
  4584. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4585. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4586. )
  4587. ) then
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4590. { Make everything homogeneous to make calculations easier }
  4591. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4592. begin
  4593. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4594. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4595. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4596. else
  4597. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4598. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4599. end;
  4600. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4601. begin
  4602. { Just to prevent miscalculations }
  4603. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4604. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4605. else
  4606. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4607. end
  4608. else
  4609. begin
  4610. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4611. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4612. end;
  4613. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4614. RemoveCurrentP(p);
  4615. result:=true;
  4616. exit;
  4617. end
  4618. { changes
  4619. lea offset1(regX), reg1
  4620. lea offset2(reg1), reg1
  4621. to
  4622. lea offset1+offset2(regX), reg1 }
  4623. else if
  4624. (
  4625. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4626. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4627. ) or (
  4628. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4629. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4630. (
  4631. (
  4632. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4633. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4634. ) or (
  4635. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4636. (
  4637. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4638. (
  4639. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4640. (
  4641. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4642. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4643. )
  4644. )
  4645. )
  4646. )
  4647. )
  4648. ) then
  4649. begin
  4650. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4651. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4652. begin
  4653. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4654. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4655. { if the register is used as index and base, we have to increase for base as well
  4656. and adapt base }
  4657. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4658. begin
  4659. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4660. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4661. end;
  4662. end
  4663. else
  4664. begin
  4665. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4666. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4667. end;
  4668. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4669. begin
  4670. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4671. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4672. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4673. end;
  4674. RemoveCurrentP(p);
  4675. result:=true;
  4676. exit;
  4677. end;
  4678. end;
  4679. { Change:
  4680. leal/q $x(%reg1),%reg2
  4681. ...
  4682. shll/q $y,%reg2
  4683. To:
  4684. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4685. }
  4686. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4687. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4688. (taicpu(hp1).oper[0]^.val <= 3) then
  4689. begin
  4690. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4691. TransferUsedRegs(TmpUsedRegs);
  4692. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4693. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4694. if
  4695. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4696. (this works even if scalefactor is zero) }
  4697. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4698. { Ensure offset doesn't go out of bounds }
  4699. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4700. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4701. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4702. (
  4703. (
  4704. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4705. (
  4706. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4707. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4708. (
  4709. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4710. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4711. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4712. )
  4713. )
  4714. ) or (
  4715. (
  4716. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4717. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4718. ) and
  4719. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4720. )
  4721. ) then
  4722. begin
  4723. repeat
  4724. with taicpu(p).oper[0]^.ref^ do
  4725. begin
  4726. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4727. if index = base then
  4728. begin
  4729. if Multiple > 4 then
  4730. { Optimisation will no longer work because resultant
  4731. scale factor will exceed 8 }
  4732. Break;
  4733. base := NR_NO;
  4734. scalefactor := 2;
  4735. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4736. end
  4737. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4738. begin
  4739. { Scale factor only works on the index register }
  4740. index := base;
  4741. base := NR_NO;
  4742. end;
  4743. { For safety }
  4744. if scalefactor <= 1 then
  4745. begin
  4746. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4747. scalefactor := Multiple;
  4748. end
  4749. else
  4750. begin
  4751. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4752. scalefactor := scalefactor * Multiple;
  4753. end;
  4754. offset := offset * Multiple;
  4755. end;
  4756. RemoveInstruction(hp1);
  4757. Result := True;
  4758. Exit;
  4759. { This repeat..until loop exists for the benefit of Break }
  4760. until True;
  4761. end;
  4762. end;
  4763. end;
  4764. end;
  4765. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4766. var
  4767. hp1 : tai;
  4768. begin
  4769. DoSubAddOpt := False;
  4770. if taicpu(p).oper[0]^.typ <> top_const then
  4771. { Should have been confirmed before calling }
  4772. InternalError(2021102601);
  4773. if GetLastInstruction(p, hp1) and
  4774. (hp1.typ = ait_instruction) and
  4775. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4776. case taicpu(hp1).opcode Of
  4777. A_DEC:
  4778. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4779. begin
  4780. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4781. RemoveInstruction(hp1);
  4782. end;
  4783. A_SUB:
  4784. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4785. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4786. begin
  4787. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4788. RemoveInstruction(hp1);
  4789. end;
  4790. A_ADD:
  4791. begin
  4792. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4793. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4794. begin
  4795. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4796. RemoveInstruction(hp1);
  4797. if (taicpu(p).oper[0]^.val = 0) then
  4798. begin
  4799. hp1 := tai(p.next);
  4800. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4801. if not GetLastInstruction(hp1, p) then
  4802. p := hp1;
  4803. DoSubAddOpt := True;
  4804. end
  4805. end;
  4806. end;
  4807. else
  4808. ;
  4809. end;
  4810. end;
  4811. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4812. begin
  4813. Result := False;
  4814. if UpdateTmpUsedRegs then
  4815. TransferUsedRegs(TmpUsedRegs);
  4816. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4817. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4818. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4819. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4820. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4821. (
  4822. (
  4823. (taicpu(hp1).opcode = A_TEST)
  4824. ) or (
  4825. (taicpu(hp1).opcode = A_CMP) and
  4826. { A sanity check more than anything }
  4827. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4828. )
  4829. ) then
  4830. begin
  4831. { change
  4832. mov mem, %reg
  4833. cmp/test x, %reg / test %reg,%reg
  4834. (reg deallocated)
  4835. to
  4836. cmp/test x, mem / cmp 0, mem
  4837. }
  4838. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4839. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4840. begin
  4841. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4842. if (taicpu(hp1).opcode = A_TEST) and
  4843. (
  4844. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4845. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4846. ) then
  4847. begin
  4848. taicpu(hp1).opcode := A_CMP;
  4849. taicpu(hp1).loadconst(0, 0);
  4850. end;
  4851. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4852. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4853. RemoveCurrentP(p, hp1);
  4854. Result := True;
  4855. Exit;
  4856. end;
  4857. end;
  4858. end;
  4859. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4860. var
  4861. hp1, hp2: tai;
  4862. ActiveReg: TRegister;
  4863. OldOffset: asizeint;
  4864. ThisConst: TCGInt;
  4865. function RegDeallocated: Boolean;
  4866. begin
  4867. TransferUsedRegs(TmpUsedRegs);
  4868. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4869. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4870. end;
  4871. begin
  4872. Result:=false;
  4873. hp1 := nil;
  4874. { replace
  4875. subX const,%reg1
  4876. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4877. dealloc %reg1
  4878. by
  4879. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  4880. }
  4881. if MatchOpType(taicpu(p),top_const,top_reg) then
  4882. begin
  4883. ActiveReg := taicpu(p).oper[1]^.reg;
  4884. { Ensures the entire register was updated }
  4885. if (taicpu(p).opsize >= S_L) and
  4886. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4887. MatchInstruction(hp1,A_LEA,[]) and
  4888. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4889. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4890. (
  4891. { Cover the case where the register in the reference is also the destination register }
  4892. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4893. (
  4894. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4895. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4896. RegDeallocated
  4897. )
  4898. ) then
  4899. begin
  4900. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4901. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4902. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4903. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4904. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4905. {$ifdef x86_64}
  4906. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4907. begin
  4908. { Overflow; abort }
  4909. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4910. end
  4911. else
  4912. {$endif x86_64}
  4913. begin
  4914. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  4915. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4916. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4917. RemoveCurrentP(p, hp1)
  4918. else
  4919. RemoveCurrentP(p);
  4920. result:=true;
  4921. Exit;
  4922. end;
  4923. end;
  4924. if (
  4925. { Save calling GetNextInstructionUsingReg again }
  4926. Assigned(hp1) or
  4927. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4928. ) and
  4929. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  4930. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4931. begin
  4932. if taicpu(hp1).oper[0]^.typ = top_const then
  4933. begin
  4934. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  4935. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  4936. Result := True;
  4937. { Handle any overflows }
  4938. case taicpu(p).opsize of
  4939. S_B:
  4940. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4941. S_W:
  4942. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4943. S_L:
  4944. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4945. {$ifdef x86_64}
  4946. S_Q:
  4947. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4948. { Overflow; abort }
  4949. Result := False
  4950. else
  4951. taicpu(p).oper[0]^.val := ThisConst;
  4952. {$endif x86_64}
  4953. else
  4954. InternalError(2021102610);
  4955. end;
  4956. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4957. if Result then
  4958. begin
  4959. if (taicpu(p).oper[0]^.val < 0) and
  4960. (
  4961. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4962. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4963. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4964. ) then
  4965. begin
  4966. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  4967. taicpu(p).opcode := A_SUB;
  4968. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4969. end
  4970. else
  4971. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  4972. RemoveInstruction(hp1);
  4973. end;
  4974. end
  4975. else
  4976. begin
  4977. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  4978. TransferUsedRegs(TmpUsedRegs);
  4979. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4980. hp2 := p;
  4981. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4982. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4983. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4984. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4985. begin
  4986. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  4987. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  4988. Asml.Remove(p);
  4989. Asml.InsertAfter(p, hp1);
  4990. p := hp1;
  4991. Result := True;
  4992. Exit;
  4993. end;
  4994. end;
  4995. end;
  4996. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4997. { * change "sub/add const1, reg" or "dec reg" followed by
  4998. "sub const2, reg" to one "sub ..., reg" }
  4999. {$ifdef i386}
  5000. if (taicpu(p).oper[0]^.val = 2) and
  5001. (ActiveReg = NR_ESP) and
  5002. { Don't do the sub/push optimization if the sub }
  5003. { comes from setting up the stack frame (JM) }
  5004. (not(GetLastInstruction(p,hp1)) or
  5005. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5006. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5007. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5008. begin
  5009. hp1 := tai(p.next);
  5010. while Assigned(hp1) and
  5011. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5012. not RegReadByInstruction(NR_ESP,hp1) and
  5013. not RegModifiedByInstruction(NR_ESP,hp1) do
  5014. hp1 := tai(hp1.next);
  5015. if Assigned(hp1) and
  5016. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5017. begin
  5018. taicpu(hp1).changeopsize(S_L);
  5019. if taicpu(hp1).oper[0]^.typ=top_reg then
  5020. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5021. hp1 := tai(p.next);
  5022. RemoveCurrentp(p, hp1);
  5023. Result:=true;
  5024. exit;
  5025. end;
  5026. end;
  5027. {$endif i386}
  5028. if DoSubAddOpt(p) then
  5029. Result:=true;
  5030. end;
  5031. end;
  5032. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5033. var
  5034. TmpBool1,TmpBool2 : Boolean;
  5035. tmpref : treference;
  5036. hp1,hp2: tai;
  5037. mask: tcgint;
  5038. begin
  5039. Result:=false;
  5040. { All these optimisations work on "shl/sal const,%reg" }
  5041. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5042. Exit;
  5043. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5044. (taicpu(p).oper[0]^.val <= 3) then
  5045. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5046. begin
  5047. { should we check the next instruction? }
  5048. TmpBool1 := True;
  5049. { have we found an add/sub which could be
  5050. integrated in the lea? }
  5051. TmpBool2 := False;
  5052. reference_reset(tmpref,2,[]);
  5053. TmpRef.index := taicpu(p).oper[1]^.reg;
  5054. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5055. while TmpBool1 and
  5056. GetNextInstruction(p, hp1) and
  5057. (tai(hp1).typ = ait_instruction) and
  5058. ((((taicpu(hp1).opcode = A_ADD) or
  5059. (taicpu(hp1).opcode = A_SUB)) and
  5060. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5061. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5062. (((taicpu(hp1).opcode = A_INC) or
  5063. (taicpu(hp1).opcode = A_DEC)) and
  5064. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5065. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5066. ((taicpu(hp1).opcode = A_LEA) and
  5067. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5068. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5069. (not GetNextInstruction(hp1,hp2) or
  5070. not instrReadsFlags(hp2)) Do
  5071. begin
  5072. TmpBool1 := False;
  5073. if taicpu(hp1).opcode=A_LEA then
  5074. begin
  5075. if (TmpRef.base = NR_NO) and
  5076. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5077. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5078. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  5079. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5080. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5081. begin
  5082. TmpBool1 := True;
  5083. TmpBool2 := True;
  5084. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5085. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5086. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5087. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5088. RemoveInstruction(hp1);
  5089. end
  5090. end
  5091. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5092. begin
  5093. TmpBool1 := True;
  5094. TmpBool2 := True;
  5095. case taicpu(hp1).opcode of
  5096. A_ADD:
  5097. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5098. A_SUB:
  5099. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5100. else
  5101. internalerror(2019050536);
  5102. end;
  5103. RemoveInstruction(hp1);
  5104. end
  5105. else
  5106. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5107. (((taicpu(hp1).opcode = A_ADD) and
  5108. (TmpRef.base = NR_NO)) or
  5109. (taicpu(hp1).opcode = A_INC) or
  5110. (taicpu(hp1).opcode = A_DEC)) then
  5111. begin
  5112. TmpBool1 := True;
  5113. TmpBool2 := True;
  5114. case taicpu(hp1).opcode of
  5115. A_ADD:
  5116. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5117. A_INC:
  5118. inc(TmpRef.offset);
  5119. A_DEC:
  5120. dec(TmpRef.offset);
  5121. else
  5122. internalerror(2019050535);
  5123. end;
  5124. RemoveInstruction(hp1);
  5125. end;
  5126. end;
  5127. if TmpBool2
  5128. {$ifndef x86_64}
  5129. or
  5130. ((current_settings.optimizecputype < cpu_Pentium2) and
  5131. (taicpu(p).oper[0]^.val <= 3) and
  5132. not(cs_opt_size in current_settings.optimizerswitches))
  5133. {$endif x86_64}
  5134. then
  5135. begin
  5136. if not(TmpBool2) and
  5137. (taicpu(p).oper[0]^.val=1) then
  5138. begin
  5139. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5140. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5141. end
  5142. else
  5143. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5144. taicpu(p).oper[1]^.reg);
  5145. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5146. InsertLLItem(p.previous, p.next, hp1);
  5147. p.free;
  5148. p := hp1;
  5149. end;
  5150. end
  5151. {$ifndef x86_64}
  5152. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5153. begin
  5154. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5155. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5156. (unlike shl, which is only Tairable in the U pipe) }
  5157. if taicpu(p).oper[0]^.val=1 then
  5158. begin
  5159. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5160. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5161. InsertLLItem(p.previous, p.next, hp1);
  5162. p.free;
  5163. p := hp1;
  5164. end
  5165. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5166. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5167. else if (taicpu(p).opsize = S_L) and
  5168. (taicpu(p).oper[0]^.val<= 3) then
  5169. begin
  5170. reference_reset(tmpref,2,[]);
  5171. TmpRef.index := taicpu(p).oper[1]^.reg;
  5172. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5173. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5174. InsertLLItem(p.previous, p.next, hp1);
  5175. p.free;
  5176. p := hp1;
  5177. end;
  5178. end
  5179. {$endif x86_64}
  5180. else if
  5181. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5182. (
  5183. (
  5184. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5185. SetAndTest(hp1, hp2)
  5186. {$ifdef x86_64}
  5187. ) or
  5188. (
  5189. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5190. GetNextInstruction(hp1, hp2) and
  5191. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5192. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5193. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5194. {$endif x86_64}
  5195. )
  5196. ) and
  5197. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5198. begin
  5199. { Change:
  5200. shl x, %reg1
  5201. mov -(1<<x), %reg2
  5202. and %reg2, %reg1
  5203. Or:
  5204. shl x, %reg1
  5205. and -(1<<x), %reg1
  5206. To just:
  5207. shl x, %reg1
  5208. Since the and operation only zeroes bits that are already zero from the shl operation
  5209. }
  5210. case taicpu(p).oper[0]^.val of
  5211. 8:
  5212. mask:=$FFFFFFFFFFFFFF00;
  5213. 16:
  5214. mask:=$FFFFFFFFFFFF0000;
  5215. 32:
  5216. mask:=$FFFFFFFF00000000;
  5217. 63:
  5218. { Constant pre-calculated to prevent overflow errors with Int64 }
  5219. mask:=$8000000000000000;
  5220. else
  5221. begin
  5222. if taicpu(p).oper[0]^.val >= 64 then
  5223. { Shouldn't happen realistically, since the register
  5224. is guaranteed to be set to zero at this point }
  5225. mask := 0
  5226. else
  5227. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5228. end;
  5229. end;
  5230. if taicpu(hp1).oper[0]^.val = mask then
  5231. begin
  5232. { Everything checks out, perform the optimisation, as long as
  5233. the FLAGS register isn't being used}
  5234. TransferUsedRegs(TmpUsedRegs);
  5235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5236. {$ifdef x86_64}
  5237. if (hp1 <> hp2) then
  5238. begin
  5239. { "shl/mov/and" version }
  5240. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5241. { Don't do the optimisation if the FLAGS register is in use }
  5242. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5243. begin
  5244. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5245. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5246. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5247. begin
  5248. RemoveInstruction(hp1);
  5249. Result := True;
  5250. end;
  5251. { Only set Result to True if the 'mov' instruction was removed }
  5252. RemoveInstruction(hp2);
  5253. end;
  5254. end
  5255. else
  5256. {$endif x86_64}
  5257. begin
  5258. { "shl/and" version }
  5259. { Don't do the optimisation if the FLAGS register is in use }
  5260. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5261. begin
  5262. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5263. RemoveInstruction(hp1);
  5264. Result := True;
  5265. end;
  5266. end;
  5267. Exit;
  5268. end
  5269. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5270. begin
  5271. { Even if the mask doesn't allow for its removal, we might be
  5272. able to optimise the mask for the "shl/and" version, which
  5273. may permit other peephole optimisations }
  5274. {$ifdef DEBUG_AOPTCPU}
  5275. mask := taicpu(hp1).oper[0]^.val and mask;
  5276. if taicpu(hp1).oper[0]^.val <> mask then
  5277. begin
  5278. DebugMsg(
  5279. SPeepholeOptimization +
  5280. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5281. ' to $' + debug_tostr(mask) +
  5282. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5283. taicpu(hp1).oper[0]^.val := mask;
  5284. end;
  5285. {$else DEBUG_AOPTCPU}
  5286. { If debugging is off, just set the operand even if it's the same }
  5287. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5288. {$endif DEBUG_AOPTCPU}
  5289. end;
  5290. end;
  5291. {
  5292. change
  5293. shl/sal const,reg
  5294. <op> ...(...,reg,1),...
  5295. into
  5296. <op> ...(...,reg,1 shl const),...
  5297. if const in 1..3
  5298. }
  5299. if MatchOpType(taicpu(p), top_const, top_reg) and
  5300. (taicpu(p).oper[0]^.val in [1..3]) and
  5301. GetNextInstruction(p, hp1) and
  5302. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5303. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5304. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5305. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5306. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5307. begin
  5308. TransferUsedRegs(TmpUsedRegs);
  5309. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5310. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5311. begin
  5312. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5313. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5314. RemoveCurrentP(p);
  5315. Result:=true;
  5316. end;
  5317. end;
  5318. end;
  5319. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5320. var
  5321. CurrentRef: TReference;
  5322. FullReg: TRegister;
  5323. hp1, hp2: tai;
  5324. begin
  5325. Result := False;
  5326. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5327. Exit;
  5328. { We assume you've checked if the operand is actually a reference by
  5329. this point. If it isn't, you'll most likely get an access violation }
  5330. CurrentRef := first_mov.oper[1]^.ref^;
  5331. { Memory must be aligned }
  5332. if (CurrentRef.offset mod 4) <> 0 then
  5333. Exit;
  5334. Inc(CurrentRef.offset);
  5335. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5336. if MatchOperand(second_mov.oper[0]^, 0) and
  5337. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5338. GetNextInstruction(second_mov, hp1) and
  5339. (hp1.typ = ait_instruction) and
  5340. (taicpu(hp1).opcode = A_MOV) and
  5341. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5342. (taicpu(hp1).oper[0]^.val = 0) then
  5343. begin
  5344. Inc(CurrentRef.offset);
  5345. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5346. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5347. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5348. begin
  5349. case taicpu(hp1).opsize of
  5350. S_B:
  5351. if GetNextInstruction(hp1, hp2) and
  5352. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5353. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5354. (taicpu(hp2).oper[0]^.val = 0) then
  5355. begin
  5356. Inc(CurrentRef.offset);
  5357. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5358. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5359. (taicpu(hp2).opsize = S_B) then
  5360. begin
  5361. RemoveInstruction(hp1);
  5362. RemoveInstruction(hp2);
  5363. first_mov.opsize := S_L;
  5364. if first_mov.oper[0]^.typ = top_reg then
  5365. begin
  5366. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5367. { Reuse second_mov as a MOVZX instruction }
  5368. second_mov.opcode := A_MOVZX;
  5369. second_mov.opsize := S_BL;
  5370. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5371. second_mov.loadreg(1, FullReg);
  5372. first_mov.oper[0]^.reg := FullReg;
  5373. asml.Remove(second_mov);
  5374. asml.InsertBefore(second_mov, first_mov);
  5375. end
  5376. else
  5377. { It's a value }
  5378. begin
  5379. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5380. RemoveInstruction(second_mov);
  5381. end;
  5382. Result := True;
  5383. Exit;
  5384. end;
  5385. end;
  5386. S_W:
  5387. begin
  5388. RemoveInstruction(hp1);
  5389. first_mov.opsize := S_L;
  5390. if first_mov.oper[0]^.typ = top_reg then
  5391. begin
  5392. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5393. { Reuse second_mov as a MOVZX instruction }
  5394. second_mov.opcode := A_MOVZX;
  5395. second_mov.opsize := S_BL;
  5396. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5397. second_mov.loadreg(1, FullReg);
  5398. first_mov.oper[0]^.reg := FullReg;
  5399. asml.Remove(second_mov);
  5400. asml.InsertBefore(second_mov, first_mov);
  5401. end
  5402. else
  5403. { It's a value }
  5404. begin
  5405. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5406. RemoveInstruction(second_mov);
  5407. end;
  5408. Result := True;
  5409. Exit;
  5410. end;
  5411. else
  5412. ;
  5413. end;
  5414. end;
  5415. end;
  5416. end;
  5417. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5418. { returns true if a "continue" should be done after this optimization }
  5419. var
  5420. hp1, hp2: tai;
  5421. begin
  5422. Result := false;
  5423. if MatchOpType(taicpu(p),top_ref) and
  5424. GetNextInstruction(p, hp1) and
  5425. (hp1.typ = ait_instruction) and
  5426. (((taicpu(hp1).opcode = A_FLD) and
  5427. (taicpu(p).opcode = A_FSTP)) or
  5428. ((taicpu(p).opcode = A_FISTP) and
  5429. (taicpu(hp1).opcode = A_FILD))) and
  5430. MatchOpType(taicpu(hp1),top_ref) and
  5431. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5432. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5433. begin
  5434. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5435. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5436. GetNextInstruction(hp1, hp2) and
  5437. (hp2.typ = ait_instruction) and
  5438. IsExitCode(hp2) and
  5439. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5440. not(assigned(current_procinfo.procdef.funcretsym) and
  5441. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5442. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5443. begin
  5444. RemoveInstruction(hp1);
  5445. RemoveCurrentP(p, hp2);
  5446. RemoveLastDeallocForFuncRes(p);
  5447. Result := true;
  5448. end
  5449. else
  5450. { we can do this only in fast math mode as fstp is rounding ...
  5451. ... still disabled as it breaks the compiler and/or rtl }
  5452. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5453. { ... or if another fstp equal to the first one follows }
  5454. (GetNextInstruction(hp1,hp2) and
  5455. (hp2.typ = ait_instruction) and
  5456. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5457. (taicpu(p).opsize=taicpu(hp2).opsize))
  5458. ) and
  5459. { fst can't store an extended/comp value }
  5460. (taicpu(p).opsize <> S_FX) and
  5461. (taicpu(p).opsize <> S_IQ) then
  5462. begin
  5463. if (taicpu(p).opcode = A_FSTP) then
  5464. taicpu(p).opcode := A_FST
  5465. else
  5466. taicpu(p).opcode := A_FIST;
  5467. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5468. RemoveInstruction(hp1);
  5469. end;
  5470. end;
  5471. end;
  5472. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5473. var
  5474. hp1, hp2: tai;
  5475. begin
  5476. result:=false;
  5477. if MatchOpType(taicpu(p),top_reg) and
  5478. GetNextInstruction(p, hp1) and
  5479. (hp1.typ = Ait_Instruction) and
  5480. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5481. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5482. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5483. { change to
  5484. fld reg fxxx reg,st
  5485. fxxxp st, st1 (hp1)
  5486. Remark: non commutative operations must be reversed!
  5487. }
  5488. begin
  5489. case taicpu(hp1).opcode Of
  5490. A_FMULP,A_FADDP,
  5491. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5492. begin
  5493. case taicpu(hp1).opcode Of
  5494. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5495. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5496. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5497. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5498. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5499. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5500. else
  5501. internalerror(2019050534);
  5502. end;
  5503. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5504. taicpu(hp1).oper[1]^.reg := NR_ST;
  5505. RemoveCurrentP(p, hp1);
  5506. Result:=true;
  5507. exit;
  5508. end;
  5509. else
  5510. ;
  5511. end;
  5512. end
  5513. else
  5514. if MatchOpType(taicpu(p),top_ref) and
  5515. GetNextInstruction(p, hp2) and
  5516. (hp2.typ = Ait_Instruction) and
  5517. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5518. (taicpu(p).opsize in [S_FS, S_FL]) and
  5519. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5520. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5521. if GetLastInstruction(p, hp1) and
  5522. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5523. MatchOpType(taicpu(hp1),top_ref) and
  5524. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5525. if ((taicpu(hp2).opcode = A_FMULP) or
  5526. (taicpu(hp2).opcode = A_FADDP)) then
  5527. { change to
  5528. fld/fst mem1 (hp1) fld/fst mem1
  5529. fld mem1 (p) fadd/
  5530. faddp/ fmul st, st
  5531. fmulp st, st1 (hp2) }
  5532. begin
  5533. RemoveCurrentP(p, hp1);
  5534. if (taicpu(hp2).opcode = A_FADDP) then
  5535. taicpu(hp2).opcode := A_FADD
  5536. else
  5537. taicpu(hp2).opcode := A_FMUL;
  5538. taicpu(hp2).oper[1]^.reg := NR_ST;
  5539. end
  5540. else
  5541. { change to
  5542. fld/fst mem1 (hp1) fld/fst mem1
  5543. fld mem1 (p) fld st}
  5544. begin
  5545. taicpu(p).changeopsize(S_FL);
  5546. taicpu(p).loadreg(0,NR_ST);
  5547. end
  5548. else
  5549. begin
  5550. case taicpu(hp2).opcode Of
  5551. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5552. { change to
  5553. fld/fst mem1 (hp1) fld/fst mem1
  5554. fld mem2 (p) fxxx mem2
  5555. fxxxp st, st1 (hp2) }
  5556. begin
  5557. case taicpu(hp2).opcode Of
  5558. A_FADDP: taicpu(p).opcode := A_FADD;
  5559. A_FMULP: taicpu(p).opcode := A_FMUL;
  5560. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5561. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5562. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5563. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5564. else
  5565. internalerror(2019050533);
  5566. end;
  5567. RemoveInstruction(hp2);
  5568. end
  5569. else
  5570. ;
  5571. end
  5572. end
  5573. end;
  5574. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5575. begin
  5576. Result := condition_in(cond1, cond2) or
  5577. { Not strictly subsets due to the actual flags checked, but because we're
  5578. comparing integers, E is a subset of AE and GE and their aliases }
  5579. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5580. end;
  5581. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5582. var
  5583. v: TCGInt;
  5584. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5585. FirstMatch: Boolean;
  5586. NewReg: TRegister;
  5587. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5588. begin
  5589. Result:=false;
  5590. { All these optimisations need a next instruction }
  5591. if not GetNextInstruction(p, hp1) then
  5592. Exit;
  5593. { Search for:
  5594. cmp ###,###
  5595. j(c1) @lbl1
  5596. ...
  5597. @lbl:
  5598. cmp ###.### (same comparison as above)
  5599. j(c2) @lbl2
  5600. If c1 is a subset of c2, change to:
  5601. cmp ###,###
  5602. j(c2) @lbl2
  5603. (@lbl1 may become a dead label as a result)
  5604. }
  5605. { Also handle cases where there are multiple jumps in a row }
  5606. p_jump := hp1;
  5607. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5608. begin
  5609. if IsJumpToLabel(taicpu(p_jump)) then
  5610. begin
  5611. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5612. p_label := nil;
  5613. if Assigned(JumpLabel) then
  5614. p_label := getlabelwithsym(JumpLabel);
  5615. if Assigned(p_label) and
  5616. GetNextInstruction(p_label, p_dist) and
  5617. MatchInstruction(p_dist, A_CMP, []) and
  5618. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5619. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5620. GetNextInstruction(p_dist, hp1_dist) and
  5621. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5622. begin
  5623. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5624. if JumpLabel = JumpLabel_dist then
  5625. { This is an infinite loop }
  5626. Exit;
  5627. { Best optimisation when the first condition is a subset (or equal) of the second }
  5628. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5629. begin
  5630. { Any registers used here will already be allocated }
  5631. if Assigned(JumpLabel_dist) then
  5632. JumpLabel_dist.IncRefs;
  5633. if Assigned(JumpLabel) then
  5634. JumpLabel.DecRefs;
  5635. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5636. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5637. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5638. Result := True;
  5639. { Don't exit yet. Since p and p_jump haven't actually been
  5640. removed, we can check for more on this iteration }
  5641. end
  5642. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5643. GetNextInstruction(hp1_dist, hp1_label) and
  5644. SkipAligns(hp1_label, hp1_label) and
  5645. (hp1_label.typ = ait_label) then
  5646. begin
  5647. JumpLabel_far := tai_label(hp1_label).labsym;
  5648. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5649. { This is an infinite loop }
  5650. Exit;
  5651. if Assigned(JumpLabel_far) then
  5652. begin
  5653. { In this situation, if the first jump branches, the second one will never,
  5654. branch so change the destination label to after the second jump }
  5655. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5656. if Assigned(JumpLabel) then
  5657. JumpLabel.DecRefs;
  5658. JumpLabel_far.IncRefs;
  5659. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5660. Result := True;
  5661. { Don't exit yet. Since p and p_jump haven't actually been
  5662. removed, we can check for more on this iteration }
  5663. Continue;
  5664. end;
  5665. end;
  5666. end;
  5667. end;
  5668. { Search for:
  5669. cmp ###,###
  5670. j(c1) @lbl1
  5671. cmp ###,### (same as first)
  5672. Remove second cmp
  5673. }
  5674. if GetNextInstruction(p_jump, hp2) and
  5675. (
  5676. (
  5677. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5678. (
  5679. (
  5680. MatchOpType(taicpu(p), top_const, top_reg) and
  5681. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5682. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5683. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5684. ) or (
  5685. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5686. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5687. )
  5688. )
  5689. ) or (
  5690. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5691. MatchOperand(taicpu(p).oper[0]^, 0) and
  5692. (taicpu(p).oper[1]^.typ = top_reg) and
  5693. MatchInstruction(hp2, A_TEST, []) and
  5694. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5695. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5696. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5697. )
  5698. ) then
  5699. begin
  5700. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5701. RemoveInstruction(hp2);
  5702. Result := True;
  5703. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5704. end;
  5705. GetNextInstruction(p_jump, p_jump);
  5706. end;
  5707. {
  5708. Try to optimise the following:
  5709. cmp $x,### ($x and $y can be registers or constants)
  5710. je @lbl1 (only reference)
  5711. cmp $y,### (### are identical)
  5712. @Lbl:
  5713. sete %reg1
  5714. Change to:
  5715. cmp $x,###
  5716. sete %reg2 (allocate new %reg2)
  5717. cmp $y,###
  5718. sete %reg1
  5719. orb %reg2,%reg1
  5720. (dealloc %reg2)
  5721. This adds an instruction (so don't perform under -Os), but it removes
  5722. a conditional branch.
  5723. }
  5724. if not (cs_opt_size in current_settings.optimizerswitches) and
  5725. (
  5726. (hp1 = p_jump) or
  5727. GetNextInstruction(p, hp1)
  5728. ) and
  5729. MatchInstruction(hp1, A_Jcc, []) and
  5730. IsJumpToLabel(taicpu(hp1)) and
  5731. (taicpu(hp1).condition in [C_E, C_Z]) and
  5732. GetNextInstruction(hp1, hp2) and
  5733. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  5734. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  5735. { The first operand of CMP instructions can only be a register or
  5736. immediate anyway, so no need to check }
  5737. GetNextInstruction(hp2, p_label) and
  5738. (p_label.typ = ait_label) and
  5739. (tai_label(p_label).labsym.getrefs = 1) and
  5740. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  5741. GetNextInstruction(p_label, p_dist) and
  5742. MatchInstruction(p_dist, A_SETcc, []) and
  5743. (taicpu(p_dist).condition in [C_E, C_Z]) and
  5744. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  5745. begin
  5746. TransferUsedRegs(TmpUsedRegs);
  5747. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5748. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5749. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  5750. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5751. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  5752. { Get the instruction after the SETcc instruction so we can
  5753. allocate a new register over the entire range }
  5754. GetNextInstruction(p_dist, hp1_dist) then
  5755. begin
  5756. { Register can appear in p if it's not used afterwards, so only
  5757. allocate between hp1 and hp1_dist }
  5758. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  5759. if NewReg <> NR_NO then
  5760. begin
  5761. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  5762. { Change the jump instruction into a SETcc instruction }
  5763. taicpu(hp1).opcode := A_SETcc;
  5764. taicpu(hp1).opsize := S_B;
  5765. taicpu(hp1).loadreg(0, NewReg);
  5766. { This is now a dead label }
  5767. tai_label(p_label).labsym.decrefs;
  5768. { Prefer adding before the next instruction so the FLAGS
  5769. register is deallicated first }
  5770. AsmL.InsertBefore(
  5771. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  5772. hp1_dist
  5773. );
  5774. Result := True;
  5775. { Don't exit yet, as p wasn't changed and hp1, while
  5776. modified, is still intact and might be optimised by the
  5777. SETcc optimisation below }
  5778. end;
  5779. end;
  5780. end;
  5781. if taicpu(p).oper[0]^.typ = top_const then
  5782. begin
  5783. if (taicpu(p).oper[0]^.val = 0) and
  5784. (taicpu(p).oper[1]^.typ = top_reg) and
  5785. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5786. begin
  5787. hp2 := p;
  5788. FirstMatch := True;
  5789. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5790. anything meaningful once it's converted to "test %reg,%reg";
  5791. additionally, some jumps will always (or never) branch, so
  5792. evaluate every jump immediately following the
  5793. comparison, optimising the conditions if possible.
  5794. Similarly with SETcc... those that are always set to 0 or 1
  5795. are changed to MOV instructions }
  5796. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5797. (
  5798. GetNextInstruction(hp2, hp1) and
  5799. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5800. ) do
  5801. begin
  5802. FirstMatch := False;
  5803. case taicpu(hp1).condition of
  5804. C_B, C_C, C_NAE, C_O:
  5805. { For B/NAE:
  5806. Will never branch since an unsigned integer can never be below zero
  5807. For C/O:
  5808. Result cannot overflow because 0 is being subtracted
  5809. }
  5810. begin
  5811. if taicpu(hp1).opcode = A_Jcc then
  5812. begin
  5813. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5814. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5815. RemoveInstruction(hp1);
  5816. { Since hp1 was deleted, hp2 must not be updated }
  5817. Continue;
  5818. end
  5819. else
  5820. begin
  5821. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5822. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5823. taicpu(hp1).opcode := A_MOV;
  5824. taicpu(hp1).ops := 2;
  5825. taicpu(hp1).condition := C_None;
  5826. taicpu(hp1).opsize := S_B;
  5827. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5828. taicpu(hp1).loadconst(0, 0);
  5829. end;
  5830. end;
  5831. C_BE, C_NA:
  5832. begin
  5833. { Will only branch if equal to zero }
  5834. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5835. taicpu(hp1).condition := C_E;
  5836. end;
  5837. C_A, C_NBE:
  5838. begin
  5839. { Will only branch if not equal to zero }
  5840. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5841. taicpu(hp1).condition := C_NE;
  5842. end;
  5843. C_AE, C_NB, C_NC, C_NO:
  5844. begin
  5845. { Will always branch }
  5846. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5847. if taicpu(hp1).opcode = A_Jcc then
  5848. begin
  5849. MakeUnconditional(taicpu(hp1));
  5850. { Any jumps/set that follow will now be dead code }
  5851. RemoveDeadCodeAfterJump(taicpu(hp1));
  5852. Break;
  5853. end
  5854. else
  5855. begin
  5856. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5857. taicpu(hp1).opcode := A_MOV;
  5858. taicpu(hp1).ops := 2;
  5859. taicpu(hp1).condition := C_None;
  5860. taicpu(hp1).opsize := S_B;
  5861. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5862. taicpu(hp1).loadconst(0, 1);
  5863. end;
  5864. end;
  5865. C_None:
  5866. InternalError(2020012201);
  5867. C_P, C_PE, C_NP, C_PO:
  5868. { We can't handle parity checks and they should never be generated
  5869. after a general-purpose CMP (it's used in some floating-point
  5870. comparisons that don't use CMP) }
  5871. InternalError(2020012202);
  5872. else
  5873. { Zero/Equality, Sign, their complements and all of the
  5874. signed comparisons do not need to be converted };
  5875. end;
  5876. hp2 := hp1;
  5877. end;
  5878. { Convert the instruction to a TEST }
  5879. taicpu(p).opcode := A_TEST;
  5880. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5881. Result := True;
  5882. Exit;
  5883. end
  5884. else if (taicpu(p).oper[0]^.val = 1) and
  5885. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5886. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5887. begin
  5888. { Convert; To:
  5889. cmp $1,r/m cmp $0,r/m
  5890. jl @lbl jle @lbl
  5891. }
  5892. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5893. taicpu(p).oper[0]^.val := 0;
  5894. taicpu(hp1).condition := C_LE;
  5895. { If the instruction is now "cmp $0,%reg", convert it to a
  5896. TEST (and effectively do the work of the "cmp $0,%reg" in
  5897. the block above)
  5898. If it's a reference, we can get away with not setting
  5899. Result to True because he haven't evaluated the jump
  5900. in this pass yet.
  5901. }
  5902. if (taicpu(p).oper[1]^.typ = top_reg) then
  5903. begin
  5904. taicpu(p).opcode := A_TEST;
  5905. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5906. Result := True;
  5907. end;
  5908. Exit;
  5909. end
  5910. else if (taicpu(p).oper[1]^.typ = top_reg)
  5911. {$ifdef x86_64}
  5912. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5913. {$endif x86_64}
  5914. then
  5915. begin
  5916. { cmp register,$8000 neg register
  5917. je target --> jo target
  5918. .... only if register is deallocated before jump.}
  5919. case Taicpu(p).opsize of
  5920. S_B: v:=$80;
  5921. S_W: v:=$8000;
  5922. S_L: v:=qword($80000000);
  5923. else
  5924. internalerror(2013112905);
  5925. end;
  5926. if (taicpu(p).oper[0]^.val=v) and
  5927. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5928. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5929. begin
  5930. TransferUsedRegs(TmpUsedRegs);
  5931. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5932. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5933. begin
  5934. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5935. Taicpu(p).opcode:=A_NEG;
  5936. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5937. Taicpu(p).clearop(1);
  5938. Taicpu(p).ops:=1;
  5939. if Taicpu(hp1).condition=C_E then
  5940. Taicpu(hp1).condition:=C_O
  5941. else
  5942. Taicpu(hp1).condition:=C_NO;
  5943. Result:=true;
  5944. exit;
  5945. end;
  5946. end;
  5947. end;
  5948. end;
  5949. if TrySwapMovCmp(p, hp1) then
  5950. begin
  5951. Result := True;
  5952. Exit;
  5953. end;
  5954. end;
  5955. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5956. var
  5957. hp1: tai;
  5958. begin
  5959. {
  5960. remove the second (v)pxor from
  5961. pxor reg,reg
  5962. ...
  5963. pxor reg,reg
  5964. }
  5965. Result:=false;
  5966. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5967. MatchOpType(taicpu(p),top_reg,top_reg) and
  5968. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5969. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5970. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5971. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5972. begin
  5973. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5974. RemoveInstruction(hp1);
  5975. Result:=true;
  5976. Exit;
  5977. end
  5978. {
  5979. replace
  5980. pxor reg1,reg1
  5981. movapd/s reg1,reg2
  5982. dealloc reg1
  5983. by
  5984. pxor reg2,reg2
  5985. }
  5986. else if GetNextInstruction(p,hp1) and
  5987. { we mix single and double opperations here because we assume that the compiler
  5988. generates vmovapd only after double operations and vmovaps only after single operations }
  5989. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5990. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5991. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5992. (taicpu(p).oper[0]^.typ=top_reg) then
  5993. begin
  5994. TransferUsedRegs(TmpUsedRegs);
  5995. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5996. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5997. begin
  5998. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5999. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6000. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6001. RemoveInstruction(hp1);
  6002. result:=true;
  6003. end;
  6004. end;
  6005. end;
  6006. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6007. var
  6008. hp1: tai;
  6009. begin
  6010. {
  6011. remove the second (v)pxor from
  6012. (v)pxor reg,reg
  6013. ...
  6014. (v)pxor reg,reg
  6015. }
  6016. Result:=false;
  6017. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6018. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6019. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6020. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6021. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6022. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6023. begin
  6024. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6025. RemoveInstruction(hp1);
  6026. Result:=true;
  6027. Exit;
  6028. end
  6029. else
  6030. Result:=OptPass1VOP(p);
  6031. end;
  6032. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6033. var
  6034. hp1 : tai;
  6035. begin
  6036. result:=false;
  6037. { replace
  6038. IMul const,%mreg1,%mreg2
  6039. Mov %reg2,%mreg3
  6040. dealloc %mreg3
  6041. by
  6042. Imul const,%mreg1,%mreg23
  6043. }
  6044. if (taicpu(p).ops=3) and
  6045. GetNextInstruction(p,hp1) and
  6046. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6047. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6048. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6049. begin
  6050. TransferUsedRegs(TmpUsedRegs);
  6051. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6052. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6053. begin
  6054. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6055. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6056. RemoveInstruction(hp1);
  6057. result:=true;
  6058. end;
  6059. end;
  6060. end;
  6061. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6062. var
  6063. hp1 : tai;
  6064. begin
  6065. result:=false;
  6066. { replace
  6067. IMul %reg0,%reg1,%reg2
  6068. Mov %reg2,%reg3
  6069. dealloc %reg2
  6070. by
  6071. Imul %reg0,%reg1,%reg3
  6072. }
  6073. if GetNextInstruction(p,hp1) and
  6074. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6075. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6076. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6077. begin
  6078. TransferUsedRegs(TmpUsedRegs);
  6079. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6080. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6081. begin
  6082. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6083. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6084. RemoveInstruction(hp1);
  6085. result:=true;
  6086. end;
  6087. end;
  6088. end;
  6089. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6090. var
  6091. hp1: tai;
  6092. begin
  6093. Result:=false;
  6094. { get rid of
  6095. (v)cvtss2sd reg0,<reg1,>reg2
  6096. (v)cvtss2sd reg2,<reg2,>reg0
  6097. }
  6098. if GetNextInstruction(p,hp1) and
  6099. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6100. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6101. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6102. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6103. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6104. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6105. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6106. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6107. )
  6108. ) then
  6109. begin
  6110. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6111. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6112. begin
  6113. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6114. RemoveCurrentP(p);
  6115. RemoveInstruction(hp1);
  6116. end
  6117. else
  6118. begin
  6119. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6120. if taicpu(hp1).opcode=A_CVTSD2SS then
  6121. begin
  6122. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6123. taicpu(p).opcode:=A_MOVAPS;
  6124. end
  6125. else
  6126. begin
  6127. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6128. taicpu(p).opcode:=A_VMOVAPS;
  6129. end;
  6130. taicpu(p).ops:=2;
  6131. RemoveInstruction(hp1);
  6132. end;
  6133. Result:=true;
  6134. Exit;
  6135. end;
  6136. end;
  6137. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6138. var
  6139. hp1, hp2, hp3, hp4, hp5: tai;
  6140. ThisReg: TRegister;
  6141. begin
  6142. Result := False;
  6143. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  6144. Exit;
  6145. {
  6146. convert
  6147. j<c> .L1
  6148. mov 1,reg
  6149. jmp .L2
  6150. .L1
  6151. mov 0,reg
  6152. .L2
  6153. into
  6154. mov 0,reg
  6155. set<not(c)> reg
  6156. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6157. would destroy the flag contents
  6158. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6159. executed at the same time as a previous comparison.
  6160. set<not(c)> reg
  6161. movzx reg, reg
  6162. }
  6163. if MatchInstruction(hp1,A_MOV,[]) and
  6164. (taicpu(hp1).oper[0]^.typ = top_const) and
  6165. (
  6166. (
  6167. (taicpu(hp1).oper[1]^.typ = top_reg)
  6168. {$ifdef i386}
  6169. { Under i386, ESI, EDI, EBP and ESP
  6170. don't have an 8-bit representation }
  6171. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6172. {$endif i386}
  6173. ) or (
  6174. {$ifdef i386}
  6175. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6176. {$endif i386}
  6177. (taicpu(hp1).opsize = S_B)
  6178. )
  6179. ) and
  6180. GetNextInstruction(hp1,hp2) and
  6181. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6182. GetNextInstruction(hp2,hp3) and
  6183. SkipAligns(hp3, hp3) and
  6184. (hp3.typ=ait_label) and
  6185. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6186. GetNextInstruction(hp3,hp4) and
  6187. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6188. (taicpu(hp4).oper[0]^.typ = top_const) and
  6189. (
  6190. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6191. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6192. ) and
  6193. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6194. GetNextInstruction(hp4,hp5) and
  6195. SkipAligns(hp5, hp5) and
  6196. (hp5.typ=ait_label) and
  6197. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6198. begin
  6199. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6200. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6201. tai_label(hp3).labsym.DecRefs;
  6202. { If this isn't the only reference to the middle label, we can
  6203. still make a saving - only that the first jump and everything
  6204. that follows will remain. }
  6205. if (tai_label(hp3).labsym.getrefs = 0) then
  6206. begin
  6207. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6208. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6209. else
  6210. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6211. { remove jump, first label and second MOV (also catching any aligns) }
  6212. repeat
  6213. if not GetNextInstruction(hp2, hp3) then
  6214. InternalError(2021040810);
  6215. RemoveInstruction(hp2);
  6216. hp2 := hp3;
  6217. until hp2 = hp5;
  6218. { Don't decrement reference count before the removal loop
  6219. above, otherwise GetNextInstruction won't stop on the
  6220. the label }
  6221. tai_label(hp5).labsym.DecRefs;
  6222. end
  6223. else
  6224. begin
  6225. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6226. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6227. else
  6228. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6229. end;
  6230. taicpu(p).opcode:=A_SETcc;
  6231. taicpu(p).opsize:=S_B;
  6232. taicpu(p).is_jmp:=False;
  6233. if taicpu(hp1).opsize=S_B then
  6234. begin
  6235. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6236. if taicpu(hp1).oper[1]^.typ = top_reg then
  6237. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6238. RemoveInstruction(hp1);
  6239. end
  6240. else
  6241. begin
  6242. { Will be a register because the size can't be S_B otherwise }
  6243. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6244. taicpu(p).loadreg(0, ThisReg);
  6245. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6246. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6247. begin
  6248. case taicpu(hp1).opsize of
  6249. S_W:
  6250. taicpu(hp1).opsize := S_BW;
  6251. S_L:
  6252. taicpu(hp1).opsize := S_BL;
  6253. {$ifdef x86_64}
  6254. S_Q:
  6255. begin
  6256. taicpu(hp1).opsize := S_BL;
  6257. { Change the destination register to 32-bit }
  6258. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6259. end;
  6260. {$endif x86_64}
  6261. else
  6262. InternalError(2021040820);
  6263. end;
  6264. taicpu(hp1).opcode := A_MOVZX;
  6265. taicpu(hp1).loadreg(0, ThisReg);
  6266. end
  6267. else
  6268. begin
  6269. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6270. { hp1 is already a MOV instruction with the correct register }
  6271. taicpu(hp1).loadconst(0, 0);
  6272. { Inserting it right before p will guarantee that the flags are also tracked }
  6273. asml.Remove(hp1);
  6274. asml.InsertBefore(hp1, p);
  6275. end;
  6276. end;
  6277. Result:=true;
  6278. exit;
  6279. end
  6280. end;
  6281. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6282. var
  6283. hp1, hp2, hp3: tai;
  6284. SourceRef, TargetRef: TReference;
  6285. CurrentReg: TRegister;
  6286. begin
  6287. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6288. if not UseAVX then
  6289. InternalError(2021100501);
  6290. Result := False;
  6291. { Look for the following to simplify:
  6292. vmovdqa/u x(mem1), %xmmreg
  6293. vmovdqa/u %xmmreg, y(mem2)
  6294. vmovdqa/u x+16(mem1), %xmmreg
  6295. vmovdqa/u %xmmreg, y+16(mem2)
  6296. Change to:
  6297. vmovdqa/u x(mem1), %ymmreg
  6298. vmovdqa/u %ymmreg, y(mem2)
  6299. vpxor %ymmreg, %ymmreg, %ymmreg
  6300. ( The VPXOR instruction is to zero the upper half, thus removing the
  6301. need to call the potentially expensive VZEROUPPER instruction. Other
  6302. peephole optimisations can remove VPXOR if it's unnecessary )
  6303. }
  6304. TransferUsedRegs(TmpUsedRegs);
  6305. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6306. { NOTE: In the optimisations below, if the references dictate that an
  6307. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6308. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6309. if (taicpu(p).opsize = S_XMM) and
  6310. MatchOpType(taicpu(p), top_ref, top_reg) and
  6311. GetNextInstruction(p, hp1) and
  6312. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6313. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6314. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6315. begin
  6316. SourceRef := taicpu(p).oper[0]^.ref^;
  6317. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6318. if GetNextInstruction(hp1, hp2) and
  6319. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6320. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6321. begin
  6322. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6323. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6324. Inc(SourceRef.offset, 16);
  6325. { Reuse the register in the first block move }
  6326. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6327. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6328. begin
  6329. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6330. Inc(TargetRef.offset, 16);
  6331. if GetNextInstruction(hp2, hp3) and
  6332. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6333. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6334. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6335. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6336. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6337. begin
  6338. { Update the register tracking to the new size }
  6339. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6340. { Remember that the offsets are 16 ahead }
  6341. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6342. if not (
  6343. ((SourceRef.offset mod 32) = 16) and
  6344. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6345. ) then
  6346. taicpu(p).opcode := A_VMOVDQU;
  6347. taicpu(p).opsize := S_YMM;
  6348. taicpu(p).oper[1]^.reg := CurrentReg;
  6349. if not (
  6350. ((TargetRef.offset mod 32) = 16) and
  6351. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6352. ) then
  6353. taicpu(hp1).opcode := A_VMOVDQU;
  6354. taicpu(hp1).opsize := S_YMM;
  6355. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6356. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6357. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6358. if (pi_uses_ymm in current_procinfo.flags) then
  6359. RemoveInstruction(hp2)
  6360. else
  6361. begin
  6362. taicpu(hp2).opcode := A_VPXOR;
  6363. taicpu(hp2).opsize := S_YMM;
  6364. taicpu(hp2).loadreg(0, CurrentReg);
  6365. taicpu(hp2).loadreg(1, CurrentReg);
  6366. taicpu(hp2).loadreg(2, CurrentReg);
  6367. taicpu(hp2).ops := 3;
  6368. end;
  6369. RemoveInstruction(hp3);
  6370. Result := True;
  6371. Exit;
  6372. end;
  6373. end
  6374. else
  6375. begin
  6376. { See if the next references are 16 less rather than 16 greater }
  6377. Dec(SourceRef.offset, 32); { -16 the other way }
  6378. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6379. begin
  6380. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6381. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6382. if GetNextInstruction(hp2, hp3) and
  6383. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6384. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6385. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6386. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6387. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6388. begin
  6389. { Update the register tracking to the new size }
  6390. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6391. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6392. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6393. if not(
  6394. ((SourceRef.offset mod 32) = 0) and
  6395. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6396. ) then
  6397. taicpu(hp2).opcode := A_VMOVDQU;
  6398. taicpu(hp2).opsize := S_YMM;
  6399. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6400. if not (
  6401. ((TargetRef.offset mod 32) = 0) and
  6402. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6403. ) then
  6404. taicpu(hp3).opcode := A_VMOVDQU;
  6405. taicpu(hp3).opsize := S_YMM;
  6406. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6407. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6408. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6409. if (pi_uses_ymm in current_procinfo.flags) then
  6410. RemoveInstruction(hp1)
  6411. else
  6412. begin
  6413. taicpu(hp1).opcode := A_VPXOR;
  6414. taicpu(hp1).opsize := S_YMM;
  6415. taicpu(hp1).loadreg(0, CurrentReg);
  6416. taicpu(hp1).loadreg(1, CurrentReg);
  6417. taicpu(hp1).loadreg(2, CurrentReg);
  6418. taicpu(hp1).ops := 3;
  6419. Asml.Remove(hp1);
  6420. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6421. end;
  6422. RemoveCurrentP(p, hp2);
  6423. Result := True;
  6424. Exit;
  6425. end;
  6426. end;
  6427. end;
  6428. end;
  6429. end;
  6430. end;
  6431. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6432. var
  6433. hp2, hp3, first_assignment: tai;
  6434. IncCount, OperIdx: Integer;
  6435. OrigLabel: TAsmLabel;
  6436. begin
  6437. Count := 0;
  6438. Result := False;
  6439. first_assignment := nil;
  6440. if (LoopCount >= 20) then
  6441. begin
  6442. { Guard against infinite loops }
  6443. Exit;
  6444. end;
  6445. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6446. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6447. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6448. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6449. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6450. Exit;
  6451. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6452. {
  6453. change
  6454. jmp .L1
  6455. ...
  6456. .L1:
  6457. mov ##, ## ( multiple movs possible )
  6458. jmp/ret
  6459. into
  6460. mov ##, ##
  6461. jmp/ret
  6462. }
  6463. if not Assigned(hp1) then
  6464. begin
  6465. hp1 := GetLabelWithSym(OrigLabel);
  6466. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6467. Exit;
  6468. end;
  6469. hp2 := hp1;
  6470. while Assigned(hp2) do
  6471. begin
  6472. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6473. SkipLabels(hp2,hp2);
  6474. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6475. Break;
  6476. case taicpu(hp2).opcode of
  6477. A_MOVSS:
  6478. begin
  6479. if taicpu(hp2).ops = 0 then
  6480. { Wrong MOVSS }
  6481. Break;
  6482. Inc(Count);
  6483. if Count >= 5 then
  6484. { Too many to be worthwhile }
  6485. Break;
  6486. GetNextInstruction(hp2, hp2);
  6487. Continue;
  6488. end;
  6489. A_MOV,
  6490. A_MOVD,
  6491. A_MOVQ,
  6492. A_MOVSX,
  6493. {$ifdef x86_64}
  6494. A_MOVSXD,
  6495. {$endif x86_64}
  6496. A_MOVZX,
  6497. A_MOVAPS,
  6498. A_MOVUPS,
  6499. A_MOVSD,
  6500. A_MOVAPD,
  6501. A_MOVUPD,
  6502. A_MOVDQA,
  6503. A_MOVDQU,
  6504. A_VMOVSS,
  6505. A_VMOVAPS,
  6506. A_VMOVUPS,
  6507. A_VMOVSD,
  6508. A_VMOVAPD,
  6509. A_VMOVUPD,
  6510. A_VMOVDQA,
  6511. A_VMOVDQU:
  6512. begin
  6513. Inc(Count);
  6514. if Count >= 5 then
  6515. { Too many to be worthwhile }
  6516. Break;
  6517. GetNextInstruction(hp2, hp2);
  6518. Continue;
  6519. end;
  6520. A_JMP:
  6521. begin
  6522. { Guard against infinite loops }
  6523. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6524. Exit;
  6525. { Analyse this jump first in case it also duplicates assignments }
  6526. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6527. begin
  6528. { Something did change! }
  6529. Result := True;
  6530. Inc(Count, IncCount);
  6531. if Count >= 5 then
  6532. begin
  6533. { Too many to be worthwhile }
  6534. Exit;
  6535. end;
  6536. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6537. Break;
  6538. end;
  6539. Result := True;
  6540. Break;
  6541. end;
  6542. A_RET:
  6543. begin
  6544. Result := True;
  6545. Break;
  6546. end;
  6547. else
  6548. Break;
  6549. end;
  6550. end;
  6551. if Result then
  6552. begin
  6553. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6554. if Count = 0 then
  6555. begin
  6556. Result := False;
  6557. Exit;
  6558. end;
  6559. hp3 := p;
  6560. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6561. while True do
  6562. begin
  6563. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6564. SkipLabels(hp1,hp1);
  6565. if (hp1.typ <> ait_instruction) then
  6566. InternalError(2021040720);
  6567. case taicpu(hp1).opcode of
  6568. A_JMP:
  6569. begin
  6570. { Change the original jump to the new destination }
  6571. OrigLabel.decrefs;
  6572. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6573. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6574. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6575. if not Assigned(first_assignment) then
  6576. InternalError(2021040810)
  6577. else
  6578. p := first_assignment;
  6579. Exit;
  6580. end;
  6581. A_RET:
  6582. begin
  6583. { Now change the jump into a RET instruction }
  6584. ConvertJumpToRET(p, hp1);
  6585. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6586. if not Assigned(first_assignment) then
  6587. InternalError(2021040811)
  6588. else
  6589. p := first_assignment;
  6590. Exit;
  6591. end;
  6592. else
  6593. begin
  6594. { Duplicate the MOV instruction }
  6595. hp3:=tai(hp1.getcopy);
  6596. if first_assignment = nil then
  6597. first_assignment := hp3;
  6598. asml.InsertBefore(hp3, p);
  6599. { Make sure the compiler knows about any final registers written here }
  6600. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6601. with taicpu(hp3).oper[OperIdx]^ do
  6602. begin
  6603. case typ of
  6604. top_ref:
  6605. begin
  6606. if (ref^.base <> NR_NO) and
  6607. (getsupreg(ref^.base) <> RS_ESP) and
  6608. (getsupreg(ref^.base) <> RS_EBP)
  6609. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6610. then
  6611. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6612. if (ref^.index <> NR_NO) and
  6613. (getsupreg(ref^.index) <> RS_ESP) and
  6614. (getsupreg(ref^.index) <> RS_EBP)
  6615. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6616. (ref^.index <> ref^.base) then
  6617. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6618. end;
  6619. top_reg:
  6620. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6621. else
  6622. ;
  6623. end;
  6624. end;
  6625. end;
  6626. end;
  6627. if not GetNextInstruction(hp1, hp1) then
  6628. { Should have dropped out earlier }
  6629. InternalError(2021040710);
  6630. end;
  6631. end;
  6632. end;
  6633. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6634. var
  6635. hp2: tai;
  6636. X: Integer;
  6637. const
  6638. WriteOp: array[0..3] of set of TInsChange = (
  6639. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6640. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6641. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6642. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6643. RegWriteFlags: array[0..7] of set of TInsChange = (
  6644. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6645. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6646. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6647. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6648. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6649. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6650. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6651. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6652. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6653. begin
  6654. { If we have something like:
  6655. cmp ###,%reg1
  6656. mov 0,%reg2
  6657. And no modified registers are shared, move the instruction to before
  6658. the comparison as this means it can be optimised without worrying
  6659. about the FLAGS register. (CMP/MOV is generated by
  6660. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6661. As long as the second instruction doesn't use the flags or one of the
  6662. registers used by CMP or TEST (also check any references that use the
  6663. registers), then it can be moved prior to the comparison.
  6664. }
  6665. Result := False;
  6666. if (hp1.typ <> ait_instruction) or
  6667. taicpu(hp1).is_jmp or
  6668. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6669. Exit;
  6670. { NOP is a pipeline fence, likely marking the beginning of the function
  6671. epilogue, so drop out. Similarly, drop out if POP or RET are
  6672. encountered }
  6673. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6674. Exit;
  6675. if (taicpu(hp1).opcode = A_MOVSS) and
  6676. (taicpu(hp1).ops = 0) then
  6677. { Wrong MOVSS }
  6678. Exit;
  6679. { Check for writes to specific registers first }
  6680. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6681. for X := 0 to 7 do
  6682. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6683. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6684. Exit;
  6685. for X := 0 to taicpu(hp1).ops - 1 do
  6686. begin
  6687. { Check to see if this operand writes to something }
  6688. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6689. { And matches something in the CMP/TEST instruction }
  6690. (
  6691. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6692. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6693. (
  6694. { If it's a register, make sure the register written to doesn't
  6695. appear in the cmp instruction as part of a reference }
  6696. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6697. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6698. )
  6699. ) then
  6700. Exit;
  6701. end;
  6702. { The instruction can be safely moved }
  6703. asml.Remove(hp1);
  6704. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6705. if not GetLastInstruction(p, hp2) then
  6706. asml.InsertBefore(hp1, p)
  6707. else
  6708. asml.InsertAfter(hp1, hp2);
  6709. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  6710. for X := 0 to taicpu(hp1).ops - 1 do
  6711. case taicpu(hp1).oper[X]^.typ of
  6712. top_reg:
  6713. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  6714. top_ref:
  6715. begin
  6716. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  6717. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  6718. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  6719. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  6720. end;
  6721. else
  6722. ;
  6723. end;
  6724. if taicpu(hp1).opcode = A_LEA then
  6725. { The flags will be overwritten by the CMP/TEST instruction }
  6726. ConvertLEA(taicpu(hp1));
  6727. Result := True;
  6728. end;
  6729. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  6730. function IsXCHGAcceptable: Boolean; inline;
  6731. begin
  6732. { Always accept if optimising for size }
  6733. Result := (cs_opt_size in current_settings.optimizerswitches) or
  6734. (
  6735. {$ifdef x86_64}
  6736. { XCHG takes 3 cycles on AMD Athlon64 }
  6737. (current_settings.optimizecputype >= cpu_core_i)
  6738. {$else x86_64}
  6739. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  6740. than 3, so it becomes a saving compared to three MOVs with two of
  6741. them able to execute simultaneously. [Kit] }
  6742. (current_settings.optimizecputype >= cpu_PentiumM)
  6743. {$endif x86_64}
  6744. );
  6745. end;
  6746. var
  6747. NewRef: TReference;
  6748. hp1, hp2, hp3, hp4: Tai;
  6749. {$ifndef x86_64}
  6750. OperIdx: Integer;
  6751. {$endif x86_64}
  6752. NewInstr : Taicpu;
  6753. NewAligh : Tai_align;
  6754. DestLabel: TAsmLabel;
  6755. function TryMovArith2Lea(InputInstr: tai): Boolean;
  6756. var
  6757. NextInstr: tai;
  6758. begin
  6759. Result := False;
  6760. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  6761. if not GetNextInstruction(InputInstr, NextInstr) or
  6762. (
  6763. { The FLAGS register isn't always tracked properly, so do not
  6764. perform this optimisation if a conditional statement follows }
  6765. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  6766. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  6767. ) then
  6768. begin
  6769. reference_reset(NewRef, 1, []);
  6770. NewRef.base := taicpu(p).oper[0]^.reg;
  6771. NewRef.scalefactor := 1;
  6772. if taicpu(InputInstr).opcode = A_ADD then
  6773. begin
  6774. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6775. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  6776. end
  6777. else
  6778. begin
  6779. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6780. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  6781. end;
  6782. taicpu(p).opcode := A_LEA;
  6783. taicpu(p).loadref(0, NewRef);
  6784. RemoveInstruction(InputInstr);
  6785. Result := True;
  6786. end;
  6787. end;
  6788. begin
  6789. Result:=false;
  6790. { This optimisation adds an instruction, so only do it for speed }
  6791. if not (cs_opt_size in current_settings.optimizerswitches) and
  6792. MatchOpType(taicpu(p), top_const, top_reg) and
  6793. (taicpu(p).oper[0]^.val = 0) then
  6794. begin
  6795. { To avoid compiler warning }
  6796. DestLabel := nil;
  6797. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  6798. InternalError(2021040750);
  6799. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  6800. Exit;
  6801. case hp1.typ of
  6802. ait_label:
  6803. begin
  6804. { Change:
  6805. mov $0,%reg mov $0,%reg
  6806. @Lbl1: @Lbl1:
  6807. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  6808. je @Lbl2 jne @Lbl2
  6809. To: To:
  6810. mov $0,%reg mov $0,%reg
  6811. jmp @Lbl2 jmp @Lbl3
  6812. (align) (align)
  6813. @Lbl1: @Lbl1:
  6814. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  6815. je @Lbl2 je @Lbl2
  6816. @Lbl3: <-- Only if label exists
  6817. (Not if it's optimised for size)
  6818. }
  6819. if not GetNextInstruction(hp1, hp2) then
  6820. Exit;
  6821. if not (cs_opt_size in current_settings.optimizerswitches) and
  6822. (hp2.typ = ait_instruction) and
  6823. (
  6824. { Register sizes must exactly match }
  6825. (
  6826. (taicpu(hp2).opcode = A_CMP) and
  6827. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  6828. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6829. ) or (
  6830. (taicpu(hp2).opcode = A_TEST) and
  6831. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6832. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  6833. )
  6834. ) and GetNextInstruction(hp2, hp3) and
  6835. (hp3.typ = ait_instruction) and
  6836. (taicpu(hp3).opcode = A_JCC) and
  6837. (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
  6838. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  6839. begin
  6840. { Check condition of jump }
  6841. { Always true? }
  6842. if condition_in(C_E, taicpu(hp3).condition) then
  6843. begin
  6844. { Copy label symbol and obtain matching label entry for the
  6845. conditional jump, as this will be our destination}
  6846. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  6847. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  6848. Result := True;
  6849. end
  6850. { Always false? }
  6851. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  6852. begin
  6853. { This is only worth it if there's a jump to take }
  6854. case hp2.typ of
  6855. ait_instruction:
  6856. begin
  6857. if taicpu(hp2).opcode = A_JMP then
  6858. begin
  6859. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6860. { An unconditional jump follows the conditional jump which will always be false,
  6861. so use this jump's destination for the new jump }
  6862. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  6863. Result := True;
  6864. end
  6865. else if taicpu(hp2).opcode = A_JCC then
  6866. begin
  6867. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  6868. if condition_in(C_E, taicpu(hp2).condition) then
  6869. begin
  6870. { A second conditional jump follows the conditional jump which will always be false,
  6871. while the second jump is always True, so use this jump's destination for the new jump }
  6872. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  6873. Result := True;
  6874. end;
  6875. { Don't risk it if the jump isn't always true (Result remains False) }
  6876. end;
  6877. end;
  6878. else
  6879. { If anything else don't optimise };
  6880. end;
  6881. end;
  6882. if Result then
  6883. begin
  6884. { Just so we have something to insert as a paremeter}
  6885. reference_reset(NewRef, 1, []);
  6886. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  6887. { Now actually load the correct parameter }
  6888. NewInstr.loadsymbol(0, DestLabel, 0);
  6889. { Get instruction before original label (may not be p under -O3) }
  6890. if not GetLastInstruction(hp1, hp2) then
  6891. { Shouldn't fail here }
  6892. InternalError(2021040701);
  6893. DestLabel.increfs;
  6894. AsmL.InsertAfter(NewInstr, hp2);
  6895. { Add new alignment field }
  6896. (* AsmL.InsertAfter(
  6897. cai_align.create_max(
  6898. current_settings.alignment.jumpalign,
  6899. current_settings.alignment.jumpalignskipmax
  6900. ),
  6901. NewInstr
  6902. ); *)
  6903. end;
  6904. Exit;
  6905. end;
  6906. end;
  6907. else
  6908. ;
  6909. end;
  6910. end;
  6911. if not GetNextInstruction(p, hp1) then
  6912. Exit;
  6913. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  6914. and DoMovCmpMemOpt(p, hp1, True) then
  6915. begin
  6916. Result := True;
  6917. Exit;
  6918. end
  6919. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  6920. begin
  6921. { Sometimes the MOVs that OptPass2JMP produces can be improved
  6922. further, but we can't just put this jump optimisation in pass 1
  6923. because it tends to perform worse when conditional jumps are
  6924. nearby (e.g. when converting CMOV instructions). [Kit] }
  6925. if OptPass2JMP(hp1) then
  6926. { call OptPass1MOV once to potentially merge any MOVs that were created }
  6927. Result := OptPass1MOV(p)
  6928. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  6929. returned True and the instruction is still a MOV, thus checking
  6930. the optimisations below }
  6931. { If OptPass2JMP returned False, no optimisations were done to
  6932. the jump and there are no further optimisations that can be done
  6933. to the MOV instruction on this pass }
  6934. end
  6935. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6936. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  6937. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6938. (taicpu(hp1).oper[1]^.typ = top_reg) and
  6939. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6940. begin
  6941. { Change:
  6942. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  6943. addl/q $x,%reg2 subl/q $x,%reg2
  6944. To:
  6945. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  6946. }
  6947. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6948. { be lazy, checking separately for sub would be slightly better }
  6949. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  6950. begin
  6951. TransferUsedRegs(TmpUsedRegs);
  6952. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6953. if TryMovArith2Lea(hp1) then
  6954. begin
  6955. Result := True;
  6956. Exit;
  6957. end
  6958. end
  6959. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  6960. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  6961. { Same as above, but also adds or subtracts to %reg2 in between.
  6962. It's still valid as long as the flags aren't in use }
  6963. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  6964. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6965. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6966. { be lazy, checking separately for sub would be slightly better }
  6967. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  6968. begin
  6969. TransferUsedRegs(TmpUsedRegs);
  6970. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6971. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6972. if TryMovArith2Lea(hp2) then
  6973. begin
  6974. Result := True;
  6975. Exit;
  6976. end;
  6977. end;
  6978. end
  6979. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6980. {$ifdef x86_64}
  6981. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6982. {$else x86_64}
  6983. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6984. {$endif x86_64}
  6985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6986. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6987. { mov reg1, reg2 mov reg1, reg2
  6988. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6989. begin
  6990. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6991. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6992. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6993. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6994. TransferUsedRegs(TmpUsedRegs);
  6995. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6996. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6997. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6998. then
  6999. begin
  7000. RemoveCurrentP(p, hp1);
  7001. Result:=true;
  7002. end;
  7003. exit;
  7004. end
  7005. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7006. IsXCHGAcceptable and
  7007. { XCHG doesn't support 8-byte registers }
  7008. (taicpu(p).opsize <> S_B) and
  7009. MatchInstruction(hp1, A_MOV, []) and
  7010. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7011. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7012. GetNextInstruction(hp1, hp2) and
  7013. MatchInstruction(hp2, A_MOV, []) and
  7014. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7015. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7016. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7017. begin
  7018. { mov %reg1,%reg2
  7019. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7020. mov %reg2,%reg3
  7021. (%reg2 not used afterwards)
  7022. Note that xchg takes 3 cycles to execute, and generally mov's take
  7023. only one cycle apiece, but the first two mov's can be executed in
  7024. parallel, only taking 2 cycles overall. Older processors should
  7025. therefore only optimise for size. [Kit]
  7026. }
  7027. TransferUsedRegs(TmpUsedRegs);
  7028. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7029. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7030. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7031. begin
  7032. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7033. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7034. taicpu(hp1).opcode := A_XCHG;
  7035. RemoveCurrentP(p, hp1);
  7036. RemoveInstruction(hp2);
  7037. Result := True;
  7038. Exit;
  7039. end;
  7040. end
  7041. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7042. MatchInstruction(hp1, A_SAR, []) then
  7043. begin
  7044. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7045. begin
  7046. { the use of %edx also covers the opsize being S_L }
  7047. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7048. begin
  7049. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7050. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7051. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7052. begin
  7053. { Change:
  7054. movl %eax,%edx
  7055. sarl $31,%edx
  7056. To:
  7057. cltd
  7058. }
  7059. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7060. RemoveInstruction(hp1);
  7061. taicpu(p).opcode := A_CDQ;
  7062. taicpu(p).opsize := S_NO;
  7063. taicpu(p).clearop(1);
  7064. taicpu(p).clearop(0);
  7065. taicpu(p).ops:=0;
  7066. Result := True;
  7067. end
  7068. else if (cs_opt_size in current_settings.optimizerswitches) and
  7069. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7070. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7071. begin
  7072. { Change:
  7073. movl %edx,%eax
  7074. sarl $31,%edx
  7075. To:
  7076. movl %edx,%eax
  7077. cltd
  7078. Note that this creates a dependency between the two instructions,
  7079. so only perform if optimising for size.
  7080. }
  7081. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7082. taicpu(hp1).opcode := A_CDQ;
  7083. taicpu(hp1).opsize := S_NO;
  7084. taicpu(hp1).clearop(1);
  7085. taicpu(hp1).clearop(0);
  7086. taicpu(hp1).ops:=0;
  7087. end;
  7088. {$ifndef x86_64}
  7089. end
  7090. { Don't bother if CMOV is supported, because a more optimal
  7091. sequence would have been generated for the Abs() intrinsic }
  7092. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7093. { the use of %eax also covers the opsize being S_L }
  7094. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7095. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7096. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7097. GetNextInstruction(hp1, hp2) and
  7098. MatchInstruction(hp2, A_XOR, [S_L]) and
  7099. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7100. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7101. GetNextInstruction(hp2, hp3) and
  7102. MatchInstruction(hp3, A_SUB, [S_L]) and
  7103. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7104. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7105. begin
  7106. { Change:
  7107. movl %eax,%edx
  7108. sarl $31,%eax
  7109. xorl %eax,%edx
  7110. subl %eax,%edx
  7111. (Instruction that uses %edx)
  7112. (%eax deallocated)
  7113. (%edx deallocated)
  7114. To:
  7115. cltd
  7116. xorl %edx,%eax <-- Note the registers have swapped
  7117. subl %edx,%eax
  7118. (Instruction that uses %eax) <-- %eax rather than %edx
  7119. }
  7120. TransferUsedRegs(TmpUsedRegs);
  7121. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7122. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7123. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7124. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7125. begin
  7126. if GetNextInstruction(hp3, hp4) and
  7127. not RegModifiedByInstruction(NR_EDX, hp4) and
  7128. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7129. begin
  7130. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7131. taicpu(p).opcode := A_CDQ;
  7132. taicpu(p).clearop(1);
  7133. taicpu(p).clearop(0);
  7134. taicpu(p).ops:=0;
  7135. RemoveInstruction(hp1);
  7136. taicpu(hp2).loadreg(0, NR_EDX);
  7137. taicpu(hp2).loadreg(1, NR_EAX);
  7138. taicpu(hp3).loadreg(0, NR_EDX);
  7139. taicpu(hp3).loadreg(1, NR_EAX);
  7140. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7141. { Convert references in the following instruction (hp4) from %edx to %eax }
  7142. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7143. with taicpu(hp4).oper[OperIdx]^ do
  7144. case typ of
  7145. top_reg:
  7146. if getsupreg(reg) = RS_EDX then
  7147. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7148. top_ref:
  7149. begin
  7150. if getsupreg(reg) = RS_EDX then
  7151. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7152. if getsupreg(reg) = RS_EDX then
  7153. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7154. end;
  7155. else
  7156. ;
  7157. end;
  7158. end;
  7159. end;
  7160. {$else x86_64}
  7161. end;
  7162. end
  7163. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7164. { the use of %rdx also covers the opsize being S_Q }
  7165. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7166. begin
  7167. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7168. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7169. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7170. begin
  7171. { Change:
  7172. movq %rax,%rdx
  7173. sarq $63,%rdx
  7174. To:
  7175. cqto
  7176. }
  7177. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7178. RemoveInstruction(hp1);
  7179. taicpu(p).opcode := A_CQO;
  7180. taicpu(p).opsize := S_NO;
  7181. taicpu(p).clearop(1);
  7182. taicpu(p).clearop(0);
  7183. taicpu(p).ops:=0;
  7184. Result := True;
  7185. end
  7186. else if (cs_opt_size in current_settings.optimizerswitches) and
  7187. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7188. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7189. begin
  7190. { Change:
  7191. movq %rdx,%rax
  7192. sarq $63,%rdx
  7193. To:
  7194. movq %rdx,%rax
  7195. cqto
  7196. Note that this creates a dependency between the two instructions,
  7197. so only perform if optimising for size.
  7198. }
  7199. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7200. taicpu(hp1).opcode := A_CQO;
  7201. taicpu(hp1).opsize := S_NO;
  7202. taicpu(hp1).clearop(1);
  7203. taicpu(hp1).clearop(0);
  7204. taicpu(hp1).ops:=0;
  7205. {$endif x86_64}
  7206. end;
  7207. end;
  7208. end
  7209. else if MatchInstruction(hp1, A_MOV, []) and
  7210. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7211. { Though "GetNextInstruction" could be factored out, along with
  7212. the instructions that depend on hp2, it is an expensive call that
  7213. should be delayed for as long as possible, hence we do cheaper
  7214. checks first that are likely to be False. [Kit] }
  7215. begin
  7216. if (
  7217. (
  7218. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7219. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7220. (
  7221. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7222. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7223. )
  7224. ) or
  7225. (
  7226. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7227. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7228. (
  7229. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7230. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7231. )
  7232. )
  7233. ) and
  7234. GetNextInstruction(hp1, hp2) and
  7235. MatchInstruction(hp2, A_SAR, []) and
  7236. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7237. begin
  7238. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7239. begin
  7240. { Change:
  7241. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7242. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7243. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7244. To:
  7245. movl r/m,%eax <- Note the change in register
  7246. cltd
  7247. }
  7248. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7249. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7250. taicpu(p).loadreg(1, NR_EAX);
  7251. taicpu(hp1).opcode := A_CDQ;
  7252. taicpu(hp1).clearop(1);
  7253. taicpu(hp1).clearop(0);
  7254. taicpu(hp1).ops:=0;
  7255. RemoveInstruction(hp2);
  7256. (*
  7257. {$ifdef x86_64}
  7258. end
  7259. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7260. { This code sequence does not get generated - however it might become useful
  7261. if and when 128-bit signed integer types make an appearance, so the code
  7262. is kept here for when it is eventually needed. [Kit] }
  7263. (
  7264. (
  7265. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7266. (
  7267. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7268. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7269. )
  7270. ) or
  7271. (
  7272. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7273. (
  7274. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7275. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7276. )
  7277. )
  7278. ) and
  7279. GetNextInstruction(hp1, hp2) and
  7280. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7281. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7282. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7283. begin
  7284. { Change:
  7285. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7286. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7287. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7288. To:
  7289. movq r/m,%rax <- Note the change in register
  7290. cqto
  7291. }
  7292. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7293. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7294. taicpu(p).loadreg(1, NR_RAX);
  7295. taicpu(hp1).opcode := A_CQO;
  7296. taicpu(hp1).clearop(1);
  7297. taicpu(hp1).clearop(0);
  7298. taicpu(hp1).ops:=0;
  7299. RemoveInstruction(hp2);
  7300. {$endif x86_64}
  7301. *)
  7302. end;
  7303. end;
  7304. {$ifdef x86_64}
  7305. end
  7306. else if (taicpu(p).opsize = S_L) and
  7307. (taicpu(p).oper[1]^.typ = top_reg) and
  7308. (
  7309. MatchInstruction(hp1, A_MOV,[]) and
  7310. (taicpu(hp1).opsize = S_L) and
  7311. (taicpu(hp1).oper[1]^.typ = top_reg)
  7312. ) and (
  7313. GetNextInstruction(hp1, hp2) and
  7314. (tai(hp2).typ=ait_instruction) and
  7315. (taicpu(hp2).opsize = S_Q) and
  7316. (
  7317. (
  7318. MatchInstruction(hp2, A_ADD,[]) and
  7319. (taicpu(hp2).opsize = S_Q) and
  7320. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7321. (
  7322. (
  7323. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7324. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7325. ) or (
  7326. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7327. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7328. )
  7329. )
  7330. ) or (
  7331. MatchInstruction(hp2, A_LEA,[]) and
  7332. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7333. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7334. (
  7335. (
  7336. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7337. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7338. ) or (
  7339. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7340. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7341. )
  7342. ) and (
  7343. (
  7344. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7345. ) or (
  7346. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7347. )
  7348. )
  7349. )
  7350. )
  7351. ) and (
  7352. GetNextInstruction(hp2, hp3) and
  7353. MatchInstruction(hp3, A_SHR,[]) and
  7354. (taicpu(hp3).opsize = S_Q) and
  7355. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7356. (taicpu(hp3).oper[0]^.val = 1) and
  7357. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7358. ) then
  7359. begin
  7360. { Change movl x, reg1d movl x, reg1d
  7361. movl y, reg2d movl y, reg2d
  7362. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7363. shrq $1, reg1q shrq $1, reg1q
  7364. ( reg1d and reg2d can be switched around in the first two instructions )
  7365. To movl x, reg1d
  7366. addl y, reg1d
  7367. rcrl $1, reg1d
  7368. This corresponds to the common expression (x + y) shr 1, where
  7369. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7370. smaller code, but won't account for x + y causing an overflow). [Kit]
  7371. }
  7372. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7373. { Change first MOV command to have the same register as the final output }
  7374. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7375. else
  7376. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7377. { Change second MOV command to an ADD command. This is easier than
  7378. converting the existing command because it means we don't have to
  7379. touch 'y', which might be a complicated reference, and also the
  7380. fact that the third command might either be ADD or LEA. [Kit] }
  7381. taicpu(hp1).opcode := A_ADD;
  7382. { Delete old ADD/LEA instruction }
  7383. RemoveInstruction(hp2);
  7384. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7385. taicpu(hp3).opcode := A_RCR;
  7386. taicpu(hp3).changeopsize(S_L);
  7387. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7388. {$endif x86_64}
  7389. end;
  7390. end;
  7391. {$push}
  7392. {$q-}{$r-}
  7393. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7394. var
  7395. ThisReg: TRegister;
  7396. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7397. TargetSubReg: TSubRegister;
  7398. hp1, hp2: tai;
  7399. RegInUse, RegChanged, p_removed: Boolean;
  7400. { Store list of found instructions so we don't have to call
  7401. GetNextInstructionUsingReg multiple times }
  7402. InstrList: array of taicpu;
  7403. InstrMax, Index: Integer;
  7404. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7405. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7406. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7407. WorkingValue: TCgInt;
  7408. PreMessage: string;
  7409. { Data flow analysis }
  7410. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7411. BitwiseOnly, OrXorUsed,
  7412. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7413. function CheckOverflowConditions: Boolean;
  7414. begin
  7415. Result := True;
  7416. if (TestValSignedMax > SignedUpperLimit) then
  7417. UpperSignedOverflow := True;
  7418. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7419. LowerSignedOverflow := True;
  7420. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7421. LowerUnsignedOverflow := True;
  7422. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7423. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7424. begin
  7425. { Absolute overflow }
  7426. Result := False;
  7427. Exit;
  7428. end;
  7429. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7430. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7431. ShiftDownOverflow := True;
  7432. if (TestValMin < 0) or (TestValMax < 0) then
  7433. begin
  7434. LowerUnsignedOverflow := True;
  7435. UpperUnsignedOverflow := True;
  7436. end;
  7437. end;
  7438. procedure AdjustFinalLoad;
  7439. begin
  7440. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7441. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7442. begin
  7443. { Convert the output MOVZX to a MOV }
  7444. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7445. begin
  7446. { Or remove it completely! }
  7447. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7448. { Be careful; if p = hp1 and p was also removed, p
  7449. will become a dangling pointer }
  7450. if p = hp1 then
  7451. begin
  7452. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7453. p_removed := True;
  7454. end
  7455. else
  7456. RemoveInstruction(hp1);
  7457. end
  7458. else
  7459. begin
  7460. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7461. taicpu(hp1).opcode := A_MOV;
  7462. taicpu(hp1).oper[0]^.reg := ThisReg;
  7463. taicpu(hp1).opsize := TargetSize;
  7464. end;
  7465. end
  7466. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7467. begin
  7468. { Need to change the size of the output }
  7469. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7470. taicpu(hp1).oper[0]^.reg := ThisReg;
  7471. taicpu(hp1).opsize := S_BL;
  7472. end;
  7473. end;
  7474. function CompressInstructions: Boolean;
  7475. var
  7476. LocalIndex: Integer;
  7477. begin
  7478. Result := False;
  7479. { The objective here is to try to find a combination that
  7480. removes one of the MOV/Z instructions. }
  7481. if (
  7482. (taicpu(p).oper[0]^.typ <> top_reg) or
  7483. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7484. ) and
  7485. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7486. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7487. begin
  7488. { Make a preference to remove the second MOVZX instruction }
  7489. case taicpu(hp1).opsize of
  7490. S_BL, S_WL:
  7491. begin
  7492. TargetSize := S_L;
  7493. TargetSubReg := R_SUBD;
  7494. end;
  7495. S_BW:
  7496. begin
  7497. TargetSize := S_W;
  7498. TargetSubReg := R_SUBW;
  7499. end;
  7500. else
  7501. InternalError(2020112302);
  7502. end;
  7503. end
  7504. else
  7505. begin
  7506. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7507. begin
  7508. { Exceeded lower bound but not upper bound }
  7509. TargetSize := MaxSize;
  7510. end
  7511. else if not LowerUnsignedOverflow then
  7512. begin
  7513. { Size didn't exceed lower bound }
  7514. TargetSize := MinSize;
  7515. end
  7516. else
  7517. Exit;
  7518. end;
  7519. case TargetSize of
  7520. S_B:
  7521. TargetSubReg := R_SUBL;
  7522. S_W:
  7523. TargetSubReg := R_SUBW;
  7524. S_L:
  7525. TargetSubReg := R_SUBD;
  7526. else
  7527. InternalError(2020112350);
  7528. end;
  7529. { Update the register to its new size }
  7530. setsubreg(ThisReg, TargetSubReg);
  7531. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7532. begin
  7533. { Check to see if the active register is used afterwards;
  7534. if not, we can change it and make a saving. }
  7535. RegInUse := False;
  7536. TransferUsedRegs(TmpUsedRegs);
  7537. { The target register may be marked as in use to cross
  7538. a jump to a distant label, so exclude it }
  7539. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7540. hp2 := p;
  7541. repeat
  7542. { Explicitly check for the excluded register (don't include the first
  7543. instruction as it may be reading from here }
  7544. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7545. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7546. begin
  7547. RegInUse := True;
  7548. Break;
  7549. end;
  7550. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7551. if not GetNextInstruction(hp2, hp2) then
  7552. InternalError(2020112340);
  7553. until (hp2 = hp1);
  7554. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7555. { We might still be able to get away with this }
  7556. RegInUse := not
  7557. (
  7558. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7559. (hp2.typ = ait_instruction) and
  7560. (
  7561. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7562. instruction that doesn't actually contain ThisReg }
  7563. (cs_opt_level3 in current_settings.optimizerswitches) or
  7564. RegInInstruction(ThisReg, hp2)
  7565. ) and
  7566. RegLoadedWithNewValue(ThisReg, hp2)
  7567. );
  7568. if not RegInUse then
  7569. begin
  7570. { Force the register size to the same as this instruction so it can be removed}
  7571. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7572. begin
  7573. TargetSize := S_L;
  7574. TargetSubReg := R_SUBD;
  7575. end
  7576. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7577. begin
  7578. TargetSize := S_W;
  7579. TargetSubReg := R_SUBW;
  7580. end;
  7581. ThisReg := taicpu(hp1).oper[1]^.reg;
  7582. setsubreg(ThisReg, TargetSubReg);
  7583. RegChanged := True;
  7584. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7585. TransferUsedRegs(TmpUsedRegs);
  7586. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7587. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7588. if p = hp1 then
  7589. begin
  7590. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7591. p_removed := True;
  7592. end
  7593. else
  7594. RemoveInstruction(hp1);
  7595. { Instruction will become "mov %reg,%reg" }
  7596. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7597. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7598. begin
  7599. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7600. RemoveCurrentP(p);
  7601. p_removed := True;
  7602. end
  7603. else
  7604. taicpu(p).oper[1]^.reg := ThisReg;
  7605. Result := True;
  7606. end
  7607. else
  7608. begin
  7609. if TargetSize <> MaxSize then
  7610. begin
  7611. { Since the register is in use, we have to force it to
  7612. MaxSize otherwise part of it may become undefined later on }
  7613. TargetSize := MaxSize;
  7614. case TargetSize of
  7615. S_B:
  7616. TargetSubReg := R_SUBL;
  7617. S_W:
  7618. TargetSubReg := R_SUBW;
  7619. S_L:
  7620. TargetSubReg := R_SUBD;
  7621. else
  7622. InternalError(2020112351);
  7623. end;
  7624. setsubreg(ThisReg, TargetSubReg);
  7625. end;
  7626. AdjustFinalLoad;
  7627. end;
  7628. end
  7629. else
  7630. AdjustFinalLoad;
  7631. if not p_removed then
  7632. begin
  7633. if TargetSize = MinSize then
  7634. begin
  7635. { Convert the input MOVZX to a MOV }
  7636. if (taicpu(p).oper[0]^.typ = top_reg) and
  7637. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7638. begin
  7639. { Or remove it completely! }
  7640. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7641. DebugMsg(SPeepholeOptimization + tostr(InstrMax), p);
  7642. RemoveCurrentP(p);
  7643. p_removed := True;
  7644. end
  7645. else
  7646. begin
  7647. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7648. taicpu(p).opcode := A_MOV;
  7649. taicpu(p).oper[1]^.reg := ThisReg;
  7650. taicpu(p).opsize := TargetSize;
  7651. end;
  7652. Result := True;
  7653. end
  7654. else if TargetSize <> MaxSize then
  7655. begin
  7656. case MaxSize of
  7657. S_L:
  7658. if TargetSize = S_W then
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7661. taicpu(p).opsize := S_BW;
  7662. taicpu(p).oper[1]^.reg := ThisReg;
  7663. Result := True;
  7664. end
  7665. else
  7666. InternalError(2020112341);
  7667. S_W:
  7668. if TargetSize = S_L then
  7669. begin
  7670. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7671. taicpu(p).opsize := S_BL;
  7672. taicpu(p).oper[1]^.reg := ThisReg;
  7673. Result := True;
  7674. end
  7675. else
  7676. InternalError(2020112342);
  7677. else
  7678. ;
  7679. end;
  7680. end;
  7681. end;
  7682. { Now go through every instruction we found and change the
  7683. size. If TargetSize = MaxSize, then almost no changes are
  7684. needed and Result can remain False if it hasn't been set
  7685. yet.
  7686. If RegChanged is True, then the register requires changing
  7687. and so the point about TargetSize = MaxSize doesn't apply. }
  7688. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7689. begin
  7690. for LocalIndex := 0 to InstrMax do
  7691. begin
  7692. { If p_removed is true, then the original MOV/Z was removed
  7693. and removing the AND instruction may not be safe if it
  7694. appears first }
  7695. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7696. InternalError(2020112310);
  7697. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7698. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7699. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7700. InstrList[LocalIndex].opsize := TargetSize;
  7701. end;
  7702. Result := True;
  7703. end;
  7704. end;
  7705. begin
  7706. Result := False;
  7707. p_removed := False;
  7708. ThisReg := taicpu(p).oper[1]^.reg;
  7709. { Check for:
  7710. movs/z ###,%ecx (or %cx or %rcx)
  7711. ...
  7712. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7713. (dealloc %ecx)
  7714. Change to:
  7715. mov ###,%cl (if ### = %cl, then remove completely)
  7716. ...
  7717. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  7718. }
  7719. if (getsupreg(ThisReg) = RS_ECX) and
  7720. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  7721. (hp1.typ = ait_instruction) and
  7722. (
  7723. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7724. instruction that doesn't actually contain ECX }
  7725. (cs_opt_level3 in current_settings.optimizerswitches) or
  7726. RegInInstruction(NR_ECX, hp1) or
  7727. (
  7728. { It's common for the shift/rotate's read/write register to be
  7729. initialised in between, so under -O2 and under, search ahead
  7730. one more instruction
  7731. }
  7732. GetNextInstruction(hp1, hp1) and
  7733. (hp1.typ = ait_instruction) and
  7734. RegInInstruction(NR_ECX, hp1)
  7735. )
  7736. ) and
  7737. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  7738. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  7739. begin
  7740. TransferUsedRegs(TmpUsedRegs);
  7741. hp2 := p;
  7742. repeat
  7743. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7744. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7745. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  7746. begin
  7747. case taicpu(p).opsize of
  7748. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7749. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  7750. begin
  7751. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  7752. RemoveCurrentP(p);
  7753. end
  7754. else
  7755. begin
  7756. taicpu(p).opcode := A_MOV;
  7757. taicpu(p).opsize := S_B;
  7758. taicpu(p).oper[1]^.reg := NR_CL;
  7759. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  7760. end;
  7761. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7762. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  7763. begin
  7764. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  7765. RemoveCurrentP(p);
  7766. end
  7767. else
  7768. begin
  7769. taicpu(p).opcode := A_MOV;
  7770. taicpu(p).opsize := S_W;
  7771. taicpu(p).oper[1]^.reg := NR_CX;
  7772. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  7773. end;
  7774. {$ifdef x86_64}
  7775. S_LQ:
  7776. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  7777. begin
  7778. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  7779. RemoveCurrentP(p);
  7780. end
  7781. else
  7782. begin
  7783. taicpu(p).opcode := A_MOV;
  7784. taicpu(p).opsize := S_L;
  7785. taicpu(p).oper[1]^.reg := NR_ECX;
  7786. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  7787. end;
  7788. {$endif x86_64}
  7789. else
  7790. InternalError(2021120401);
  7791. end;
  7792. Result := True;
  7793. Exit;
  7794. end;
  7795. end;
  7796. { This is anything but quick! }
  7797. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  7798. Exit;
  7799. SetLength(InstrList, 0);
  7800. InstrMax := -1;
  7801. case taicpu(p).opsize of
  7802. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7803. begin
  7804. {$if defined(i386) or defined(i8086)}
  7805. { If the target size is 8-bit, make sure we can actually encode it }
  7806. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  7807. Exit;
  7808. {$endif i386 or i8086}
  7809. LowerLimit := $FF;
  7810. SignedLowerLimit := $7F;
  7811. SignedLowerLimitBottom := -128;
  7812. MinSize := S_B;
  7813. if taicpu(p).opsize = S_BW then
  7814. begin
  7815. MaxSize := S_W;
  7816. UpperLimit := $FFFF;
  7817. SignedUpperLimit := $7FFF;
  7818. SignedUpperLimitBottom := -32768;
  7819. end
  7820. else
  7821. begin
  7822. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  7823. MaxSize := S_L;
  7824. UpperLimit := $FFFFFFFF;
  7825. SignedUpperLimit := $7FFFFFFF;
  7826. SignedUpperLimitBottom := -2147483648;
  7827. end;
  7828. end;
  7829. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7830. begin
  7831. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  7832. LowerLimit := $FFFF;
  7833. SignedLowerLimit := $7FFF;
  7834. SignedLowerLimitBottom := -32768;
  7835. UpperLimit := $FFFFFFFF;
  7836. SignedUpperLimit := $7FFFFFFF;
  7837. SignedUpperLimitBottom := -2147483648;
  7838. MinSize := S_W;
  7839. MaxSize := S_L;
  7840. end;
  7841. {$ifdef x86_64}
  7842. S_LQ:
  7843. begin
  7844. { Both the lower and upper limits are set to 32-bit. If a limit
  7845. is breached, then optimisation is impossible }
  7846. LowerLimit := $FFFFFFFF;
  7847. SignedLowerLimit := $7FFFFFFF;
  7848. SignedLowerLimitBottom := -2147483648;
  7849. UpperLimit := $FFFFFFFF;
  7850. SignedUpperLimit := $7FFFFFFF;
  7851. SignedUpperLimitBottom := -2147483648;
  7852. MinSize := S_L;
  7853. MaxSize := S_L;
  7854. end;
  7855. {$endif x86_64}
  7856. else
  7857. InternalError(2020112301);
  7858. end;
  7859. TestValMin := 0;
  7860. TestValMax := LowerLimit;
  7861. TestValSignedMax := SignedLowerLimit;
  7862. TryShiftDownLimit := LowerLimit;
  7863. TryShiftDown := S_NO;
  7864. ShiftDownOverflow := False;
  7865. RegChanged := False;
  7866. BitwiseOnly := True;
  7867. OrXorUsed := False;
  7868. UpperSignedOverflow := False;
  7869. LowerSignedOverflow := False;
  7870. UpperUnsignedOverflow := False;
  7871. LowerUnsignedOverflow := False;
  7872. hp1 := p;
  7873. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  7874. (hp1.typ = ait_instruction) and
  7875. (
  7876. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7877. instruction that doesn't actually contain ThisReg }
  7878. (cs_opt_level3 in current_settings.optimizerswitches) or
  7879. { This allows this Movx optimisation to work through the SETcc instructions
  7880. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  7881. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  7882. skip over these SETcc instructions). }
  7883. (taicpu(hp1).opcode = A_SETcc) or
  7884. RegInInstruction(ThisReg, hp1)
  7885. ) do
  7886. begin
  7887. case taicpu(hp1).opcode of
  7888. A_INC,A_DEC:
  7889. begin
  7890. { Has to be an exact match on the register }
  7891. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  7892. Break;
  7893. if taicpu(hp1).opcode = A_INC then
  7894. begin
  7895. Inc(TestValMin);
  7896. Inc(TestValMax);
  7897. Inc(TestValSignedMax);
  7898. end
  7899. else
  7900. begin
  7901. Dec(TestValMin);
  7902. Dec(TestValMax);
  7903. Dec(TestValSignedMax);
  7904. end;
  7905. end;
  7906. A_TEST, A_CMP:
  7907. begin
  7908. if (
  7909. { Too high a risk of non-linear behaviour that breaks DFA
  7910. here, unless it's cmp $0,%reg, which is equivalent to
  7911. test %reg,%reg }
  7912. OrXorUsed and
  7913. (taicpu(hp1).opcode = A_CMP) and
  7914. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  7915. ) or
  7916. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  7917. { Has to be an exact match on the register }
  7918. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  7919. (
  7920. { Permit "test %reg,%reg" }
  7921. (taicpu(hp1).opcode = A_TEST) and
  7922. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7923. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  7924. ) or
  7925. (taicpu(hp1).oper[0]^.typ <> top_const) or
  7926. { Make sure the comparison value is not smaller than the
  7927. smallest allowed signed value for the minimum size (e.g.
  7928. -128 for 8-bit) }
  7929. not (
  7930. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  7931. { Is it in the negative range? }
  7932. (
  7933. (taicpu(hp1).oper[0]^.val < 0) and
  7934. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  7935. )
  7936. ) then
  7937. Break;
  7938. { Check to see if the active register is used afterwards }
  7939. TransferUsedRegs(TmpUsedRegs);
  7940. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  7941. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7942. begin
  7943. { Make sure the comparison or any previous instructions
  7944. hasn't pushed the test values outside of the range of
  7945. MinSize }
  7946. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7947. begin
  7948. { Exceeded lower bound but not upper bound }
  7949. TargetSize := MaxSize;
  7950. end
  7951. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  7952. begin
  7953. { Size didn't exceed lower bound }
  7954. TargetSize := MinSize;
  7955. end
  7956. else
  7957. Break;
  7958. case TargetSize of
  7959. S_B:
  7960. TargetSubReg := R_SUBL;
  7961. S_W:
  7962. TargetSubReg := R_SUBW;
  7963. S_L:
  7964. TargetSubReg := R_SUBD;
  7965. else
  7966. InternalError(2021051002);
  7967. end;
  7968. { Update the register to its new size }
  7969. setsubreg(ThisReg, TargetSubReg);
  7970. taicpu(hp1).oper[1]^.reg := ThisReg;
  7971. taicpu(hp1).opsize := MinSize;
  7972. { Convert the input MOVZX to a MOV }
  7973. if (taicpu(p).oper[0]^.typ = top_reg) and
  7974. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7975. begin
  7976. { Or remove it completely! }
  7977. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  7978. RemoveCurrentP(p);
  7979. p_removed := True;
  7980. end
  7981. else
  7982. begin
  7983. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  7984. taicpu(p).opcode := A_MOV;
  7985. taicpu(p).oper[1]^.reg := ThisReg;
  7986. taicpu(p).opsize := MinSize;
  7987. end;
  7988. if (InstrMax >= 0) then
  7989. begin
  7990. for Index := 0 to InstrMax do
  7991. begin
  7992. { If p_removed is true, then the original MOV/Z was removed
  7993. and removing the AND instruction may not be safe if it
  7994. appears first }
  7995. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  7996. InternalError(2020112311);
  7997. if InstrList[Index].oper[0]^.typ = top_reg then
  7998. InstrList[Index].oper[0]^.reg := ThisReg;
  7999. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8000. InstrList[Index].opsize := MinSize;
  8001. end;
  8002. end;
  8003. Result := True;
  8004. Exit;
  8005. end;
  8006. end;
  8007. A_SETcc:
  8008. begin
  8009. { This allows this Movx optimisation to work through the SETcc instructions
  8010. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8011. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8012. skip over these SETcc instructions). }
  8013. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8014. { Of course, break out if the current register is used }
  8015. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8016. Break
  8017. else
  8018. { We must use Continue so the instruction doesn't get added
  8019. to InstrList }
  8020. Continue;
  8021. end;
  8022. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8023. begin
  8024. if
  8025. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8026. { Has to be an exact match on the register }
  8027. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8028. (
  8029. (
  8030. (taicpu(hp1).oper[0]^.typ = top_const) and
  8031. (
  8032. (
  8033. (taicpu(hp1).opcode = A_SHL) and
  8034. (
  8035. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8036. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8037. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8038. )
  8039. ) or (
  8040. (taicpu(hp1).opcode <> A_SHL) and
  8041. (
  8042. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8043. { Is it in the negative range? }
  8044. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8045. )
  8046. )
  8047. )
  8048. ) or (
  8049. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8050. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8051. )
  8052. ) then
  8053. Break;
  8054. { Only process OR and XOR if there are only bitwise operations,
  8055. since otherwise they can too easily fool the data flow
  8056. analysis (they can cause non-linear behaviour) }
  8057. case taicpu(hp1).opcode of
  8058. A_ADD:
  8059. begin
  8060. if OrXorUsed then
  8061. { Too high a risk of non-linear behaviour that breaks DFA here }
  8062. Break
  8063. else
  8064. BitwiseOnly := False;
  8065. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8066. begin
  8067. TestValMin := TestValMin * 2;
  8068. TestValMax := TestValMax * 2;
  8069. TestValSignedMax := TestValSignedMax * 2;
  8070. end
  8071. else
  8072. begin
  8073. WorkingValue := taicpu(hp1).oper[0]^.val;
  8074. TestValMin := TestValMin + WorkingValue;
  8075. TestValMax := TestValMax + WorkingValue;
  8076. TestValSignedMax := TestValSignedMax + WorkingValue;
  8077. end;
  8078. end;
  8079. A_SUB:
  8080. begin
  8081. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8082. begin
  8083. TestValMin := 0;
  8084. TestValMax := 0;
  8085. TestValSignedMax := 0;
  8086. end
  8087. else
  8088. begin
  8089. if OrXorUsed then
  8090. { Too high a risk of non-linear behaviour that breaks DFA here }
  8091. Break
  8092. else
  8093. BitwiseOnly := False;
  8094. WorkingValue := taicpu(hp1).oper[0]^.val;
  8095. TestValMin := TestValMin - WorkingValue;
  8096. TestValMax := TestValMax - WorkingValue;
  8097. TestValSignedMax := TestValSignedMax - WorkingValue;
  8098. end;
  8099. end;
  8100. A_AND:
  8101. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8102. begin
  8103. { we might be able to go smaller if AND appears first }
  8104. if InstrMax = -1 then
  8105. case MinSize of
  8106. S_B:
  8107. ;
  8108. S_W:
  8109. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8110. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8111. begin
  8112. TryShiftDown := S_B;
  8113. TryShiftDownLimit := $FF;
  8114. end;
  8115. S_L:
  8116. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8117. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8118. begin
  8119. TryShiftDown := S_B;
  8120. TryShiftDownLimit := $FF;
  8121. end
  8122. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8123. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8124. begin
  8125. TryShiftDown := S_W;
  8126. TryShiftDownLimit := $FFFF;
  8127. end;
  8128. else
  8129. InternalError(2020112320);
  8130. end;
  8131. WorkingValue := taicpu(hp1).oper[0]^.val;
  8132. TestValMin := TestValMin and WorkingValue;
  8133. TestValMax := TestValMax and WorkingValue;
  8134. TestValSignedMax := TestValSignedMax and WorkingValue;
  8135. end;
  8136. A_OR:
  8137. begin
  8138. if not BitwiseOnly then
  8139. Break;
  8140. OrXorUsed := True;
  8141. WorkingValue := taicpu(hp1).oper[0]^.val;
  8142. TestValMin := TestValMin or WorkingValue;
  8143. TestValMax := TestValMax or WorkingValue;
  8144. TestValSignedMax := TestValSignedMax or WorkingValue;
  8145. end;
  8146. A_XOR:
  8147. begin
  8148. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8149. begin
  8150. TestValMin := 0;
  8151. TestValMax := 0;
  8152. TestValSignedMax := 0;
  8153. end
  8154. else
  8155. begin
  8156. if not BitwiseOnly then
  8157. Break;
  8158. OrXorUsed := True;
  8159. WorkingValue := taicpu(hp1).oper[0]^.val;
  8160. TestValMin := TestValMin xor WorkingValue;
  8161. TestValMax := TestValMax xor WorkingValue;
  8162. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8163. end;
  8164. end;
  8165. A_SHL:
  8166. begin
  8167. BitwiseOnly := False;
  8168. WorkingValue := taicpu(hp1).oper[0]^.val;
  8169. TestValMin := TestValMin shl WorkingValue;
  8170. TestValMax := TestValMax shl WorkingValue;
  8171. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8172. end;
  8173. A_SHR,
  8174. { The first instruction was MOVZX, so the value won't be negative }
  8175. A_SAR:
  8176. begin
  8177. if InstrMax <> -1 then
  8178. BitwiseOnly := False
  8179. else
  8180. { we might be able to go smaller if SHR appears first }
  8181. case MinSize of
  8182. S_B:
  8183. ;
  8184. S_W:
  8185. if (taicpu(hp1).oper[0]^.val >= 8) then
  8186. begin
  8187. TryShiftDown := S_B;
  8188. TryShiftDownLimit := $FF;
  8189. TryShiftDownSignedLimit := $7F;
  8190. TryShiftDownSignedLimitLower := -128;
  8191. end;
  8192. S_L:
  8193. if (taicpu(hp1).oper[0]^.val >= 24) then
  8194. begin
  8195. TryShiftDown := S_B;
  8196. TryShiftDownLimit := $FF;
  8197. TryShiftDownSignedLimit := $7F;
  8198. TryShiftDownSignedLimitLower := -128;
  8199. end
  8200. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8201. begin
  8202. TryShiftDown := S_W;
  8203. TryShiftDownLimit := $FFFF;
  8204. TryShiftDownSignedLimit := $7FFF;
  8205. TryShiftDownSignedLimitLower := -32768;
  8206. end;
  8207. else
  8208. InternalError(2020112321);
  8209. end;
  8210. WorkingValue := taicpu(hp1).oper[0]^.val;
  8211. if taicpu(hp1).opcode = A_SAR then
  8212. begin
  8213. TestValMin := SarInt64(TestValMin, WorkingValue);
  8214. TestValMax := SarInt64(TestValMax, WorkingValue);
  8215. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8216. end
  8217. else
  8218. begin
  8219. TestValMin := TestValMin shr WorkingValue;
  8220. TestValMax := TestValMax shr WorkingValue;
  8221. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8222. end;
  8223. end;
  8224. else
  8225. InternalError(2020112303);
  8226. end;
  8227. end;
  8228. (*
  8229. A_IMUL:
  8230. case taicpu(hp1).ops of
  8231. 2:
  8232. begin
  8233. if not MatchOpType(hp1, top_reg, top_reg) or
  8234. { Has to be an exact match on the register }
  8235. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8236. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8237. Break;
  8238. TestValMin := TestValMin * TestValMin;
  8239. TestValMax := TestValMax * TestValMax;
  8240. TestValSignedMax := TestValSignedMax * TestValMax;
  8241. end;
  8242. 3:
  8243. begin
  8244. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8245. { Has to be an exact match on the register }
  8246. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8247. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8248. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8249. { Is it in the negative range? }
  8250. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8251. Break;
  8252. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8253. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8254. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8255. end;
  8256. else
  8257. Break;
  8258. end;
  8259. A_IDIV:
  8260. case taicpu(hp1).ops of
  8261. 3:
  8262. begin
  8263. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8264. { Has to be an exact match on the register }
  8265. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8266. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8267. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8268. { Is it in the negative range? }
  8269. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8270. Break;
  8271. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8272. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8273. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8274. end;
  8275. else
  8276. Break;
  8277. end;
  8278. *)
  8279. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8280. begin
  8281. { If there are no instructions in between, then we might be able to make a saving }
  8282. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8283. Break;
  8284. { We have something like:
  8285. movzbw %dl,%dx
  8286. ...
  8287. movswl %dx,%edx
  8288. Change the latter to a zero-extension then enter the
  8289. A_MOVZX case branch.
  8290. }
  8291. {$ifdef x86_64}
  8292. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8293. begin
  8294. { this becomes a zero extension from 32-bit to 64-bit, but
  8295. the upper 32 bits are already zero, so just delete the
  8296. instruction }
  8297. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8298. RemoveInstruction(hp1);
  8299. Result := True;
  8300. Exit;
  8301. end
  8302. else
  8303. {$endif x86_64}
  8304. begin
  8305. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8306. taicpu(hp1).opcode := A_MOVZX;
  8307. {$ifdef x86_64}
  8308. case taicpu(hp1).opsize of
  8309. S_BQ:
  8310. begin
  8311. taicpu(hp1).opsize := S_BL;
  8312. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8313. end;
  8314. S_WQ:
  8315. begin
  8316. taicpu(hp1).opsize := S_WL;
  8317. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8318. end;
  8319. S_LQ:
  8320. begin
  8321. taicpu(hp1).opcode := A_MOV;
  8322. taicpu(hp1).opsize := S_L;
  8323. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8324. { In this instance, we need to break out because the
  8325. instruction is no longer MOVZX or MOVSXD }
  8326. Result := True;
  8327. Exit;
  8328. end;
  8329. else
  8330. ;
  8331. end;
  8332. {$endif x86_64}
  8333. Result := CompressInstructions;
  8334. Exit;
  8335. end;
  8336. end;
  8337. A_MOVZX:
  8338. begin
  8339. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8340. Break;
  8341. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8342. begin
  8343. if (InstrMax = -1) and
  8344. { Will return false if the second parameter isn't ThisReg
  8345. (can happen on -O2 and under) }
  8346. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8347. begin
  8348. { The two MOVZX instructions are adjacent, so remove the first one }
  8349. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8350. RemoveCurrentP(p);
  8351. Result := True;
  8352. Exit;
  8353. end;
  8354. Break;
  8355. end;
  8356. Result := CompressInstructions;
  8357. Exit;
  8358. end;
  8359. else
  8360. { This includes ADC, SBB and IDIV }
  8361. Break;
  8362. end;
  8363. if not CheckOverflowConditions then
  8364. Break;
  8365. { Contains highest index (so instruction count - 1) }
  8366. Inc(InstrMax);
  8367. if InstrMax > High(InstrList) then
  8368. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8369. InstrList[InstrMax] := taicpu(hp1);
  8370. end;
  8371. end;
  8372. {$pop}
  8373. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8374. var
  8375. hp1 : tai;
  8376. begin
  8377. Result:=false;
  8378. if (taicpu(p).ops >= 2) and
  8379. ((taicpu(p).oper[0]^.typ = top_const) or
  8380. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8381. (taicpu(p).oper[1]^.typ = top_reg) and
  8382. ((taicpu(p).ops = 2) or
  8383. ((taicpu(p).oper[2]^.typ = top_reg) and
  8384. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8385. GetLastInstruction(p,hp1) and
  8386. MatchInstruction(hp1,A_MOV,[]) and
  8387. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8388. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8389. begin
  8390. TransferUsedRegs(TmpUsedRegs);
  8391. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8392. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8393. { change
  8394. mov reg1,reg2
  8395. imul y,reg2 to imul y,reg1,reg2 }
  8396. begin
  8397. taicpu(p).ops := 3;
  8398. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8399. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8400. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8401. RemoveInstruction(hp1);
  8402. result:=true;
  8403. end;
  8404. end;
  8405. end;
  8406. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8407. var
  8408. ThisLabel: TAsmLabel;
  8409. begin
  8410. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8411. ThisLabel.decrefs;
  8412. taicpu(p).opcode := A_RET;
  8413. taicpu(p).is_jmp := false;
  8414. taicpu(p).ops := taicpu(ret_p).ops;
  8415. case taicpu(ret_p).ops of
  8416. 0:
  8417. taicpu(p).clearop(0);
  8418. 1:
  8419. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8420. else
  8421. internalerror(2016041301);
  8422. end;
  8423. { If the original label is now dead, it might turn out that the label
  8424. immediately follows p. As a result, everything beyond it, which will
  8425. be just some final register configuration and a RET instruction, is
  8426. now dead code. [Kit] }
  8427. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8428. running RemoveDeadCodeAfterJump for each RET instruction, because
  8429. this optimisation rarely happens and most RETs appear at the end of
  8430. routines where there is nothing that can be stripped. [Kit] }
  8431. if not ThisLabel.is_used then
  8432. RemoveDeadCodeAfterJump(p);
  8433. end;
  8434. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8435. var
  8436. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8437. Unconditional, PotentialModified: Boolean;
  8438. OperPtr: POper;
  8439. NewRef: TReference;
  8440. InstrList: array of taicpu;
  8441. InstrMax, Index: Integer;
  8442. const
  8443. {$ifdef DEBUG_AOPTCPU}
  8444. SNoFlags: shortstring = ' so the flags aren''t modified';
  8445. {$else DEBUG_AOPTCPU}
  8446. SNoFlags = '';
  8447. {$endif DEBUG_AOPTCPU}
  8448. begin
  8449. Result:=false;
  8450. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8451. begin
  8452. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8453. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8454. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8455. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8456. GetNextInstruction(hp1, hp2) and
  8457. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8458. { Change from: To:
  8459. set(C) %reg j(~C) label
  8460. test %reg,%reg/cmp $0,%reg
  8461. je label
  8462. set(C) %reg j(C) label
  8463. test %reg,%reg/cmp $0,%reg
  8464. jne label
  8465. (Also do something similar with sete/setne instead of je/jne)
  8466. }
  8467. begin
  8468. { Before we do anything else, we need to check the instructions
  8469. in between SETcc and TEST to make sure they don't modify the
  8470. FLAGS register - if -O2 or under, there won't be any
  8471. instructions between SET and TEST }
  8472. TransferUsedRegs(TmpUsedRegs);
  8473. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8474. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8475. begin
  8476. next := p;
  8477. SetLength(InstrList, 0);
  8478. InstrMax := -1;
  8479. PotentialModified := False;
  8480. { Make a note of every instruction that modifies the FLAGS
  8481. register }
  8482. while GetNextInstruction(next, next) and (next <> hp1) do
  8483. begin
  8484. if next.typ <> ait_instruction then
  8485. { GetNextInstructionUsingReg should have returned False }
  8486. InternalError(2021051701);
  8487. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8488. begin
  8489. case taicpu(next).opcode of
  8490. A_SETcc,
  8491. A_CMOVcc,
  8492. A_Jcc:
  8493. begin
  8494. if PotentialModified then
  8495. { Not safe because the flags were modified earlier }
  8496. Exit
  8497. else
  8498. { Condition is the same as the initial SETcc, so this is safe
  8499. (don't add to instruction list though) }
  8500. Continue;
  8501. end;
  8502. A_ADD:
  8503. begin
  8504. if (taicpu(next).opsize = S_B) or
  8505. { LEA doesn't support 8-bit operands }
  8506. (taicpu(next).oper[1]^.typ <> top_reg) or
  8507. { Must write to a register }
  8508. (taicpu(next).oper[0]^.typ = top_ref) then
  8509. { Require a constant or a register }
  8510. Exit;
  8511. PotentialModified := True;
  8512. end;
  8513. A_SUB:
  8514. begin
  8515. if (taicpu(next).opsize = S_B) or
  8516. { LEA doesn't support 8-bit operands }
  8517. (taicpu(next).oper[1]^.typ <> top_reg) or
  8518. { Must write to a register }
  8519. (taicpu(next).oper[0]^.typ <> top_const) or
  8520. (taicpu(next).oper[0]^.val = $80000000) then
  8521. { Can't subtract a register with LEA - also
  8522. check that the value isn't -2^31, as this
  8523. can't be negated }
  8524. Exit;
  8525. PotentialModified := True;
  8526. end;
  8527. A_SAL,
  8528. A_SHL:
  8529. begin
  8530. if (taicpu(next).opsize = S_B) or
  8531. { LEA doesn't support 8-bit operands }
  8532. (taicpu(next).oper[1]^.typ <> top_reg) or
  8533. { Must write to a register }
  8534. (taicpu(next).oper[0]^.typ <> top_const) or
  8535. (taicpu(next).oper[0]^.val < 0) or
  8536. (taicpu(next).oper[0]^.val > 3) then
  8537. Exit;
  8538. PotentialModified := True;
  8539. end;
  8540. A_IMUL:
  8541. begin
  8542. if (taicpu(next).ops <> 3) or
  8543. (taicpu(next).oper[1]^.typ <> top_reg) or
  8544. { Must write to a register }
  8545. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8546. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8547. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8548. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8549. Exit
  8550. else
  8551. PotentialModified := True;
  8552. end;
  8553. else
  8554. { Don't know how to change this, so abort }
  8555. Exit;
  8556. end;
  8557. { Contains highest index (so instruction count - 1) }
  8558. Inc(InstrMax);
  8559. if InstrMax > High(InstrList) then
  8560. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8561. InstrList[InstrMax] := taicpu(next);
  8562. end;
  8563. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8564. end;
  8565. if not Assigned(next) or (next <> hp1) then
  8566. { It should be equal to hp1 }
  8567. InternalError(2021051702);
  8568. { Cycle through each instruction and check to see if we can
  8569. change them to versions that don't modify the flags }
  8570. if (InstrMax >= 0) then
  8571. begin
  8572. for Index := 0 to InstrMax do
  8573. case InstrList[Index].opcode of
  8574. A_ADD:
  8575. begin
  8576. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8577. InstrList[Index].opcode := A_LEA;
  8578. reference_reset(NewRef, 1, []);
  8579. NewRef.base := InstrList[Index].oper[1]^.reg;
  8580. if InstrList[Index].oper[0]^.typ = top_reg then
  8581. begin
  8582. NewRef.index := InstrList[Index].oper[0]^.reg;
  8583. NewRef.scalefactor := 1;
  8584. end
  8585. else
  8586. NewRef.offset := InstrList[Index].oper[0]^.val;
  8587. InstrList[Index].loadref(0, NewRef);
  8588. end;
  8589. A_SUB:
  8590. begin
  8591. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8592. InstrList[Index].opcode := A_LEA;
  8593. reference_reset(NewRef, 1, []);
  8594. NewRef.base := InstrList[Index].oper[1]^.reg;
  8595. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8596. InstrList[Index].loadref(0, NewRef);
  8597. end;
  8598. A_SHL,
  8599. A_SAL:
  8600. begin
  8601. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8602. InstrList[Index].opcode := A_LEA;
  8603. reference_reset(NewRef, 1, []);
  8604. NewRef.index := InstrList[Index].oper[1]^.reg;
  8605. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8606. InstrList[Index].loadref(0, NewRef);
  8607. end;
  8608. A_IMUL:
  8609. begin
  8610. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8611. InstrList[Index].opcode := A_LEA;
  8612. reference_reset(NewRef, 1, []);
  8613. NewRef.index := InstrList[Index].oper[1]^.reg;
  8614. case InstrList[Index].oper[0]^.val of
  8615. 2, 4, 8:
  8616. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8617. else {3, 5 and 9}
  8618. begin
  8619. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8620. NewRef.base := InstrList[Index].oper[1]^.reg;
  8621. end;
  8622. end;
  8623. InstrList[Index].loadref(0, NewRef);
  8624. end;
  8625. else
  8626. InternalError(2021051710);
  8627. end;
  8628. end;
  8629. { Mark the FLAGS register as used across this whole block }
  8630. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8631. end;
  8632. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8633. JumpC := taicpu(hp2).condition;
  8634. Unconditional := False;
  8635. if conditions_equal(JumpC, C_E) then
  8636. SetC := inverse_cond(taicpu(p).condition)
  8637. else if conditions_equal(JumpC, C_NE) then
  8638. SetC := taicpu(p).condition
  8639. else
  8640. { We've got something weird here (and inefficent) }
  8641. begin
  8642. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8643. SetC := C_NONE;
  8644. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8645. if condition_in(C_AE, JumpC) then
  8646. Unconditional := True
  8647. else
  8648. { Not sure what to do with this jump - drop out }
  8649. Exit;
  8650. end;
  8651. RemoveInstruction(hp1);
  8652. if Unconditional then
  8653. MakeUnconditional(taicpu(hp2))
  8654. else
  8655. begin
  8656. if SetC = C_NONE then
  8657. InternalError(2018061402);
  8658. taicpu(hp2).SetCondition(SetC);
  8659. end;
  8660. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8661. TmpUsedRegs }
  8662. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8663. begin
  8664. RemoveCurrentp(p, hp2);
  8665. if taicpu(hp2).opcode = A_SETcc then
  8666. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8667. else
  8668. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8669. end
  8670. else
  8671. if taicpu(hp2).opcode = A_SETcc then
  8672. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8673. else
  8674. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8675. Result := True;
  8676. end
  8677. else if
  8678. { Make sure the instructions are adjacent }
  8679. (
  8680. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8681. GetNextInstruction(p, hp1)
  8682. ) and
  8683. MatchInstruction(hp1, A_MOV, [S_B]) and
  8684. { Writing to memory is allowed }
  8685. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8686. begin
  8687. {
  8688. Watch out for sequences such as:
  8689. set(c)b %regb
  8690. movb %regb,(ref)
  8691. movb $0,1(ref)
  8692. movb $0,2(ref)
  8693. movb $0,3(ref)
  8694. Much more efficient to turn it into:
  8695. movl $0,%regl
  8696. set(c)b %regb
  8697. movl %regl,(ref)
  8698. Or:
  8699. set(c)b %regb
  8700. movzbl %regb,%regl
  8701. movl %regl,(ref)
  8702. }
  8703. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8704. GetNextInstruction(hp1, hp2) and
  8705. MatchInstruction(hp2, A_MOV, [S_B]) and
  8706. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8707. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8708. begin
  8709. { Don't do anything else except set Result to True }
  8710. end
  8711. else
  8712. begin
  8713. if taicpu(p).oper[0]^.typ = top_reg then
  8714. begin
  8715. TransferUsedRegs(TmpUsedRegs);
  8716. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8717. end;
  8718. { If it's not a register, it's a memory address }
  8719. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  8720. begin
  8721. { Even if the register is still in use, we can minimise the
  8722. pipeline stall by changing the MOV into another SETcc. }
  8723. taicpu(hp1).opcode := A_SETcc;
  8724. taicpu(hp1).condition := taicpu(p).condition;
  8725. if taicpu(hp1).oper[1]^.typ = top_ref then
  8726. begin
  8727. { Swapping the operand pointers like this is probably a
  8728. bit naughty, but it is far faster than using loadoper
  8729. to transfer the reference from oper[1] to oper[0] if
  8730. you take into account the extra procedure calls and
  8731. the memory allocation and deallocation required }
  8732. OperPtr := taicpu(hp1).oper[1];
  8733. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  8734. taicpu(hp1).oper[0] := OperPtr;
  8735. end
  8736. else
  8737. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  8738. taicpu(hp1).clearop(1);
  8739. taicpu(hp1).ops := 1;
  8740. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  8741. end
  8742. else
  8743. begin
  8744. if taicpu(hp1).oper[1]^.typ = top_reg then
  8745. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  8746. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8747. RemoveInstruction(hp1);
  8748. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  8749. end
  8750. end;
  8751. Result := True;
  8752. end;
  8753. end;
  8754. end;
  8755. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  8756. var
  8757. hp1: tai;
  8758. Count: Integer;
  8759. OrigLabel: TAsmLabel;
  8760. begin
  8761. result := False;
  8762. { Sometimes, the optimisations below can permit this }
  8763. RemoveDeadCodeAfterJump(p);
  8764. 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
  8765. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  8766. begin
  8767. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8768. { Also a side-effect of optimisations }
  8769. if CollapseZeroDistJump(p, OrigLabel) then
  8770. begin
  8771. Result := True;
  8772. Exit;
  8773. end;
  8774. hp1 := GetLabelWithSym(OrigLabel);
  8775. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  8776. begin
  8777. case taicpu(hp1).opcode of
  8778. A_RET:
  8779. {
  8780. change
  8781. jmp .L1
  8782. ...
  8783. .L1:
  8784. ret
  8785. into
  8786. ret
  8787. }
  8788. begin
  8789. ConvertJumpToRET(p, hp1);
  8790. result:=true;
  8791. end;
  8792. { Check any kind of direct assignment instruction }
  8793. A_MOV,
  8794. A_MOVD,
  8795. A_MOVQ,
  8796. A_MOVSX,
  8797. {$ifdef x86_64}
  8798. A_MOVSXD,
  8799. {$endif x86_64}
  8800. A_MOVZX,
  8801. A_MOVAPS,
  8802. A_MOVUPS,
  8803. A_MOVSD,
  8804. A_MOVAPD,
  8805. A_MOVUPD,
  8806. A_MOVDQA,
  8807. A_MOVDQU,
  8808. A_VMOVSS,
  8809. A_VMOVAPS,
  8810. A_VMOVUPS,
  8811. A_VMOVSD,
  8812. A_VMOVAPD,
  8813. A_VMOVUPD,
  8814. A_VMOVDQA,
  8815. A_VMOVDQU:
  8816. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  8817. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  8818. begin
  8819. Result := True;
  8820. Exit;
  8821. end;
  8822. else
  8823. ;
  8824. end;
  8825. end;
  8826. end;
  8827. end;
  8828. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  8829. begin
  8830. CanBeCMOV:=assigned(p) and
  8831. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  8832. { we can't use cmov ref,reg because
  8833. ref could be nil and cmov still throws an exception
  8834. if ref=nil but the mov isn't done (FK)
  8835. or ((taicpu(p).oper[0]^.typ = top_ref) and
  8836. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  8837. }
  8838. (taicpu(p).oper[1]^.typ = top_reg) and
  8839. (
  8840. (taicpu(p).oper[0]^.typ = top_reg) or
  8841. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  8842. it is not expected that this can cause a seg. violation }
  8843. (
  8844. (taicpu(p).oper[0]^.typ = top_ref) and
  8845. IsRefSafe(taicpu(p).oper[0]^.ref)
  8846. )
  8847. );
  8848. end;
  8849. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  8850. var
  8851. hp1,hp2: tai;
  8852. {$ifndef i8086}
  8853. hp3,hp4,hpmov2, hp5: tai;
  8854. l : Longint;
  8855. condition : TAsmCond;
  8856. {$endif i8086}
  8857. carryadd_opcode : TAsmOp;
  8858. symbol: TAsmSymbol;
  8859. reg: tsuperregister;
  8860. increg, tmpreg: TRegister;
  8861. begin
  8862. result:=false;
  8863. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  8864. begin
  8865. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8866. if (
  8867. (
  8868. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  8869. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  8870. (Taicpu(hp1).oper[0]^.val=1)
  8871. ) or
  8872. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  8873. ) and
  8874. GetNextInstruction(hp1,hp2) and
  8875. SkipAligns(hp2, hp2) and
  8876. (hp2.typ = ait_label) and
  8877. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  8878. { jb @@1 cmc
  8879. inc/dec operand --> adc/sbb operand,0
  8880. @@1:
  8881. ... and ...
  8882. jnb @@1
  8883. inc/dec operand --> adc/sbb operand,0
  8884. @@1: }
  8885. begin
  8886. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  8887. begin
  8888. case taicpu(hp1).opcode of
  8889. A_INC,
  8890. A_ADD:
  8891. carryadd_opcode:=A_ADC;
  8892. A_DEC,
  8893. A_SUB:
  8894. carryadd_opcode:=A_SBB;
  8895. else
  8896. InternalError(2021011001);
  8897. end;
  8898. Taicpu(p).clearop(0);
  8899. Taicpu(p).ops:=0;
  8900. Taicpu(p).is_jmp:=false;
  8901. Taicpu(p).opcode:=A_CMC;
  8902. Taicpu(p).condition:=C_NONE;
  8903. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  8904. Taicpu(hp1).ops:=2;
  8905. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8906. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8907. else
  8908. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8909. Taicpu(hp1).loadconst(0,0);
  8910. Taicpu(hp1).opcode:=carryadd_opcode;
  8911. result:=true;
  8912. exit;
  8913. end
  8914. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  8915. begin
  8916. case taicpu(hp1).opcode of
  8917. A_INC,
  8918. A_ADD:
  8919. carryadd_opcode:=A_ADC;
  8920. A_DEC,
  8921. A_SUB:
  8922. carryadd_opcode:=A_SBB;
  8923. else
  8924. InternalError(2021011002);
  8925. end;
  8926. Taicpu(hp1).ops:=2;
  8927. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  8928. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  8929. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  8930. else
  8931. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  8932. Taicpu(hp1).loadconst(0,0);
  8933. Taicpu(hp1).opcode:=carryadd_opcode;
  8934. RemoveCurrentP(p, hp1);
  8935. result:=true;
  8936. exit;
  8937. end
  8938. {
  8939. jcc @@1 setcc tmpreg
  8940. inc/dec/add/sub operand -> (movzx tmpreg)
  8941. @@1: add/sub tmpreg,operand
  8942. While this increases code size slightly, it makes the code much faster if the
  8943. jump is unpredictable
  8944. }
  8945. else if not(cs_opt_size in current_settings.optimizerswitches) then
  8946. begin
  8947. { search for an available register which is volatile }
  8948. for reg in tcpuregisterset do
  8949. begin
  8950. if
  8951. {$if defined(i386) or defined(i8086)}
  8952. { Only use registers whose lowest 8-bits can Be accessed }
  8953. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  8954. {$endif i386 or i8086}
  8955. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  8956. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  8957. { We don't need to check if tmpreg is in hp1 or not, because
  8958. it will be marked as in use at p (if not, this is
  8959. indictive of a compiler bug). }
  8960. then
  8961. begin
  8962. TAsmLabel(symbol).decrefs;
  8963. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  8964. Taicpu(p).clearop(0);
  8965. Taicpu(p).ops:=1;
  8966. Taicpu(p).is_jmp:=false;
  8967. Taicpu(p).opcode:=A_SETcc;
  8968. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  8969. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  8970. Taicpu(p).loadreg(0,increg);
  8971. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  8972. begin
  8973. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  8974. R_SUBW:
  8975. begin
  8976. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  8977. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  8978. end;
  8979. R_SUBD:
  8980. begin
  8981. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  8982. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  8983. end;
  8984. {$ifdef x86_64}
  8985. R_SUBQ:
  8986. begin
  8987. { MOVZX doesn't have a 64-bit variant, because
  8988. the 32-bit version implicitly zeroes the
  8989. upper 32-bits of the destination register }
  8990. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  8991. newreg(R_INTREGISTER,reg,R_SUBD));
  8992. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  8993. end;
  8994. {$endif x86_64}
  8995. else
  8996. Internalerror(2020030601);
  8997. end;
  8998. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  8999. asml.InsertAfter(hp2,p);
  9000. end
  9001. else
  9002. tmpreg := increg;
  9003. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9004. begin
  9005. Taicpu(hp1).ops:=2;
  9006. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9007. end;
  9008. Taicpu(hp1).loadreg(0,tmpreg);
  9009. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9010. Result := True;
  9011. { p is no longer a Jcc instruction, so exit }
  9012. Exit;
  9013. end;
  9014. end;
  9015. end;
  9016. end;
  9017. { Detect the following:
  9018. jmp<cond> @Lbl1
  9019. jmp @Lbl2
  9020. ...
  9021. @Lbl1:
  9022. ret
  9023. Change to:
  9024. jmp<inv_cond> @Lbl2
  9025. ret
  9026. }
  9027. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9028. begin
  9029. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9030. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9031. MatchInstruction(hp2,A_RET,[S_NO]) then
  9032. begin
  9033. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9034. { Change label address to that of the unconditional jump }
  9035. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9036. TAsmLabel(symbol).DecRefs;
  9037. taicpu(hp1).opcode := A_RET;
  9038. taicpu(hp1).is_jmp := false;
  9039. taicpu(hp1).ops := taicpu(hp2).ops;
  9040. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9041. case taicpu(hp2).ops of
  9042. 0:
  9043. taicpu(hp1).clearop(0);
  9044. 1:
  9045. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9046. else
  9047. internalerror(2016041302);
  9048. end;
  9049. end;
  9050. {$ifndef i8086}
  9051. end
  9052. {
  9053. convert
  9054. j<c> .L1
  9055. mov 1,reg
  9056. jmp .L2
  9057. .L1
  9058. mov 0,reg
  9059. .L2
  9060. into
  9061. mov 0,reg
  9062. set<not(c)> reg
  9063. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9064. would destroy the flag contents
  9065. }
  9066. else if MatchInstruction(hp1,A_MOV,[]) and
  9067. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9068. {$ifdef i386}
  9069. (
  9070. { Under i386, ESI, EDI, EBP and ESP
  9071. don't have an 8-bit representation }
  9072. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9073. ) and
  9074. {$endif i386}
  9075. (taicpu(hp1).oper[0]^.val=1) and
  9076. GetNextInstruction(hp1,hp2) and
  9077. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9078. GetNextInstruction(hp2,hp3) and
  9079. { skip align }
  9080. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9081. (hp3.typ=ait_label) and
  9082. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9083. (tai_label(hp3).labsym.getrefs=1) and
  9084. GetNextInstruction(hp3,hp4) and
  9085. MatchInstruction(hp4,A_MOV,[]) and
  9086. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9087. (taicpu(hp4).oper[0]^.val=0) and
  9088. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9089. GetNextInstruction(hp4,hp5) and
  9090. (hp5.typ=ait_label) and
  9091. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9092. (tai_label(hp5).labsym.getrefs=1) then
  9093. begin
  9094. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9095. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9096. { remove last label }
  9097. RemoveInstruction(hp5);
  9098. { remove second label }
  9099. RemoveInstruction(hp3);
  9100. { if align is present remove it }
  9101. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9102. RemoveInstruction(hp3);
  9103. { remove jmp }
  9104. RemoveInstruction(hp2);
  9105. if taicpu(hp1).opsize=S_B then
  9106. RemoveInstruction(hp1)
  9107. else
  9108. taicpu(hp1).loadconst(0,0);
  9109. taicpu(hp4).opcode:=A_SETcc;
  9110. taicpu(hp4).opsize:=S_B;
  9111. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9112. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9113. taicpu(hp4).opercnt:=1;
  9114. taicpu(hp4).ops:=1;
  9115. taicpu(hp4).freeop(1);
  9116. RemoveCurrentP(p);
  9117. Result:=true;
  9118. exit;
  9119. end
  9120. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9121. begin
  9122. { check for
  9123. jCC xxx
  9124. <several movs>
  9125. xxx:
  9126. }
  9127. l:=0;
  9128. while assigned(hp1) and
  9129. CanBeCMOV(hp1) and
  9130. { stop on labels }
  9131. not(hp1.typ=ait_label) do
  9132. begin
  9133. inc(l);
  9134. GetNextInstruction(hp1,hp1);
  9135. end;
  9136. if assigned(hp1) then
  9137. begin
  9138. if FindLabel(tasmlabel(symbol),hp1) then
  9139. begin
  9140. if (l<=4) and (l>0) then
  9141. begin
  9142. condition:=inverse_cond(taicpu(p).condition);
  9143. UpdateUsedRegs(tai(p.next));
  9144. GetNextInstruction(p,hp1);
  9145. repeat
  9146. if not Assigned(hp1) then
  9147. InternalError(2018062900);
  9148. taicpu(hp1).opcode:=A_CMOVcc;
  9149. taicpu(hp1).condition:=condition;
  9150. UpdateUsedRegs(tai(hp1.next));
  9151. GetNextInstruction(hp1,hp1);
  9152. until not(CanBeCMOV(hp1));
  9153. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9154. hp2 := hp1;
  9155. repeat
  9156. if not Assigned(hp2) then
  9157. InternalError(2018062910);
  9158. case hp2.typ of
  9159. ait_label:
  9160. { What we expected - break out of the loop (it won't be a dead label at the top of
  9161. a cluster because that was optimised at an earlier stage) }
  9162. Break;
  9163. ait_align:
  9164. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9165. begin
  9166. hp2 := tai(hp2.Next);
  9167. Continue;
  9168. end;
  9169. else
  9170. begin
  9171. { Might be a comment or temporary allocation entry }
  9172. if not (hp2.typ in SkipInstr) then
  9173. InternalError(2018062911);
  9174. hp2 := tai(hp2.Next);
  9175. Continue;
  9176. end;
  9177. end;
  9178. until False;
  9179. { Now we can safely decrement the reference count }
  9180. tasmlabel(symbol).decrefs;
  9181. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9182. { Remove the original jump }
  9183. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9184. UpdateUsedRegs(tai(hp2.next));
  9185. GetNextInstruction(hp2, p); { Instruction after the label }
  9186. { Remove the label if this is its final reference }
  9187. if (tasmlabel(symbol).getrefs=0) then
  9188. StripLabelFast(hp1);
  9189. if Assigned(p) then
  9190. result:=true;
  9191. exit;
  9192. end;
  9193. end
  9194. else
  9195. begin
  9196. { check further for
  9197. jCC xxx
  9198. <several movs 1>
  9199. jmp yyy
  9200. xxx:
  9201. <several movs 2>
  9202. yyy:
  9203. }
  9204. { hp2 points to jmp yyy }
  9205. hp2:=hp1;
  9206. { skip hp1 to xxx (or an align right before it) }
  9207. GetNextInstruction(hp1, hp1);
  9208. if assigned(hp2) and
  9209. assigned(hp1) and
  9210. (l<=3) and
  9211. (hp2.typ=ait_instruction) and
  9212. (taicpu(hp2).is_jmp) and
  9213. (taicpu(hp2).condition=C_None) and
  9214. { real label and jump, no further references to the
  9215. label are allowed }
  9216. (tasmlabel(symbol).getrefs=1) and
  9217. FindLabel(tasmlabel(symbol),hp1) then
  9218. begin
  9219. l:=0;
  9220. { skip hp1 to <several moves 2> }
  9221. if (hp1.typ = ait_align) then
  9222. GetNextInstruction(hp1, hp1);
  9223. GetNextInstruction(hp1, hpmov2);
  9224. hp1 := hpmov2;
  9225. while assigned(hp1) and
  9226. CanBeCMOV(hp1) do
  9227. begin
  9228. inc(l);
  9229. GetNextInstruction(hp1, hp1);
  9230. end;
  9231. { hp1 points to yyy (or an align right before it) }
  9232. hp3 := hp1;
  9233. if assigned(hp1) and
  9234. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9235. begin
  9236. condition:=inverse_cond(taicpu(p).condition);
  9237. UpdateUsedRegs(tai(p.next));
  9238. GetNextInstruction(p,hp1);
  9239. repeat
  9240. taicpu(hp1).opcode:=A_CMOVcc;
  9241. taicpu(hp1).condition:=condition;
  9242. UpdateUsedRegs(tai(hp1.next));
  9243. GetNextInstruction(hp1,hp1);
  9244. until not(assigned(hp1)) or
  9245. not(CanBeCMOV(hp1));
  9246. condition:=inverse_cond(condition);
  9247. if GetLastInstruction(hpmov2,hp1) then
  9248. UpdateUsedRegs(tai(hp1.next));
  9249. hp1 := hpmov2;
  9250. { hp1 is now at <several movs 2> }
  9251. while Assigned(hp1) and CanBeCMOV(hp1) do
  9252. begin
  9253. taicpu(hp1).opcode:=A_CMOVcc;
  9254. taicpu(hp1).condition:=condition;
  9255. UpdateUsedRegs(tai(hp1.next));
  9256. GetNextInstruction(hp1,hp1);
  9257. end;
  9258. hp1 := p;
  9259. { Get first instruction after label }
  9260. UpdateUsedRegs(tai(hp3.next));
  9261. GetNextInstruction(hp3, p);
  9262. if assigned(p) and (hp3.typ = ait_align) then
  9263. GetNextInstruction(p, p);
  9264. { Don't dereference yet, as doing so will cause
  9265. GetNextInstruction to skip the label and
  9266. optional align marker. [Kit] }
  9267. GetNextInstruction(hp2, hp4);
  9268. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9269. { remove jCC }
  9270. RemoveInstruction(hp1);
  9271. { Now we can safely decrement it }
  9272. tasmlabel(symbol).decrefs;
  9273. { Remove label xxx (it will have a ref of zero due to the initial check }
  9274. StripLabelFast(hp4);
  9275. { remove jmp }
  9276. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9277. RemoveInstruction(hp2);
  9278. { As before, now we can safely decrement it }
  9279. tasmlabel(symbol).decrefs;
  9280. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9281. if tasmlabel(symbol).getrefs = 0 then
  9282. StripLabelFast(hp3);
  9283. if Assigned(p) then
  9284. result:=true;
  9285. exit;
  9286. end;
  9287. end;
  9288. end;
  9289. end;
  9290. {$endif i8086}
  9291. end;
  9292. end;
  9293. end;
  9294. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9295. var
  9296. hp1,hp2,hp3: tai;
  9297. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9298. NewSize: TOpSize;
  9299. NewRegSize: TSubRegister;
  9300. Limit: TCgInt;
  9301. SwapOper: POper;
  9302. begin
  9303. result:=false;
  9304. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9305. GetNextInstruction(p,hp1) and
  9306. (hp1.typ = ait_instruction);
  9307. if reg_and_hp1_is_instr and
  9308. (
  9309. (taicpu(hp1).opcode <> A_LEA) or
  9310. { If the LEA instruction can be converted into an arithmetic instruction,
  9311. it may be possible to then fold it. }
  9312. (
  9313. { If the flags register is in use, don't change the instruction
  9314. to an ADD otherwise this will scramble the flags. [Kit] }
  9315. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9316. ConvertLEA(taicpu(hp1))
  9317. )
  9318. ) and
  9319. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9320. GetNextInstruction(hp1,hp2) and
  9321. MatchInstruction(hp2,A_MOV,[]) and
  9322. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9323. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9324. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9325. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9326. {$ifdef i386}
  9327. { not all registers have byte size sub registers on i386 }
  9328. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9329. {$endif i386}
  9330. (((taicpu(hp1).ops=2) and
  9331. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9332. ((taicpu(hp1).ops=1) and
  9333. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9334. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9335. begin
  9336. { change movsX/movzX reg/ref, reg2
  9337. add/sub/or/... reg3/$const, reg2
  9338. mov reg2 reg/ref
  9339. to add/sub/or/... reg3/$const, reg/ref }
  9340. { by example:
  9341. movswl %si,%eax movswl %si,%eax p
  9342. decl %eax addl %edx,%eax hp1
  9343. movw %ax,%si movw %ax,%si hp2
  9344. ->
  9345. movswl %si,%eax movswl %si,%eax p
  9346. decw %eax addw %edx,%eax hp1
  9347. movw %ax,%si movw %ax,%si hp2
  9348. }
  9349. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9350. {
  9351. ->
  9352. movswl %si,%eax movswl %si,%eax p
  9353. decw %si addw %dx,%si hp1
  9354. movw %ax,%si movw %ax,%si hp2
  9355. }
  9356. case taicpu(hp1).ops of
  9357. 1:
  9358. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9359. 2:
  9360. begin
  9361. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9362. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9363. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9364. end;
  9365. else
  9366. internalerror(2008042702);
  9367. end;
  9368. {
  9369. ->
  9370. decw %si addw %dx,%si p
  9371. }
  9372. DebugMsg(SPeepholeOptimization + 'var3',p);
  9373. RemoveCurrentP(p, hp1);
  9374. RemoveInstruction(hp2);
  9375. Result := True;
  9376. Exit;
  9377. end;
  9378. if reg_and_hp1_is_instr and
  9379. (taicpu(hp1).opcode = A_MOV) and
  9380. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9381. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9382. {$ifdef x86_64}
  9383. { check for implicit extension to 64 bit }
  9384. or
  9385. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9386. (taicpu(hp1).opsize=S_Q) and
  9387. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9388. )
  9389. {$endif x86_64}
  9390. )
  9391. then
  9392. begin
  9393. { change
  9394. movx %reg1,%reg2
  9395. mov %reg2,%reg3
  9396. dealloc %reg2
  9397. into
  9398. movx %reg,%reg3
  9399. }
  9400. TransferUsedRegs(TmpUsedRegs);
  9401. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9402. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9403. begin
  9404. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9405. {$ifdef x86_64}
  9406. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9407. (taicpu(hp1).opsize=S_Q) then
  9408. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9409. else
  9410. {$endif x86_64}
  9411. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9412. RemoveInstruction(hp1);
  9413. Result := True;
  9414. Exit;
  9415. end;
  9416. end;
  9417. if reg_and_hp1_is_instr and
  9418. ((taicpu(hp1).opcode=A_MOV) or
  9419. (taicpu(hp1).opcode=A_ADD) or
  9420. (taicpu(hp1).opcode=A_SUB) or
  9421. (taicpu(hp1).opcode=A_CMP) or
  9422. (taicpu(hp1).opcode=A_OR) or
  9423. (taicpu(hp1).opcode=A_XOR) or
  9424. (taicpu(hp1).opcode=A_AND)
  9425. ) and
  9426. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9427. begin
  9428. AndTest := (taicpu(hp1).opcode=A_AND) and
  9429. GetNextInstruction(hp1, hp2) and
  9430. (hp2.typ = ait_instruction) and
  9431. (
  9432. (
  9433. (taicpu(hp2).opcode=A_TEST) and
  9434. (
  9435. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9436. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9437. (
  9438. { If the AND and TEST instructions share a constant, this is also valid }
  9439. (taicpu(hp1).oper[0]^.typ = top_const) and
  9440. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9441. )
  9442. ) and
  9443. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9444. ) or
  9445. (
  9446. (taicpu(hp2).opcode=A_CMP) and
  9447. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9448. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9449. )
  9450. );
  9451. { change
  9452. movx (oper),%reg2
  9453. and $x,%reg2
  9454. test %reg2,%reg2
  9455. dealloc %reg2
  9456. into
  9457. op %reg1,%reg3
  9458. if the second op accesses only the bits stored in reg1
  9459. }
  9460. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9461. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9462. (taicpu(hp1).oper[0]^.typ = top_const) and
  9463. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9464. AndTest then
  9465. begin
  9466. { Check if the AND constant is in range }
  9467. case taicpu(p).opsize of
  9468. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9469. begin
  9470. NewSize := S_B;
  9471. Limit := $FF;
  9472. end;
  9473. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9474. begin
  9475. NewSize := S_W;
  9476. Limit := $FFFF;
  9477. end;
  9478. {$ifdef x86_64}
  9479. S_LQ:
  9480. begin
  9481. NewSize := S_L;
  9482. Limit := $FFFFFFFF;
  9483. end;
  9484. {$endif x86_64}
  9485. else
  9486. InternalError(2021120303);
  9487. end;
  9488. if (
  9489. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9490. { Check for negative operands }
  9491. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9492. ) and
  9493. GetNextInstruction(hp2,hp3) and
  9494. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9495. (taicpu(hp3).condition in [C_E,C_NE]) then
  9496. begin
  9497. TransferUsedRegs(TmpUsedRegs);
  9498. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9499. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9500. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9501. begin
  9502. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9503. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9504. taicpu(hp1).opcode := A_TEST;
  9505. taicpu(hp1).opsize := NewSize;
  9506. RemoveInstruction(hp2);
  9507. RemoveCurrentP(p, hp1);
  9508. Result:=true;
  9509. exit;
  9510. end;
  9511. end;
  9512. end;
  9513. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9514. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9515. (taicpu(hp1).opsize=S_B)) or
  9516. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9517. (taicpu(hp1).opsize=S_W))
  9518. {$ifdef x86_64}
  9519. or ((taicpu(p).opsize=S_LQ) and
  9520. (taicpu(hp1).opsize=S_L))
  9521. {$endif x86_64}
  9522. ) and
  9523. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9524. begin
  9525. { change
  9526. movx %reg1,%reg2
  9527. op %reg2,%reg3
  9528. dealloc %reg2
  9529. into
  9530. op %reg1,%reg3
  9531. if the second op accesses only the bits stored in reg1
  9532. }
  9533. TransferUsedRegs(TmpUsedRegs);
  9534. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9535. if AndTest then
  9536. begin
  9537. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9538. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9539. end
  9540. else
  9541. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9542. if not RegUsed then
  9543. begin
  9544. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9545. if taicpu(p).oper[0]^.typ=top_reg then
  9546. begin
  9547. case taicpu(hp1).opsize of
  9548. S_B:
  9549. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9550. S_W:
  9551. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9552. S_L:
  9553. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9554. else
  9555. Internalerror(2020102301);
  9556. end;
  9557. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9558. end
  9559. else
  9560. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9561. RemoveCurrentP(p);
  9562. if AndTest then
  9563. RemoveInstruction(hp2);
  9564. result:=true;
  9565. exit;
  9566. end;
  9567. end
  9568. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9569. (
  9570. { Bitwise operations only }
  9571. (taicpu(hp1).opcode=A_AND) or
  9572. (taicpu(hp1).opcode=A_TEST) or
  9573. (
  9574. (taicpu(hp1).oper[0]^.typ = top_const) and
  9575. (
  9576. (taicpu(hp1).opcode=A_OR) or
  9577. (taicpu(hp1).opcode=A_XOR)
  9578. )
  9579. )
  9580. ) and
  9581. (
  9582. (taicpu(hp1).oper[0]^.typ = top_const) or
  9583. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9584. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9585. ) then
  9586. begin
  9587. { change
  9588. movx %reg2,%reg2
  9589. op const,%reg2
  9590. into
  9591. op const,%reg2 (smaller version)
  9592. movx %reg2,%reg2
  9593. also change
  9594. movx %reg1,%reg2
  9595. and/test (oper),%reg2
  9596. dealloc %reg2
  9597. into
  9598. and/test (oper),%reg1
  9599. }
  9600. case taicpu(p).opsize of
  9601. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9602. begin
  9603. NewSize := S_B;
  9604. NewRegSize := R_SUBL;
  9605. Limit := $FF;
  9606. end;
  9607. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9608. begin
  9609. NewSize := S_W;
  9610. NewRegSize := R_SUBW;
  9611. Limit := $FFFF;
  9612. end;
  9613. {$ifdef x86_64}
  9614. S_LQ:
  9615. begin
  9616. NewSize := S_L;
  9617. NewRegSize := R_SUBD;
  9618. Limit := $FFFFFFFF;
  9619. end;
  9620. {$endif x86_64}
  9621. else
  9622. Internalerror(2021120302);
  9623. end;
  9624. TransferUsedRegs(TmpUsedRegs);
  9625. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9626. if AndTest then
  9627. begin
  9628. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9629. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9630. end
  9631. else
  9632. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9633. if
  9634. (
  9635. (taicpu(p).opcode = A_MOVZX) and
  9636. (
  9637. (taicpu(hp1).opcode=A_AND) or
  9638. (taicpu(hp1).opcode=A_TEST)
  9639. ) and
  9640. not (
  9641. { If both are references, then the final instruction will have
  9642. both operands as references, which is not allowed }
  9643. (taicpu(p).oper[0]^.typ = top_ref) and
  9644. (taicpu(hp1).oper[0]^.typ = top_ref)
  9645. ) and
  9646. not RegUsed
  9647. ) or
  9648. (
  9649. (
  9650. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9651. not RegUsed
  9652. ) and
  9653. (taicpu(p).oper[0]^.typ = top_reg) and
  9654. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9655. (taicpu(hp1).oper[0]^.typ = top_const) and
  9656. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9657. ) then
  9658. begin
  9659. {$if defined(i386) or defined(i8086)}
  9660. { If the target size is 8-bit, make sure we can actually encode it }
  9661. 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
  9662. Exit;
  9663. {$endif i386 or i8086}
  9664. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9665. taicpu(hp1).opsize := NewSize;
  9666. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9667. if AndTest then
  9668. begin
  9669. RemoveInstruction(hp2);
  9670. if not RegUsed then
  9671. begin
  9672. taicpu(hp1).opcode := A_TEST;
  9673. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9674. begin
  9675. { Make sure the reference is the second operand }
  9676. SwapOper := taicpu(hp1).oper[0];
  9677. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9678. taicpu(hp1).oper[1] := SwapOper;
  9679. end;
  9680. end;
  9681. end;
  9682. case taicpu(hp1).oper[0]^.typ of
  9683. top_reg:
  9684. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9685. top_const:
  9686. { For the AND/TEST case }
  9687. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9688. else
  9689. ;
  9690. end;
  9691. if RegUsed then
  9692. begin
  9693. AsmL.Remove(p);
  9694. AsmL.InsertAfter(p, hp1);
  9695. p := hp1;
  9696. end
  9697. else
  9698. RemoveCurrentP(p, hp1);
  9699. result:=true;
  9700. exit;
  9701. end;
  9702. end;
  9703. end;
  9704. if reg_and_hp1_is_instr and
  9705. (taicpu(p).oper[0]^.typ = top_reg) and
  9706. (
  9707. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  9708. ) and
  9709. (taicpu(hp1).oper[0]^.typ = top_const) and
  9710. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9711. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9712. { Minimum shift value allowed is the bit difference between the sizes }
  9713. (taicpu(hp1).oper[0]^.val >=
  9714. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9715. 8 * (
  9716. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  9717. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9718. )
  9719. ) then
  9720. begin
  9721. { For:
  9722. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  9723. shl/sal ##, %reg1
  9724. Remove the movsx/movzx instruction if the shift overwrites the
  9725. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  9726. }
  9727. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  9728. RemoveCurrentP(p, hp1);
  9729. Result := True;
  9730. Exit;
  9731. end
  9732. else if reg_and_hp1_is_instr and
  9733. (taicpu(p).oper[0]^.typ = top_reg) and
  9734. (
  9735. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  9736. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  9737. ) and
  9738. (taicpu(hp1).oper[0]^.typ = top_const) and
  9739. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9740. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  9741. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  9742. (taicpu(hp1).oper[0]^.val <
  9743. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  9744. 8 * (
  9745. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  9746. )
  9747. ) then
  9748. begin
  9749. { For:
  9750. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  9751. sar ##, %reg1 shr ##, %reg1
  9752. Move the shift to before the movx instruction if the shift value
  9753. is not too large.
  9754. }
  9755. asml.Remove(hp1);
  9756. asml.InsertBefore(hp1, p);
  9757. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9758. case taicpu(p).opsize of
  9759. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  9760. taicpu(hp1).opsize := S_B;
  9761. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  9762. taicpu(hp1).opsize := S_W;
  9763. {$ifdef x86_64}
  9764. S_LQ:
  9765. taicpu(hp1).opsize := S_L;
  9766. {$endif}
  9767. else
  9768. InternalError(2020112401);
  9769. end;
  9770. if (taicpu(hp1).opcode = A_SHR) then
  9771. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  9772. else
  9773. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  9774. Result := True;
  9775. end;
  9776. if reg_and_hp1_is_instr and
  9777. (taicpu(p).oper[0]^.typ = top_reg) and
  9778. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9779. (
  9780. (taicpu(hp1).opcode = taicpu(p).opcode)
  9781. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  9782. {$ifdef x86_64}
  9783. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  9784. {$endif x86_64}
  9785. ) then
  9786. begin
  9787. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  9788. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  9789. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  9790. begin
  9791. {
  9792. For example:
  9793. movzbw %al,%ax
  9794. movzwl %ax,%eax
  9795. Compress into:
  9796. movzbl %al,%eax
  9797. }
  9798. RegUsed := False;
  9799. case taicpu(p).opsize of
  9800. S_BW:
  9801. case taicpu(hp1).opsize of
  9802. S_WL:
  9803. begin
  9804. taicpu(p).opsize := S_BL;
  9805. RegUsed := True;
  9806. end;
  9807. {$ifdef x86_64}
  9808. S_WQ:
  9809. begin
  9810. if taicpu(p).opcode = A_MOVZX then
  9811. begin
  9812. taicpu(p).opsize := S_BL;
  9813. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9814. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9815. end
  9816. else
  9817. taicpu(p).opsize := S_BQ;
  9818. RegUsed := True;
  9819. end;
  9820. {$endif x86_64}
  9821. else
  9822. ;
  9823. end;
  9824. {$ifdef x86_64}
  9825. S_BL:
  9826. case taicpu(hp1).opsize of
  9827. S_LQ:
  9828. begin
  9829. if taicpu(p).opcode = A_MOVZX then
  9830. begin
  9831. taicpu(p).opsize := S_BL;
  9832. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9833. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9834. end
  9835. else
  9836. taicpu(p).opsize := S_BQ;
  9837. RegUsed := True;
  9838. end;
  9839. else
  9840. ;
  9841. end;
  9842. S_WL:
  9843. case taicpu(hp1).opsize of
  9844. S_LQ:
  9845. begin
  9846. if taicpu(p).opcode = A_MOVZX then
  9847. begin
  9848. taicpu(p).opsize := S_WL;
  9849. { 64-bit zero extension is implicit, so change to the 32-bit register }
  9850. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9851. end
  9852. else
  9853. taicpu(p).opsize := S_WQ;
  9854. RegUsed := True;
  9855. end;
  9856. else
  9857. ;
  9858. end;
  9859. {$endif x86_64}
  9860. else
  9861. ;
  9862. end;
  9863. if RegUsed then
  9864. begin
  9865. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  9866. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9867. RemoveInstruction(hp1);
  9868. Result := True;
  9869. Exit;
  9870. end;
  9871. end;
  9872. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  9873. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  9874. GetNextInstruction(hp1, hp2) and
  9875. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  9876. (
  9877. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  9878. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  9879. {$ifdef x86_64}
  9880. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  9881. {$endif x86_64}
  9882. ) and
  9883. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  9884. (
  9885. (
  9886. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9887. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9888. ) or
  9889. (
  9890. { Only allow the operands in reverse order for TEST instructions }
  9891. (taicpu(hp2).opcode = A_TEST) and
  9892. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  9893. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  9894. )
  9895. ) then
  9896. begin
  9897. {
  9898. For example:
  9899. movzbl %al,%eax
  9900. movzbl (ref),%edx
  9901. andl %edx,%eax
  9902. (%edx deallocated)
  9903. Change to:
  9904. andb (ref),%al
  9905. movzbl %al,%eax
  9906. Rules are:
  9907. - First two instructions have the same opcode and opsize
  9908. - First instruction's operands are the same super-register
  9909. - Second instruction operates on a different register
  9910. - Third instruction is AND, OR, XOR or TEST
  9911. - Third instruction's operands are the destination registers of the first two instructions
  9912. - Third instruction writes to the destination register of the first instruction (except with TEST)
  9913. - Second instruction's destination register is deallocated afterwards
  9914. }
  9915. TransferUsedRegs(TmpUsedRegs);
  9916. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9917. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9918. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  9919. begin
  9920. case taicpu(p).opsize of
  9921. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9922. NewSize := S_B;
  9923. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9924. NewSize := S_W;
  9925. {$ifdef x86_64}
  9926. S_LQ:
  9927. NewSize := S_L;
  9928. {$endif x86_64}
  9929. else
  9930. InternalError(2021120301);
  9931. end;
  9932. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  9933. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  9934. taicpu(hp2).opsize := NewSize;
  9935. RemoveInstruction(hp1);
  9936. { With TEST, it's best to keep the MOVX instruction at the top }
  9937. if (taicpu(hp2).opcode <> A_TEST) then
  9938. begin
  9939. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  9940. asml.Remove(p);
  9941. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  9942. asml.InsertAfter(p, hp2);
  9943. p := hp2;
  9944. end
  9945. else
  9946. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  9947. Result := True;
  9948. Exit;
  9949. end;
  9950. end;
  9951. end;
  9952. if taicpu(p).opcode=A_MOVZX then
  9953. begin
  9954. { removes superfluous And's after movzx's }
  9955. if reg_and_hp1_is_instr and
  9956. (taicpu(hp1).opcode = A_AND) and
  9957. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9958. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  9959. {$ifdef x86_64}
  9960. { check for implicit extension to 64 bit }
  9961. or
  9962. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9963. (taicpu(hp1).opsize=S_Q) and
  9964. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  9965. )
  9966. {$endif x86_64}
  9967. )
  9968. then
  9969. begin
  9970. case taicpu(p).opsize Of
  9971. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9972. if (taicpu(hp1).oper[0]^.val = $ff) then
  9973. begin
  9974. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  9975. RemoveInstruction(hp1);
  9976. Result:=true;
  9977. exit;
  9978. end;
  9979. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9980. if (taicpu(hp1).oper[0]^.val = $ffff) then
  9981. begin
  9982. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  9983. RemoveInstruction(hp1);
  9984. Result:=true;
  9985. exit;
  9986. end;
  9987. {$ifdef x86_64}
  9988. S_LQ:
  9989. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  9990. begin
  9991. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  9992. RemoveInstruction(hp1);
  9993. Result:=true;
  9994. exit;
  9995. end;
  9996. {$endif x86_64}
  9997. else
  9998. ;
  9999. end;
  10000. { we cannot get rid of the and, but can we get rid of the movz ?}
  10001. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10002. begin
  10003. case taicpu(p).opsize Of
  10004. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10005. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10006. begin
  10007. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10008. RemoveCurrentP(p,hp1);
  10009. Result:=true;
  10010. exit;
  10011. end;
  10012. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10013. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10014. begin
  10015. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10016. RemoveCurrentP(p,hp1);
  10017. Result:=true;
  10018. exit;
  10019. end;
  10020. {$ifdef x86_64}
  10021. S_LQ:
  10022. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10023. begin
  10024. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10025. RemoveCurrentP(p,hp1);
  10026. Result:=true;
  10027. exit;
  10028. end;
  10029. {$endif x86_64}
  10030. else
  10031. ;
  10032. end;
  10033. end;
  10034. end;
  10035. { changes some movzx constructs to faster synonyms (all examples
  10036. are given with eax/ax, but are also valid for other registers)}
  10037. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10038. begin
  10039. case taicpu(p).opsize of
  10040. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10041. (the machine code is equivalent to movzbl %al,%eax), but the
  10042. code generator still generates that assembler instruction and
  10043. it is silently converted. This should probably be checked.
  10044. [Kit] }
  10045. S_BW:
  10046. begin
  10047. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10048. (
  10049. not IsMOVZXAcceptable
  10050. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10051. or (
  10052. (cs_opt_size in current_settings.optimizerswitches) and
  10053. (taicpu(p).oper[1]^.reg = NR_AX)
  10054. )
  10055. ) then
  10056. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10057. begin
  10058. DebugMsg(SPeepholeOptimization + 'var7',p);
  10059. taicpu(p).opcode := A_AND;
  10060. taicpu(p).changeopsize(S_W);
  10061. taicpu(p).loadConst(0,$ff);
  10062. Result := True;
  10063. end
  10064. else if not IsMOVZXAcceptable and
  10065. GetNextInstruction(p, hp1) and
  10066. (tai(hp1).typ = ait_instruction) and
  10067. (taicpu(hp1).opcode = A_AND) and
  10068. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10069. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10070. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10071. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10072. begin
  10073. DebugMsg(SPeepholeOptimization + 'var8',p);
  10074. taicpu(p).opcode := A_MOV;
  10075. taicpu(p).changeopsize(S_W);
  10076. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10077. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10078. Result := True;
  10079. end;
  10080. end;
  10081. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10082. S_BL:
  10083. begin
  10084. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10085. (
  10086. not IsMOVZXAcceptable
  10087. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10088. or (
  10089. (cs_opt_size in current_settings.optimizerswitches) and
  10090. (taicpu(p).oper[1]^.reg = NR_EAX)
  10091. )
  10092. ) then
  10093. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10094. begin
  10095. DebugMsg(SPeepholeOptimization + 'var9',p);
  10096. taicpu(p).opcode := A_AND;
  10097. taicpu(p).changeopsize(S_L);
  10098. taicpu(p).loadConst(0,$ff);
  10099. Result := True;
  10100. end
  10101. else if not IsMOVZXAcceptable and
  10102. GetNextInstruction(p, hp1) and
  10103. (tai(hp1).typ = ait_instruction) and
  10104. (taicpu(hp1).opcode = A_AND) and
  10105. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10106. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10107. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10108. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10109. begin
  10110. DebugMsg(SPeepholeOptimization + 'var10',p);
  10111. taicpu(p).opcode := A_MOV;
  10112. taicpu(p).changeopsize(S_L);
  10113. { do not use R_SUBWHOLE
  10114. as movl %rdx,%eax
  10115. is invalid in assembler PM }
  10116. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10117. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10118. Result := True;
  10119. end;
  10120. end;
  10121. {$endif i8086}
  10122. S_WL:
  10123. if not IsMOVZXAcceptable then
  10124. begin
  10125. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10126. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10127. begin
  10128. DebugMsg(SPeepholeOptimization + 'var11',p);
  10129. taicpu(p).opcode := A_AND;
  10130. taicpu(p).changeopsize(S_L);
  10131. taicpu(p).loadConst(0,$ffff);
  10132. Result := True;
  10133. end
  10134. else if GetNextInstruction(p, hp1) and
  10135. (tai(hp1).typ = ait_instruction) and
  10136. (taicpu(hp1).opcode = A_AND) and
  10137. (taicpu(hp1).oper[0]^.typ = top_const) and
  10138. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10139. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10140. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10141. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10142. begin
  10143. DebugMsg(SPeepholeOptimization + 'var12',p);
  10144. taicpu(p).opcode := A_MOV;
  10145. taicpu(p).changeopsize(S_L);
  10146. { do not use R_SUBWHOLE
  10147. as movl %rdx,%eax
  10148. is invalid in assembler PM }
  10149. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10150. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10151. Result := True;
  10152. end;
  10153. end;
  10154. else
  10155. InternalError(2017050705);
  10156. end;
  10157. end
  10158. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10159. begin
  10160. if GetNextInstruction(p, hp1) and
  10161. (tai(hp1).typ = ait_instruction) and
  10162. (taicpu(hp1).opcode = A_AND) and
  10163. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10164. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10165. begin
  10166. //taicpu(p).opcode := A_MOV;
  10167. case taicpu(p).opsize Of
  10168. S_BL:
  10169. begin
  10170. DebugMsg(SPeepholeOptimization + 'var13',p);
  10171. taicpu(hp1).changeopsize(S_L);
  10172. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10173. end;
  10174. S_WL:
  10175. begin
  10176. DebugMsg(SPeepholeOptimization + 'var14',p);
  10177. taicpu(hp1).changeopsize(S_L);
  10178. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10179. end;
  10180. S_BW:
  10181. begin
  10182. DebugMsg(SPeepholeOptimization + 'var15',p);
  10183. taicpu(hp1).changeopsize(S_W);
  10184. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10185. end;
  10186. else
  10187. Internalerror(2017050704)
  10188. end;
  10189. Result := True;
  10190. end;
  10191. end;
  10192. end;
  10193. end;
  10194. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10195. var
  10196. hp1, hp2 : tai;
  10197. MaskLength : Cardinal;
  10198. MaskedBits : TCgInt;
  10199. ActiveReg : TRegister;
  10200. begin
  10201. Result:=false;
  10202. { There are no optimisations for reference targets }
  10203. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10204. Exit;
  10205. while GetNextInstruction(p, hp1) and
  10206. (hp1.typ = ait_instruction) do
  10207. begin
  10208. if (taicpu(p).oper[0]^.typ = top_const) then
  10209. begin
  10210. case taicpu(hp1).opcode of
  10211. A_AND:
  10212. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10213. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10214. { the second register must contain the first one, so compare their subreg types }
  10215. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10216. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10217. { change
  10218. and const1, reg
  10219. and const2, reg
  10220. to
  10221. and (const1 and const2), reg
  10222. }
  10223. begin
  10224. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10225. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10226. RemoveCurrentP(p, hp1);
  10227. Result:=true;
  10228. exit;
  10229. end;
  10230. A_CMP:
  10231. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10232. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10233. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10234. { Just check that the condition on the next instruction is compatible }
  10235. GetNextInstruction(hp1, hp2) and
  10236. (hp2.typ = ait_instruction) and
  10237. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10238. then
  10239. { change
  10240. and 2^n, reg
  10241. cmp 2^n, reg
  10242. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10243. to
  10244. and 2^n, reg
  10245. test reg, reg
  10246. j(~c) / set(~c) / cmov(~c)
  10247. }
  10248. begin
  10249. { Keep TEST instruction in, rather than remove it, because
  10250. it may trigger other optimisations such as MovAndTest2Test }
  10251. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10252. taicpu(hp1).opcode := A_TEST;
  10253. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10254. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10255. Result := True;
  10256. Exit;
  10257. end;
  10258. A_MOVZX:
  10259. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10260. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10261. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10262. (
  10263. (
  10264. (taicpu(p).opsize=S_W) and
  10265. (taicpu(hp1).opsize=S_BW)
  10266. ) or
  10267. (
  10268. (taicpu(p).opsize=S_L) and
  10269. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10270. )
  10271. {$ifdef x86_64}
  10272. or
  10273. (
  10274. (taicpu(p).opsize=S_Q) and
  10275. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10276. )
  10277. {$endif x86_64}
  10278. ) then
  10279. begin
  10280. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10281. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10282. ) or
  10283. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10284. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10285. then
  10286. begin
  10287. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10288. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10289. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10290. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10291. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10292. }
  10293. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10294. RemoveInstruction(hp1);
  10295. { See if there are other optimisations possible }
  10296. Continue;
  10297. end;
  10298. end;
  10299. A_SHL:
  10300. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10301. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10302. begin
  10303. {$ifopt R+}
  10304. {$define RANGE_WAS_ON}
  10305. {$R-}
  10306. {$endif}
  10307. { get length of potential and mask }
  10308. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10309. { really a mask? }
  10310. {$ifdef RANGE_WAS_ON}
  10311. {$R+}
  10312. {$endif}
  10313. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10314. { unmasked part shifted out? }
  10315. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10316. begin
  10317. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10318. RemoveCurrentP(p, hp1);
  10319. Result:=true;
  10320. exit;
  10321. end;
  10322. end;
  10323. A_SHR:
  10324. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10325. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10326. (taicpu(hp1).oper[0]^.val <= 63) then
  10327. begin
  10328. { Does SHR combined with the AND cover all the bits?
  10329. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10330. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10331. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10332. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10333. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10334. begin
  10335. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10336. RemoveCurrentP(p, hp1);
  10337. Result := True;
  10338. Exit;
  10339. end;
  10340. end;
  10341. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10342. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10343. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10344. begin
  10345. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10346. (
  10347. (
  10348. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10349. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10350. ) or (
  10351. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10352. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10353. {$ifdef x86_64}
  10354. ) or (
  10355. (taicpu(hp1).opsize = S_LQ) and
  10356. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10357. {$endif x86_64}
  10358. )
  10359. ) then
  10360. begin
  10361. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10362. begin
  10363. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10364. RemoveInstruction(hp1);
  10365. { See if there are other optimisations possible }
  10366. Continue;
  10367. end;
  10368. { The super-registers are the same though.
  10369. Note that this change by itself doesn't improve
  10370. code speed, but it opens up other optimisations. }
  10371. {$ifdef x86_64}
  10372. { Convert 64-bit register to 32-bit }
  10373. case taicpu(hp1).opsize of
  10374. S_BQ:
  10375. begin
  10376. taicpu(hp1).opsize := S_BL;
  10377. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10378. end;
  10379. S_WQ:
  10380. begin
  10381. taicpu(hp1).opsize := S_WL;
  10382. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10383. end
  10384. else
  10385. ;
  10386. end;
  10387. {$endif x86_64}
  10388. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10389. taicpu(hp1).opcode := A_MOVZX;
  10390. { See if there are other optimisations possible }
  10391. Continue;
  10392. end;
  10393. end;
  10394. else
  10395. ;
  10396. end;
  10397. end
  10398. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10399. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10400. begin
  10401. {$ifdef x86_64}
  10402. if (taicpu(p).opsize = S_Q) then
  10403. begin
  10404. { Never necessary }
  10405. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10406. RemoveCurrentP(p, hp1);
  10407. Result := True;
  10408. Exit;
  10409. end;
  10410. {$endif x86_64}
  10411. { Forward check to determine necessity of and %reg,%reg }
  10412. TransferUsedRegs(TmpUsedRegs);
  10413. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10414. { Saves on a bunch of dereferences }
  10415. ActiveReg := taicpu(p).oper[1]^.reg;
  10416. case taicpu(hp1).opcode of
  10417. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10418. if (
  10419. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10420. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10421. ) and
  10422. (
  10423. (taicpu(hp1).opcode <> A_MOV) or
  10424. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10425. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10426. ) and
  10427. not (
  10428. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10429. (taicpu(hp1).opcode = A_MOV) and
  10430. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10431. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10432. ) and
  10433. (
  10434. (
  10435. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10436. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10437. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10438. ) or
  10439. (
  10440. {$ifdef x86_64}
  10441. (
  10442. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10443. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10444. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10445. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10446. ) and
  10447. {$endif x86_64}
  10448. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10449. )
  10450. ) then
  10451. begin
  10452. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10453. RemoveCurrentP(p, hp1);
  10454. Result := True;
  10455. Exit;
  10456. end;
  10457. A_ADD,
  10458. A_AND,
  10459. A_BSF,
  10460. A_BSR,
  10461. A_BTC,
  10462. A_BTR,
  10463. A_BTS,
  10464. A_OR,
  10465. A_SUB,
  10466. A_XOR:
  10467. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10468. if (
  10469. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10470. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10471. ) and
  10472. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10473. begin
  10474. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10475. RemoveCurrentP(p, hp1);
  10476. Result := True;
  10477. Exit;
  10478. end;
  10479. A_CMP,
  10480. A_TEST:
  10481. if (
  10482. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10483. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10484. ) and
  10485. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10486. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10487. begin
  10488. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10489. RemoveCurrentP(p, hp1);
  10490. Result := True;
  10491. Exit;
  10492. end;
  10493. A_BSWAP,
  10494. A_NEG,
  10495. A_NOT:
  10496. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10497. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10498. begin
  10499. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10500. RemoveCurrentP(p, hp1);
  10501. Result := True;
  10502. Exit;
  10503. end;
  10504. else
  10505. ;
  10506. end;
  10507. end;
  10508. if (taicpu(hp1).is_jmp) and
  10509. (taicpu(hp1).opcode<>A_JMP) and
  10510. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10511. begin
  10512. { change
  10513. and x, reg
  10514. jxx
  10515. to
  10516. test x, reg
  10517. jxx
  10518. if reg is deallocated before the
  10519. jump, but only if it's a conditional jump (PFV)
  10520. }
  10521. taicpu(p).opcode := A_TEST;
  10522. Exit;
  10523. end;
  10524. Break;
  10525. end;
  10526. { Lone AND tests }
  10527. if (taicpu(p).oper[0]^.typ = top_const) then
  10528. begin
  10529. {
  10530. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10531. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10532. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10533. }
  10534. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10535. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10536. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10537. begin
  10538. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10539. if taicpu(p).opsize = S_L then
  10540. begin
  10541. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10542. Result := True;
  10543. end;
  10544. end;
  10545. end;
  10546. { Backward check to determine necessity of and %reg,%reg }
  10547. if (taicpu(p).oper[0]^.typ = top_reg) and
  10548. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10549. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10550. GetLastInstruction(p, hp2) and
  10551. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10552. { Check size of adjacent instruction to determine if the AND is
  10553. effectively a null operation }
  10554. (
  10555. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10556. { Note: Don't include S_Q }
  10557. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10558. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10559. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10560. ) then
  10561. begin
  10562. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10563. { If GetNextInstruction returned False, hp1 will be nil }
  10564. RemoveCurrentP(p, hp1);
  10565. Result := True;
  10566. Exit;
  10567. end;
  10568. end;
  10569. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10570. var
  10571. hp1: tai; NewRef: TReference;
  10572. { This entire nested function is used in an if-statement below, but we
  10573. want to avoid all the used reg transfers and GetNextInstruction calls
  10574. until we really have to check }
  10575. function MemRegisterNotUsedLater: Boolean; inline;
  10576. var
  10577. hp2: tai;
  10578. begin
  10579. TransferUsedRegs(TmpUsedRegs);
  10580. hp2 := p;
  10581. repeat
  10582. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10583. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10584. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10585. end;
  10586. begin
  10587. Result := False;
  10588. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10589. Exit;
  10590. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10591. begin
  10592. { Change:
  10593. add %reg2,%reg1
  10594. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10595. To:
  10596. mov/s/z #(%reg1,%reg2),%reg1
  10597. }
  10598. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10599. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10600. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10601. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10602. (
  10603. (
  10604. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10605. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10606. { r/esp cannot be an index }
  10607. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10608. ) or (
  10609. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10610. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10611. )
  10612. ) and (
  10613. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10614. (
  10615. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10616. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10617. MemRegisterNotUsedLater
  10618. )
  10619. ) then
  10620. begin
  10621. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10622. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10623. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10624. RemoveCurrentp(p, hp1);
  10625. Result := True;
  10626. Exit;
  10627. end;
  10628. { Change:
  10629. addl/q $x,%reg1
  10630. movl/q %reg1,%reg2
  10631. To:
  10632. leal/q $x(%reg1),%reg2
  10633. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10634. Breaks the dependency chain.
  10635. }
  10636. if MatchOpType(taicpu(p),top_const,top_reg) and
  10637. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10638. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10639. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10640. (
  10641. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10642. not (cs_opt_size in current_settings.optimizerswitches) or
  10643. (
  10644. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10645. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10646. )
  10647. ) then
  10648. begin
  10649. { Change the MOV instruction to a LEA instruction, and update the
  10650. first operand }
  10651. reference_reset(NewRef, 1, []);
  10652. NewRef.base := taicpu(p).oper[1]^.reg;
  10653. NewRef.scalefactor := 1;
  10654. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10655. taicpu(hp1).opcode := A_LEA;
  10656. taicpu(hp1).loadref(0, NewRef);
  10657. TransferUsedRegs(TmpUsedRegs);
  10658. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10659. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10660. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10661. begin
  10662. { Move what is now the LEA instruction to before the SUB instruction }
  10663. Asml.Remove(hp1);
  10664. Asml.InsertBefore(hp1, p);
  10665. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10666. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10667. p := hp1;
  10668. end
  10669. else
  10670. begin
  10671. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10672. RemoveCurrentP(p, hp1);
  10673. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10674. end;
  10675. Result := True;
  10676. end;
  10677. end;
  10678. end;
  10679. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10680. var
  10681. SubReg: TSubRegister;
  10682. begin
  10683. Result:=false;
  10684. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10685. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10686. with taicpu(p).oper[0]^.ref^ do
  10687. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10688. begin
  10689. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  10690. begin
  10691. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  10692. taicpu(p).opcode := A_ADD;
  10693. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  10694. Result := True;
  10695. end
  10696. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  10697. begin
  10698. if (base <> NR_NO) then
  10699. begin
  10700. if (scalefactor <= 1) then
  10701. begin
  10702. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  10703. taicpu(p).opcode := A_ADD;
  10704. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  10705. Result := True;
  10706. end;
  10707. end
  10708. else
  10709. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  10710. if (scalefactor in [2, 4, 8]) then
  10711. begin
  10712. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  10713. taicpu(p).loadconst(0, BsrByte(scalefactor));
  10714. taicpu(p).opcode := A_SHL;
  10715. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  10716. Result := True;
  10717. end;
  10718. end;
  10719. end;
  10720. end;
  10721. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  10722. var
  10723. hp1: tai; NewRef: TReference;
  10724. begin
  10725. { Change:
  10726. subl/q $x,%reg1
  10727. movl/q %reg1,%reg2
  10728. To:
  10729. leal/q $-x(%reg1),%reg2
  10730. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10731. Breaks the dependency chain and potentially permits the removal of
  10732. a CMP instruction if one follows.
  10733. }
  10734. Result := False;
  10735. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  10736. MatchOpType(taicpu(p),top_const,top_reg) and
  10737. GetNextInstruction(p, hp1) and
  10738. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10739. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10740. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10741. (
  10742. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  10743. not (cs_opt_size in current_settings.optimizerswitches) or
  10744. (
  10745. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10746. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10747. )
  10748. ) then
  10749. begin
  10750. { Change the MOV instruction to a LEA instruction, and update the
  10751. first operand }
  10752. reference_reset(NewRef, 1, []);
  10753. NewRef.base := taicpu(p).oper[1]^.reg;
  10754. NewRef.scalefactor := 1;
  10755. NewRef.offset := -taicpu(p).oper[0]^.val;
  10756. taicpu(hp1).opcode := A_LEA;
  10757. taicpu(hp1).loadref(0, NewRef);
  10758. TransferUsedRegs(TmpUsedRegs);
  10759. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10760. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10761. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10762. begin
  10763. { Move what is now the LEA instruction to before the SUB instruction }
  10764. Asml.Remove(hp1);
  10765. Asml.InsertBefore(hp1, p);
  10766. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10767. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  10768. p := hp1;
  10769. end
  10770. else
  10771. begin
  10772. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10773. RemoveCurrentP(p, hp1);
  10774. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  10775. end;
  10776. Result := True;
  10777. end;
  10778. end;
  10779. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  10780. begin
  10781. { we can skip all instructions not messing with the stack pointer }
  10782. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  10783. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  10784. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  10785. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  10786. ({(taicpu(hp1).ops=0) or }
  10787. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  10788. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  10789. ) and }
  10790. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  10791. )
  10792. ) do
  10793. GetNextInstruction(hp1,hp1);
  10794. Result:=assigned(hp1);
  10795. end;
  10796. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  10797. var
  10798. hp1, hp2, hp3, hp4, hp5: tai;
  10799. begin
  10800. Result:=false;
  10801. hp5:=nil;
  10802. { replace
  10803. leal(q) x(<stackpointer>),<stackpointer>
  10804. call procname
  10805. leal(q) -x(<stackpointer>),<stackpointer>
  10806. ret
  10807. by
  10808. jmp procname
  10809. but do it only on level 4 because it destroys stack back traces
  10810. }
  10811. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10812. MatchOpType(taicpu(p),top_ref,top_reg) and
  10813. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10814. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  10815. { the -8 or -24 are not required, but bail out early if possible,
  10816. higher values are unlikely }
  10817. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  10818. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  10819. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  10820. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  10821. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  10822. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10823. GetNextInstruction(p, hp1) and
  10824. { Take a copy of hp1 }
  10825. SetAndTest(hp1, hp4) and
  10826. { trick to skip label }
  10827. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10828. SkipSimpleInstructions(hp1) and
  10829. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10830. GetNextInstruction(hp1, hp2) and
  10831. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  10832. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  10833. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  10834. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  10835. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  10836. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  10837. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  10838. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  10839. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  10840. GetNextInstruction(hp2, hp3) and
  10841. { trick to skip label }
  10842. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10843. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10844. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10845. SetAndTest(hp3,hp5) and
  10846. GetNextInstruction(hp3,hp3) and
  10847. MatchInstruction(hp3,A_RET,[S_NO])
  10848. )
  10849. ) and
  10850. (taicpu(hp3).ops=0) then
  10851. begin
  10852. taicpu(hp1).opcode := A_JMP;
  10853. taicpu(hp1).is_jmp := true;
  10854. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  10855. RemoveCurrentP(p, hp4);
  10856. RemoveInstruction(hp2);
  10857. RemoveInstruction(hp3);
  10858. if Assigned(hp5) then
  10859. begin
  10860. AsmL.Remove(hp5);
  10861. ASmL.InsertBefore(hp5,hp1)
  10862. end;
  10863. Result:=true;
  10864. end;
  10865. end;
  10866. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  10867. {$ifdef x86_64}
  10868. var
  10869. hp1, hp2, hp3, hp4, hp5: tai;
  10870. {$endif x86_64}
  10871. begin
  10872. Result:=false;
  10873. {$ifdef x86_64}
  10874. hp5:=nil;
  10875. { replace
  10876. push %rax
  10877. call procname
  10878. pop %rcx
  10879. ret
  10880. by
  10881. jmp procname
  10882. but do it only on level 4 because it destroys stack back traces
  10883. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  10884. for all supported calling conventions
  10885. }
  10886. if (cs_opt_level4 in current_settings.optimizerswitches) and
  10887. MatchOpType(taicpu(p),top_reg) and
  10888. (taicpu(p).oper[0]^.reg=NR_RAX) and
  10889. GetNextInstruction(p, hp1) and
  10890. { Take a copy of hp1 }
  10891. SetAndTest(hp1, hp4) and
  10892. { trick to skip label }
  10893. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  10894. SkipSimpleInstructions(hp1) and
  10895. MatchInstruction(hp1,A_CALL,[S_NO]) and
  10896. GetNextInstruction(hp1, hp2) and
  10897. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  10898. MatchOpType(taicpu(hp2),top_reg) and
  10899. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  10900. GetNextInstruction(hp2, hp3) and
  10901. { trick to skip label }
  10902. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  10903. (MatchInstruction(hp3,A_RET,[S_NO]) or
  10904. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  10905. SetAndTest(hp3,hp5) and
  10906. GetNextInstruction(hp3,hp3) and
  10907. MatchInstruction(hp3,A_RET,[S_NO])
  10908. )
  10909. ) and
  10910. (taicpu(hp3).ops=0) then
  10911. begin
  10912. taicpu(hp1).opcode := A_JMP;
  10913. taicpu(hp1).is_jmp := true;
  10914. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  10915. RemoveCurrentP(p, hp4);
  10916. RemoveInstruction(hp2);
  10917. RemoveInstruction(hp3);
  10918. if Assigned(hp5) then
  10919. begin
  10920. AsmL.Remove(hp5);
  10921. ASmL.InsertBefore(hp5,hp1)
  10922. end;
  10923. Result:=true;
  10924. end;
  10925. {$endif x86_64}
  10926. end;
  10927. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  10928. var
  10929. Value, RegName: string;
  10930. begin
  10931. Result:=false;
  10932. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  10933. begin
  10934. case taicpu(p).oper[0]^.val of
  10935. 0:
  10936. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  10937. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10938. begin
  10939. { change "mov $0,%reg" into "xor %reg,%reg" }
  10940. taicpu(p).opcode := A_XOR;
  10941. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  10942. Result := True;
  10943. {$ifdef x86_64}
  10944. end
  10945. else if (taicpu(p).opsize = S_Q) then
  10946. begin
  10947. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10948. { The actual optimization }
  10949. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10950. taicpu(p).changeopsize(S_L);
  10951. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10952. Result := True;
  10953. end;
  10954. $1..$FFFFFFFF:
  10955. begin
  10956. { Code size reduction by J. Gareth "Kit" Moreton }
  10957. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  10958. case taicpu(p).opsize of
  10959. S_Q:
  10960. begin
  10961. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  10962. Value := debug_tostr(taicpu(p).oper[0]^.val);
  10963. { The actual optimization }
  10964. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  10965. taicpu(p).changeopsize(S_L);
  10966. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  10967. Result := True;
  10968. end;
  10969. else
  10970. { Do nothing };
  10971. end;
  10972. {$endif x86_64}
  10973. end;
  10974. -1:
  10975. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  10976. if (cs_opt_size in current_settings.optimizerswitches) and
  10977. (taicpu(p).opsize <> S_B) and
  10978. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10979. begin
  10980. { change "mov $-1,%reg" into "or $-1,%reg" }
  10981. { NOTES:
  10982. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  10983. - This operation creates a false dependency on the register, so only do it when optimising for size
  10984. - 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
  10985. }
  10986. taicpu(p).opcode := A_OR;
  10987. Result := True;
  10988. end;
  10989. else
  10990. { Do nothing };
  10991. end;
  10992. end;
  10993. end;
  10994. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  10995. var
  10996. hp1: tai;
  10997. begin
  10998. { Detect:
  10999. andw x, %ax (0 <= x < $8000)
  11000. ...
  11001. movzwl %ax,%eax
  11002. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11003. }
  11004. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11005. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11006. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11007. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11008. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11009. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11010. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11011. begin
  11012. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11013. taicpu(hp1).opcode := A_CWDE;
  11014. taicpu(hp1).clearop(0);
  11015. taicpu(hp1).clearop(1);
  11016. taicpu(hp1).ops := 0;
  11017. { A change was made, but not with p, so move forward 1 }
  11018. p := tai(p.Next);
  11019. Result := True;
  11020. end;
  11021. end;
  11022. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11023. begin
  11024. Result := False;
  11025. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11026. Exit;
  11027. { Convert:
  11028. movswl %ax,%eax -> cwtl
  11029. movslq %eax,%rax -> cdqe
  11030. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11031. refer to the same opcode and depends only on the assembler's
  11032. current operand-size attribute. [Kit]
  11033. }
  11034. with taicpu(p) do
  11035. case opsize of
  11036. S_WL:
  11037. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11038. begin
  11039. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11040. opcode := A_CWDE;
  11041. clearop(0);
  11042. clearop(1);
  11043. ops := 0;
  11044. Result := True;
  11045. end;
  11046. {$ifdef x86_64}
  11047. S_LQ:
  11048. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11049. begin
  11050. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11051. opcode := A_CDQE;
  11052. clearop(0);
  11053. clearop(1);
  11054. ops := 0;
  11055. Result := True;
  11056. end;
  11057. {$endif x86_64}
  11058. else
  11059. ;
  11060. end;
  11061. end;
  11062. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11063. var
  11064. hp1: tai;
  11065. begin
  11066. { Detect:
  11067. shr x, %ax (x > 0)
  11068. ...
  11069. movzwl %ax,%eax
  11070. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11071. }
  11072. Result := False;
  11073. if MatchOpType(taicpu(p), top_const, top_reg) and
  11074. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11075. (taicpu(p).oper[0]^.val > 0) and
  11076. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11077. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11078. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11079. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11080. begin
  11081. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11082. taicpu(hp1).opcode := A_CWDE;
  11083. taicpu(hp1).clearop(0);
  11084. taicpu(hp1).clearop(1);
  11085. taicpu(hp1).ops := 0;
  11086. { A change was made, but not with p, so move forward 1 }
  11087. p := tai(p.Next);
  11088. Result := True;
  11089. end;
  11090. end;
  11091. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11092. var
  11093. hp1, hp2: tai;
  11094. Opposite, SecondOpposite: TAsmOp;
  11095. NewCond: TAsmCond;
  11096. begin
  11097. Result := False;
  11098. { Change:
  11099. add/sub 128,(dest)
  11100. To:
  11101. sub/add -128,(dest)
  11102. This generaally takes fewer bytes to encode because -128 can be stored
  11103. in a signed byte, whereas +128 cannot.
  11104. }
  11105. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11106. begin
  11107. if taicpu(p).opcode = A_ADD then
  11108. Opposite := A_SUB
  11109. else
  11110. Opposite := A_ADD;
  11111. { Be careful if the flags are in use, because the CF flag inverts
  11112. when changing from ADD to SUB and vice versa }
  11113. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11114. GetNextInstruction(p, hp1) then
  11115. begin
  11116. TransferUsedRegs(TmpUsedRegs);
  11117. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11118. hp2 := hp1;
  11119. { Scan ahead to check if everything's safe }
  11120. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11121. begin
  11122. if (hp1.typ <> ait_instruction) then
  11123. { Probably unsafe since the flags are still in use }
  11124. Exit;
  11125. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11126. { Stop searching at an unconditional jump }
  11127. Break;
  11128. if not
  11129. (
  11130. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11131. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11132. ) and
  11133. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11134. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11135. Exit;
  11136. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11137. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11138. { Move to the next instruction }
  11139. GetNextInstruction(hp1, hp1);
  11140. end;
  11141. while Assigned(hp2) and (hp2 <> hp1) do
  11142. begin
  11143. NewCond := C_None;
  11144. case taicpu(hp2).condition of
  11145. C_A, C_NBE:
  11146. NewCond := C_BE;
  11147. C_B, C_C, C_NAE:
  11148. NewCond := C_AE;
  11149. C_AE, C_NB, C_NC:
  11150. NewCond := C_B;
  11151. C_BE, C_NA:
  11152. NewCond := C_A;
  11153. else
  11154. { No change needed };
  11155. end;
  11156. if NewCond <> C_None then
  11157. begin
  11158. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11159. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11160. taicpu(hp2).condition := NewCond;
  11161. end
  11162. else
  11163. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11164. begin
  11165. { Because of the flipping of the carry bit, to ensure
  11166. the operation remains equivalent, ADC becomes SBB
  11167. and vice versa, and the constant is not-inverted.
  11168. If multiple ADCs or SBBs appear in a row, each one
  11169. changed causes the carry bit to invert, so they all
  11170. need to be flipped }
  11171. if taicpu(hp2).opcode = A_ADC then
  11172. SecondOpposite := A_SBB
  11173. else
  11174. SecondOpposite := A_ADC;
  11175. if taicpu(hp2).oper[0]^.typ <> top_const then
  11176. { Should have broken out of this optimisation already }
  11177. InternalError(2021112901);
  11178. 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]^) + ' -> ' +
  11179. 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);
  11180. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11181. taicpu(hp2).opcode := SecondOpposite;
  11182. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11183. end;
  11184. { Move to the next instruction }
  11185. GetNextInstruction(hp2, hp2);
  11186. end;
  11187. if (hp2 <> hp1) then
  11188. InternalError(2021111501);
  11189. end;
  11190. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11191. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11192. taicpu(p).opcode := Opposite;
  11193. taicpu(p).oper[0]^.val := -128;
  11194. { No further optimisations can be made on this instruction, so move
  11195. onto the next one to save time }
  11196. p := tai(p.Next);
  11197. UpdateUsedRegs(p);
  11198. Result := True;
  11199. Exit;
  11200. end;
  11201. { Detect:
  11202. add/sub %reg2,(dest)
  11203. add/sub x, (dest)
  11204. (dest can be a register or a reference)
  11205. Swap the instructions to minimise a pipeline stall. This reverses the
  11206. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11207. optimisations could be made.
  11208. }
  11209. if (taicpu(p).oper[0]^.typ = top_reg) and
  11210. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11211. (
  11212. (
  11213. (taicpu(p).oper[1]^.typ = top_reg) and
  11214. { We can try searching further ahead if we're writing to a register }
  11215. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11216. ) or
  11217. (
  11218. (taicpu(p).oper[1]^.typ = top_ref) and
  11219. GetNextInstruction(p, hp1)
  11220. )
  11221. ) and
  11222. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11223. (taicpu(hp1).oper[0]^.typ = top_const) and
  11224. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11225. begin
  11226. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11227. TransferUsedRegs(TmpUsedRegs);
  11228. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11229. hp2 := p;
  11230. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11231. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11232. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11233. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11234. begin
  11235. asml.remove(hp1);
  11236. asml.InsertBefore(hp1, p);
  11237. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11238. Result := True;
  11239. end;
  11240. end;
  11241. end;
  11242. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11243. begin
  11244. Result:=false;
  11245. { change "cmp $0, %reg" to "test %reg, %reg" }
  11246. if MatchOpType(taicpu(p),top_const,top_reg) and
  11247. (taicpu(p).oper[0]^.val = 0) then
  11248. begin
  11249. taicpu(p).opcode := A_TEST;
  11250. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11251. Result:=true;
  11252. end;
  11253. end;
  11254. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11255. var
  11256. IsTestConstX : Boolean;
  11257. hp1,hp2 : tai;
  11258. begin
  11259. Result:=false;
  11260. { removes the line marked with (x) from the sequence
  11261. and/or/xor/add/sub/... $x, %y
  11262. test/or %y, %y | test $-1, %y (x)
  11263. j(n)z _Label
  11264. as the first instruction already adjusts the ZF
  11265. %y operand may also be a reference }
  11266. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11267. MatchOperand(taicpu(p).oper[0]^,-1);
  11268. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11269. GetLastInstruction(p, hp1) and
  11270. (tai(hp1).typ = ait_instruction) and
  11271. GetNextInstruction(p,hp2) and
  11272. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11273. case taicpu(hp1).opcode Of
  11274. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11275. { These two instructions set the zero flag if the result is zero }
  11276. A_POPCNT, A_LZCNT:
  11277. begin
  11278. if (
  11279. { With POPCNT, an input of zero will set the zero flag
  11280. because the population count of zero is zero }
  11281. (taicpu(hp1).opcode = A_POPCNT) and
  11282. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11283. (
  11284. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11285. { Faster than going through the second half of the 'or'
  11286. condition below }
  11287. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11288. )
  11289. ) or (
  11290. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11291. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11292. { and in case of carry for A(E)/B(E)/C/NC }
  11293. (
  11294. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11295. (
  11296. (taicpu(hp1).opcode <> A_ADD) and
  11297. (taicpu(hp1).opcode <> A_SUB) and
  11298. (taicpu(hp1).opcode <> A_LZCNT)
  11299. )
  11300. )
  11301. ) then
  11302. begin
  11303. RemoveCurrentP(p, hp2);
  11304. Result:=true;
  11305. Exit;
  11306. end;
  11307. end;
  11308. A_SHL, A_SAL, A_SHR, A_SAR:
  11309. begin
  11310. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11311. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11312. { therefore, it's only safe to do this optimization for }
  11313. { shifts by a (nonzero) constant }
  11314. (taicpu(hp1).oper[0]^.typ = top_const) and
  11315. (taicpu(hp1).oper[0]^.val <> 0) and
  11316. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11317. { and in case of carry for A(E)/B(E)/C/NC }
  11318. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11319. begin
  11320. RemoveCurrentP(p, hp2);
  11321. Result:=true;
  11322. Exit;
  11323. end;
  11324. end;
  11325. A_DEC, A_INC, A_NEG:
  11326. begin
  11327. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11328. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11329. { and in case of carry for A(E)/B(E)/C/NC }
  11330. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11331. begin
  11332. RemoveCurrentP(p, hp2);
  11333. Result:=true;
  11334. Exit;
  11335. end;
  11336. end
  11337. else
  11338. ;
  11339. end; { case }
  11340. { change "test $-1,%reg" into "test %reg,%reg" }
  11341. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11342. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11343. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11344. if MatchInstruction(p, A_OR, []) and
  11345. { Can only match if they're both registers }
  11346. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11347. begin
  11348. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11349. taicpu(p).opcode := A_TEST;
  11350. { No need to set Result to True, as we've done all the optimisations we can }
  11351. end;
  11352. end;
  11353. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11354. var
  11355. hp1,hp3 : tai;
  11356. {$ifndef x86_64}
  11357. hp2 : taicpu;
  11358. {$endif x86_64}
  11359. begin
  11360. Result:=false;
  11361. hp3:=nil;
  11362. {$ifndef x86_64}
  11363. { don't do this on modern CPUs, this really hurts them due to
  11364. broken call/ret pairing }
  11365. if (current_settings.optimizecputype < cpu_Pentium2) and
  11366. not(cs_create_pic in current_settings.moduleswitches) and
  11367. GetNextInstruction(p, hp1) and
  11368. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11369. MatchOpType(taicpu(hp1),top_ref) and
  11370. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11371. begin
  11372. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11373. InsertLLItem(p.previous, p, hp2);
  11374. taicpu(p).opcode := A_JMP;
  11375. taicpu(p).is_jmp := true;
  11376. RemoveInstruction(hp1);
  11377. Result:=true;
  11378. end
  11379. else
  11380. {$endif x86_64}
  11381. { replace
  11382. call procname
  11383. ret
  11384. by
  11385. jmp procname
  11386. but do it only on level 4 because it destroys stack back traces
  11387. else if the subroutine is marked as no return, remove the ret
  11388. }
  11389. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11390. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11391. GetNextInstruction(p, hp1) and
  11392. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11393. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11394. SetAndTest(hp1,hp3) and
  11395. GetNextInstruction(hp1,hp1) and
  11396. MatchInstruction(hp1,A_RET,[S_NO])
  11397. )
  11398. ) and
  11399. (taicpu(hp1).ops=0) then
  11400. begin
  11401. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11402. { we might destroy stack alignment here if we do not do a call }
  11403. (target_info.stackalign<=sizeof(SizeUInt)) then
  11404. begin
  11405. taicpu(p).opcode := A_JMP;
  11406. taicpu(p).is_jmp := true;
  11407. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11408. end
  11409. else
  11410. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11411. RemoveInstruction(hp1);
  11412. if Assigned(hp3) then
  11413. begin
  11414. AsmL.Remove(hp3);
  11415. AsmL.InsertBefore(hp3,p)
  11416. end;
  11417. Result:=true;
  11418. end;
  11419. end;
  11420. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11421. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11422. begin
  11423. case OpSize of
  11424. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11425. Result := (Val <= $FF) and (Val >= -128);
  11426. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11427. Result := (Val <= $FFFF) and (Val >= -32768);
  11428. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11429. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11430. else
  11431. Result := True;
  11432. end;
  11433. end;
  11434. var
  11435. hp1, hp2 : tai;
  11436. SizeChange: Boolean;
  11437. PreMessage: string;
  11438. begin
  11439. Result := False;
  11440. if (taicpu(p).oper[0]^.typ = top_reg) and
  11441. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11442. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11443. begin
  11444. { Change (using movzbl %al,%eax as an example):
  11445. movzbl %al, %eax movzbl %al, %eax
  11446. cmpl x, %eax testl %eax,%eax
  11447. To:
  11448. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11449. movzbl %al, %eax movzbl %al, %eax
  11450. Smaller instruction and minimises pipeline stall as the CPU
  11451. doesn't have to wait for the register to get zero-extended. [Kit]
  11452. Also allow if the smaller of the two registers is being checked,
  11453. as this still removes the false dependency.
  11454. }
  11455. if
  11456. (
  11457. (
  11458. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11459. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11460. ) or (
  11461. { If MatchOperand returns True, they must both be registers }
  11462. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11463. )
  11464. ) and
  11465. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11466. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11467. begin
  11468. 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);
  11469. asml.Remove(hp1);
  11470. asml.InsertBefore(hp1, p);
  11471. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11472. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11473. begin
  11474. taicpu(hp1).opcode := A_TEST;
  11475. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11476. end;
  11477. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11478. case taicpu(p).opsize of
  11479. S_BW, S_BL:
  11480. begin
  11481. SizeChange := taicpu(hp1).opsize <> S_B;
  11482. taicpu(hp1).changeopsize(S_B);
  11483. end;
  11484. S_WL:
  11485. begin
  11486. SizeChange := taicpu(hp1).opsize <> S_W;
  11487. taicpu(hp1).changeopsize(S_W);
  11488. end
  11489. else
  11490. InternalError(2020112701);
  11491. end;
  11492. UpdateUsedRegs(tai(p.Next));
  11493. { Check if the register is used aferwards - if not, we can
  11494. remove the movzx instruction completely }
  11495. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11496. begin
  11497. { Hp1 is a better position than p for debugging purposes }
  11498. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11499. RemoveCurrentp(p, hp1);
  11500. Result := True;
  11501. end;
  11502. if SizeChange then
  11503. DebugMsg(SPeepholeOptimization + PreMessage +
  11504. 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)
  11505. else
  11506. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11507. Exit;
  11508. end;
  11509. { Change (using movzwl %ax,%eax as an example):
  11510. movzwl %ax, %eax
  11511. movb %al, (dest) (Register is smaller than read register in movz)
  11512. To:
  11513. movb %al, (dest) (Move one back to avoid a false dependency)
  11514. movzwl %ax, %eax
  11515. }
  11516. if (taicpu(hp1).opcode = A_MOV) and
  11517. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11518. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11519. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11520. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11521. begin
  11522. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11523. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11524. asml.Remove(hp1);
  11525. asml.InsertBefore(hp1, p);
  11526. if taicpu(hp1).oper[1]^.typ = top_reg then
  11527. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11528. { Check if the register is used aferwards - if not, we can
  11529. remove the movzx instruction completely }
  11530. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11531. begin
  11532. { Hp1 is a better position than p for debugging purposes }
  11533. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11534. RemoveCurrentp(p, hp1);
  11535. Result := True;
  11536. end;
  11537. Exit;
  11538. end;
  11539. end;
  11540. end;
  11541. {$ifdef x86_64}
  11542. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11543. var
  11544. PreMessage, RegName: string;
  11545. begin
  11546. { Code size reduction by J. Gareth "Kit" Moreton }
  11547. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11548. as this removes the REX prefix }
  11549. Result := False;
  11550. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11551. Exit;
  11552. if taicpu(p).oper[0]^.typ <> top_reg then
  11553. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11554. InternalError(2018011500);
  11555. case taicpu(p).opsize of
  11556. S_Q:
  11557. begin
  11558. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11559. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11560. { The actual optimization }
  11561. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11562. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11563. taicpu(p).changeopsize(S_L);
  11564. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11565. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11566. end;
  11567. else
  11568. ;
  11569. end;
  11570. end;
  11571. {$endif}
  11572. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11573. var
  11574. XReg: TRegister;
  11575. begin
  11576. Result := False;
  11577. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11578. Smaller encoding and slightly faster on some platforms (also works for
  11579. ZMM-sized registers) }
  11580. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11581. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11582. begin
  11583. XReg := taicpu(p).oper[0]^.reg;
  11584. if (taicpu(p).oper[1]^.reg = XReg) then
  11585. begin
  11586. taicpu(p).changeopsize(S_XMM);
  11587. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11588. if (cs_opt_size in current_settings.optimizerswitches) then
  11589. begin
  11590. { Change input registers to %xmm0 to reduce size. Note that
  11591. there's a risk of a false dependency doing this, so only
  11592. optimise for size here }
  11593. XReg := NR_XMM0;
  11594. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11595. end
  11596. else
  11597. begin
  11598. setsubreg(XReg, R_SUBMMX);
  11599. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11600. end;
  11601. taicpu(p).oper[0]^.reg := XReg;
  11602. taicpu(p).oper[1]^.reg := XReg;
  11603. Result := True;
  11604. end;
  11605. end;
  11606. end;
  11607. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11608. var
  11609. OperIdx: Integer;
  11610. begin
  11611. for OperIdx := 0 to p.ops - 1 do
  11612. if p.oper[OperIdx]^.typ = top_ref then
  11613. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11614. end;
  11615. end.