aoptx86.pas 575 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  46. potentially allowing further optimisation (although it might need to know if
  47. it crossed a conditional jump. }
  48. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  49. {
  50. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  51. the use of a register by allocs/dealloc, so it can ignore calls.
  52. In the following example, GetNextInstructionUsingReg will return the second movq,
  53. GetNextInstructionUsingRegTrackingUse won't.
  54. movq %rdi,%rax
  55. # Register rdi released
  56. # Register rdi allocated
  57. movq %rax,%rdi
  58. While in this example:
  59. movq %rdi,%rax
  60. call proc
  61. movq %rdi,%rax
  62. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  63. won't.
  64. }
  65. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  66. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  67. private
  68. function SkipSimpleInstructions(var hp1: tai): Boolean;
  69. protected
  70. class function IsMOVZXAcceptable: Boolean; static; inline;
  71. { Attempts to allocate a volatile integer register for use between p and hp,
  72. using AUsedRegs for the current register usage information. Returns NR_NO
  73. if no free register could be found }
  74. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  75. { Attempts to allocate a volatile MM register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  79. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  80. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  81. { checks whether reading the value in reg1 depends on the value of reg2. This
  82. is very similar to SuperRegisterEquals, except it takes into account that
  83. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  84. depend on the value in AH). }
  85. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  86. { Replaces all references to AOldReg in a memory reference to ANewReg }
  87. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an operand to ANewReg }
  89. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  90. { Replaces all references to AOldReg in an instruction to ANewReg,
  91. except where the register is being written }
  92. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  93. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  94. or writes to a global symbol }
  95. class function IsRefSafe(const ref: PReference): Boolean; static;
  96. { Returns true if the given MOV instruction can be safely converted to CMOV }
  97. class function CanBeCMOV(p : tai) : boolean; static;
  98. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  99. conversion was successful }
  100. function ConvertLEA(const p : taicpu): Boolean;
  101. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  102. procedure DebugMsg(const s : string; p : tai);inline;
  103. class function IsExitCode(p : tai) : boolean; static;
  104. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  105. procedure RemoveLastDeallocForFuncRes(p : tai);
  106. function DoSubAddOpt(var p : tai) : Boolean;
  107. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  108. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  109. function PrePeepholeOptSxx(var p : tai) : boolean;
  110. function PrePeepholeOptIMUL(var p : tai) : boolean;
  111. function PrePeepholeOptAND(var p : tai) : boolean;
  112. function OptPass1Test(var p: tai): boolean;
  113. function OptPass1Add(var p: tai): boolean;
  114. function OptPass1AND(var p : tai) : boolean;
  115. function OptPass1_V_MOVAP(var p : tai) : boolean;
  116. function OptPass1VOP(var p : tai) : boolean;
  117. function OptPass1MOV(var p : tai) : boolean;
  118. function OptPass1Movx(var p : tai) : boolean;
  119. function OptPass1MOVXX(var p : tai) : boolean;
  120. function OptPass1OP(var p : tai) : boolean;
  121. function OptPass1LEA(var p : tai) : boolean;
  122. function OptPass1Sub(var p : tai) : boolean;
  123. function OptPass1SHLSAL(var p : tai) : boolean;
  124. function OptPass1FSTP(var p : tai) : boolean;
  125. function OptPass1FLD(var p : tai) : boolean;
  126. function OptPass1Cmp(var p : tai) : boolean;
  127. function OptPass1PXor(var p : tai) : boolean;
  128. function OptPass1VPXor(var p: tai): boolean;
  129. function OptPass1Imul(var p : tai) : boolean;
  130. function OptPass1Jcc(var p : tai) : boolean;
  131. function OptPass1SHXX(var p: tai): boolean;
  132. function OptPass1VMOVDQ(var p: tai): Boolean;
  133. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  134. function OptPass2Movx(var p : tai): Boolean;
  135. function OptPass2MOV(var p : tai) : boolean;
  136. function OptPass2Imul(var p : tai) : boolean;
  137. function OptPass2Jmp(var p : tai) : boolean;
  138. function OptPass2Jcc(var p : tai) : boolean;
  139. function OptPass2Lea(var p: tai): Boolean;
  140. function OptPass2SUB(var p: tai): Boolean;
  141. function OptPass2ADD(var p : tai): Boolean;
  142. function OptPass2SETcc(var p : tai) : boolean;
  143. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  144. function PostPeepholeOptMov(var p : tai) : Boolean;
  145. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  146. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  147. function PostPeepholeOptXor(var p : tai) : Boolean;
  148. {$endif x86_64}
  149. function PostPeepholeOptAnd(var p : tai) : boolean;
  150. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  151. function PostPeepholeOptCmp(var p : tai) : Boolean;
  152. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  153. function PostPeepholeOptCall(var p : tai) : Boolean;
  154. function PostPeepholeOptLea(var p : tai) : Boolean;
  155. function PostPeepholeOptPush(var p: tai): Boolean;
  156. function PostPeepholeOptShr(var p : tai) : boolean;
  157. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  158. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  159. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  160. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  161. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  162. { Processor-dependent reference optimisation }
  163. class procedure OptimizeRefs(var p: taicpu); static;
  164. end;
  165. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  168. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  169. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  170. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  171. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  172. {$if max_operands>2}
  173. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  174. {$endif max_operands>2}
  175. function RefsEqual(const r1, r2: treference): boolean;
  176. { Note that Result is set to True if the references COULD overlap but the
  177. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  178. might still overlap because %reg2 could be equal to %reg1-4 }
  179. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  180. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  181. { returns true, if ref is a reference using only the registers passed as base and index
  182. and having an offset }
  183. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  184. implementation
  185. uses
  186. cutils,verbose,
  187. systems,
  188. globals,
  189. cpuinfo,
  190. procinfo,
  191. paramgr,
  192. aasmbase,
  193. aoptbase,aoptutils,
  194. symconst,symsym,
  195. cgx86,
  196. itcpugas;
  197. {$ifdef DEBUG_AOPTCPU}
  198. const
  199. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  200. {$else DEBUG_AOPTCPU}
  201. { Empty strings help the optimizer to remove string concatenations that won't
  202. ever appear to the user on release builds. [Kit] }
  203. const
  204. SPeepholeOptimization = '';
  205. {$endif DEBUG_AOPTCPU}
  206. LIST_STEP_SIZE = 4;
  207. type
  208. TJumpTrackingItem = class(TLinkedListItem)
  209. private
  210. FSymbol: TAsmSymbol;
  211. FRefs: LongInt;
  212. public
  213. constructor Create(ASymbol: TAsmSymbol);
  214. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  215. property Symbol: TAsmSymbol read FSymbol;
  216. property Refs: LongInt read FRefs;
  217. end;
  218. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  219. begin
  220. inherited Create;
  221. FSymbol := ASymbol;
  222. FRefs := 0;
  223. end;
  224. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  225. begin
  226. Inc(FRefs);
  227. end;
  228. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  229. begin
  230. result :=
  231. (instr.typ = ait_instruction) and
  232. (taicpu(instr).opcode = op) and
  233. ((opsize = []) or (taicpu(instr).opsize in opsize));
  234. end;
  235. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. ((taicpu(instr).opcode = op1) or
  240. (taicpu(instr).opcode = op2)
  241. ) and
  242. ((opsize = []) or (taicpu(instr).opsize in opsize));
  243. end;
  244. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  245. begin
  246. result :=
  247. (instr.typ = ait_instruction) and
  248. ((taicpu(instr).opcode = op1) or
  249. (taicpu(instr).opcode = op2) or
  250. (taicpu(instr).opcode = op3)
  251. ) and
  252. ((opsize = []) or (taicpu(instr).opsize in opsize));
  253. end;
  254. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  255. const opsize : topsizes) : boolean;
  256. var
  257. op : TAsmOp;
  258. begin
  259. result:=false;
  260. if (instr.typ <> ait_instruction) or
  261. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  262. exit;
  263. for op in ops do
  264. begin
  265. if taicpu(instr).opcode = op then
  266. begin
  267. result:=true;
  268. exit;
  269. end;
  270. end;
  271. end;
  272. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  273. begin
  274. result := (oper.typ = top_reg) and (oper.reg = reg);
  275. end;
  276. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  277. begin
  278. result := (oper.typ = top_const) and (oper.val = a);
  279. end;
  280. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  281. begin
  282. result := oper1.typ = oper2.typ;
  283. if result then
  284. case oper1.typ of
  285. top_const:
  286. Result:=oper1.val = oper2.val;
  287. top_reg:
  288. Result:=oper1.reg = oper2.reg;
  289. top_ref:
  290. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  291. else
  292. internalerror(2013102801);
  293. end
  294. end;
  295. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  296. begin
  297. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  298. if result then
  299. case oper1.typ of
  300. top_const:
  301. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  302. top_reg:
  303. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  304. top_ref:
  305. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  306. else
  307. internalerror(2020052401);
  308. end
  309. end;
  310. function RefsEqual(const r1, r2: treference): boolean;
  311. begin
  312. RefsEqual :=
  313. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  314. (r1.relsymbol = r2.relsymbol) and
  315. (r1.segment = r2.segment) and (r1.base = r2.base) and
  316. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  317. (r1.offset = r2.offset) and
  318. (r1.volatility + r2.volatility = []);
  319. end;
  320. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  321. begin
  322. if (r1.symbol<>r2.symbol) then
  323. { If the index registers are different, there's a chance one could
  324. be set so it equals the other symbol }
  325. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  326. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  327. (r1.relsymbol = r2.relsymbol) and
  328. (r1.segment = r2.segment) and (r1.base = r2.base) and
  329. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  330. (r1.volatility + r2.volatility = []) then
  331. { In this case, it all depends on the offsets }
  332. Exit(abs(r1.offset - r2.offset) < Range);
  333. { There's a chance things MIGHT overlap, so take no chances }
  334. Result := True;
  335. end;
  336. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  337. begin
  338. Result:=(ref.offset=0) and
  339. (ref.scalefactor in [0,1]) and
  340. (ref.segment=NR_NO) and
  341. (ref.symbol=nil) and
  342. (ref.relsymbol=nil) and
  343. ((base=NR_INVALID) or
  344. (ref.base=base)) and
  345. ((index=NR_INVALID) or
  346. (ref.index=index)) and
  347. (ref.volatility=[]);
  348. end;
  349. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  350. begin
  351. Result:=(ref.scalefactor in [0,1]) and
  352. (ref.segment=NR_NO) and
  353. (ref.symbol=nil) and
  354. (ref.relsymbol=nil) and
  355. ((base=NR_INVALID) or
  356. (ref.base=base)) and
  357. ((index=NR_INVALID) or
  358. (ref.index=index)) and
  359. (ref.volatility=[]);
  360. end;
  361. function InstrReadsFlags(p: tai): boolean;
  362. begin
  363. InstrReadsFlags := true;
  364. case p.typ of
  365. ait_instruction:
  366. if InsProp[taicpu(p).opcode].Ch*
  367. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  368. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  369. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  370. exit;
  371. ait_label:
  372. exit;
  373. else
  374. ;
  375. end;
  376. InstrReadsFlags := false;
  377. end;
  378. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  379. begin
  380. Next:=Current;
  381. repeat
  382. Result:=GetNextInstruction(Next,Next);
  383. until not (Result) or
  384. not(cs_opt_level3 in current_settings.optimizerswitches) or
  385. (Next.typ<>ait_instruction) or
  386. RegInInstruction(reg,Next) or
  387. is_calljmp(taicpu(Next).opcode);
  388. end;
  389. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  390. procedure TrackJump(Symbol: TAsmSymbol);
  391. var
  392. Search: TJumpTrackingItem;
  393. begin
  394. { See if an entry already exists in our jump tracking list
  395. (faster to search backwards due to the higher chance of
  396. matching destinations) }
  397. Search := TJumpTrackingItem(JumpTracking.Last);
  398. while Assigned(Search) do
  399. begin
  400. if Search.Symbol = Symbol then
  401. begin
  402. { Found it - remove it so it can be pushed to the front }
  403. JumpTracking.Remove(Search);
  404. Break;
  405. end;
  406. Search := TJumpTrackingItem(Search.Previous);
  407. end;
  408. if not Assigned(Search) then
  409. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  410. JumpTracking.Concat(Search);
  411. Search.IncRefs;
  412. end;
  413. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  414. var
  415. Search: TJumpTrackingItem;
  416. begin
  417. Result := False;
  418. { See if this label appears in the tracking list }
  419. Search := TJumpTrackingItem(JumpTracking.Last);
  420. while Assigned(Search) do
  421. begin
  422. if Search.Symbol = Symbol then
  423. begin
  424. { Found it - let's see what we can discover }
  425. if Search.Symbol.getrefs = Search.Refs then
  426. begin
  427. { Success - all the references are accounted for }
  428. JumpTracking.Remove(Search);
  429. Search.Free;
  430. { It is logically impossible for CrossJump to be false here
  431. because we must have run into a conditional jump for
  432. this label at some point }
  433. if not CrossJump then
  434. InternalError(2022041710);
  435. if JumpTracking.First = nil then
  436. { Tracking list is now empty - no more cross jumps }
  437. CrossJump := False;
  438. Result := True;
  439. Exit;
  440. end;
  441. { If the references don't match, it's possible to enter
  442. this label through other means, so drop out }
  443. Exit;
  444. end;
  445. Search := TJumpTrackingItem(Search.Previous);
  446. end;
  447. end;
  448. var
  449. Next_Label: tai;
  450. begin
  451. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  452. Next := Current;
  453. repeat
  454. Result := GetNextInstruction(Next,Next);
  455. if not Result then
  456. Break;
  457. if Next.typ = ait_align then
  458. Result := SkipAligns(Next, Next);
  459. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  460. if is_calljmpuncondret(taicpu(Next).opcode) then
  461. begin
  462. if (taicpu(Next).opcode = A_JMP) and
  463. { Remove dead code now to save time }
  464. RemoveDeadCodeAfterJump(taicpu(Next)) then
  465. { A jump was removed, but not the current instruction, and
  466. Result doesn't necessarily translate into an optimisation
  467. routine's Result, so use the "Force New Iteration" flag so
  468. mark a new pass }
  469. Include(OptsToCheck, aoc_ForceNewIteration);
  470. if not Assigned(JumpTracking) then
  471. begin
  472. { Cross-label optimisations often causes other optimisations
  473. to perform worse because they're not given the chance to
  474. optimise locally. In this case, don't do the cross-label
  475. optimisations yet, but flag them as a potential possibility
  476. for the next iteration of Pass 1 }
  477. if not NotFirstIteration then
  478. Include(OptsToCheck, aoc_ForceNewIteration);
  479. end
  480. else if IsJumpToLabel(taicpu(Next)) and
  481. GetNextInstruction(Next, Next_Label) and
  482. SkipAligns(Next_Label, Next_Label) then
  483. begin
  484. { If we have JMP .lbl, and the label after it has all of its
  485. references tracked, then this is probably an if-else style of
  486. block and we can keep tracking. If the label for this jump
  487. then appears later and is fully tracked, then it's the end
  488. of the if-else blocks and the code paths converge (thus
  489. marking the end of the cross-jump) }
  490. if (Next_Label.typ = ait_label) then
  491. begin
  492. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  493. begin
  494. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  495. Next := Next_Label;
  496. { CrossJump gets set to false by LabelAccountedFor if the
  497. list is completely emptied (as it indicates that all
  498. code paths have converged). We could avoid this nuance
  499. by moving the TrackJump call to before the
  500. LabelAccountedFor call, but this is slower in situations
  501. where LabelAccountedFor would return False due to the
  502. creation of a new object that is not used and destroyed
  503. soon after. }
  504. CrossJump := True;
  505. Continue;
  506. end;
  507. end
  508. else if (Next_Label.typ <> ait_marker) then
  509. { We just did a RemoveDeadCodeAfterJump, so either we find
  510. a label, the end of the procedure or some kind of marker}
  511. InternalError(2022041720);
  512. end;
  513. Result := False;
  514. Exit;
  515. end
  516. else
  517. begin
  518. if not Assigned(JumpTracking) then
  519. begin
  520. { Cross-label optimisations often causes other optimisations
  521. to perform worse because they're not given the chance to
  522. optimise locally. In this case, don't do the cross-label
  523. optimisations yet, but flag them as a potential possibility
  524. for the next iteration of Pass 1 }
  525. if not NotFirstIteration then
  526. Include(OptsToCheck, aoc_ForceNewIteration);
  527. end
  528. else if IsJumpToLabel(taicpu(Next)) then
  529. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  530. else
  531. { Conditional jumps should always be a jump to label }
  532. InternalError(2022041701);
  533. CrossJump := True;
  534. Continue;
  535. end;
  536. if Next.typ = ait_label then
  537. begin
  538. if not Assigned(JumpTracking) then
  539. begin
  540. { Cross-label optimisations often causes other optimisations
  541. to perform worse because they're not given the chance to
  542. optimise locally. In this case, don't do the cross-label
  543. optimisations yet, but flag them as a potential possibility
  544. for the next iteration of Pass 1 }
  545. if not NotFirstIteration then
  546. Include(OptsToCheck, aoc_ForceNewIteration);
  547. end
  548. else if LabelAccountedFor(tai_label(Next).labsym) then
  549. Continue;
  550. { If we reach here, we're at a label that hasn't been seen before
  551. (or JumpTracking was nil) }
  552. Break;
  553. end;
  554. until not Result or
  555. not (cs_opt_level3 in current_settings.optimizerswitches) or
  556. not (Next.typ in [ait_label, ait_instruction]) or
  557. RegInInstruction(reg,Next);
  558. end;
  559. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  560. begin
  561. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  562. begin
  563. Result:=GetNextInstruction(Current,Next);
  564. exit;
  565. end;
  566. Next:=tai(Current.Next);
  567. Result:=false;
  568. while assigned(Next) do
  569. begin
  570. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  571. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  572. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  573. exit
  574. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  575. begin
  576. Result:=true;
  577. exit;
  578. end;
  579. Next:=tai(Next.Next);
  580. end;
  581. end;
  582. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  583. begin
  584. Result:=RegReadByInstruction(reg,hp);
  585. end;
  586. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  587. var
  588. p: taicpu;
  589. opcount: longint;
  590. begin
  591. RegReadByInstruction := false;
  592. if hp.typ <> ait_instruction then
  593. exit;
  594. p := taicpu(hp);
  595. case p.opcode of
  596. A_CALL:
  597. regreadbyinstruction := true;
  598. A_IMUL:
  599. case p.ops of
  600. 1:
  601. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  602. (
  603. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  604. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  605. );
  606. 2,3:
  607. regReadByInstruction :=
  608. reginop(reg,p.oper[0]^) or
  609. reginop(reg,p.oper[1]^);
  610. else
  611. InternalError(2019112801);
  612. end;
  613. A_MUL:
  614. begin
  615. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  616. (
  617. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  618. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  619. );
  620. end;
  621. A_IDIV,A_DIV:
  622. begin
  623. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  624. (
  625. (getregtype(reg)=R_INTREGISTER) and
  626. (
  627. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  628. )
  629. );
  630. end;
  631. else
  632. begin
  633. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  634. begin
  635. RegReadByInstruction := false;
  636. exit;
  637. end;
  638. for opcount := 0 to p.ops-1 do
  639. if (p.oper[opCount]^.typ = top_ref) and
  640. RegInRef(reg,p.oper[opcount]^.ref^) then
  641. begin
  642. RegReadByInstruction := true;
  643. exit
  644. end;
  645. { special handling for SSE MOVSD }
  646. if (p.opcode=A_MOVSD) and (p.ops>0) then
  647. begin
  648. if p.ops<>2 then
  649. internalerror(2017042702);
  650. regReadByInstruction := reginop(reg,p.oper[0]^) or
  651. (
  652. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  653. );
  654. exit;
  655. end;
  656. with insprop[p.opcode] do
  657. begin
  658. case getregtype(reg) of
  659. R_INTREGISTER:
  660. begin
  661. case getsupreg(reg) of
  662. RS_EAX:
  663. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  664. begin
  665. RegReadByInstruction := true;
  666. exit
  667. end;
  668. RS_ECX:
  669. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  670. begin
  671. RegReadByInstruction := true;
  672. exit
  673. end;
  674. RS_EDX:
  675. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  676. begin
  677. RegReadByInstruction := true;
  678. exit
  679. end;
  680. RS_EBX:
  681. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  682. begin
  683. RegReadByInstruction := true;
  684. exit
  685. end;
  686. RS_ESP:
  687. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  688. begin
  689. RegReadByInstruction := true;
  690. exit
  691. end;
  692. RS_EBP:
  693. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  694. begin
  695. RegReadByInstruction := true;
  696. exit
  697. end;
  698. RS_ESI:
  699. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  700. begin
  701. RegReadByInstruction := true;
  702. exit
  703. end;
  704. RS_EDI:
  705. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  706. begin
  707. RegReadByInstruction := true;
  708. exit
  709. end;
  710. end;
  711. end;
  712. R_MMREGISTER:
  713. begin
  714. case getsupreg(reg) of
  715. RS_XMM0:
  716. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  717. begin
  718. RegReadByInstruction := true;
  719. exit
  720. end;
  721. end;
  722. end;
  723. else
  724. ;
  725. end;
  726. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  727. begin
  728. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  729. begin
  730. case p.condition of
  731. C_A,C_NBE, { CF=0 and ZF=0 }
  732. C_BE,C_NA: { CF=1 or ZF=1 }
  733. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  734. C_AE,C_NB,C_NC, { CF=0 }
  735. C_B,C_NAE,C_C: { CF=1 }
  736. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  737. C_NE,C_NZ, { ZF=0 }
  738. C_E,C_Z: { ZF=1 }
  739. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  740. C_G,C_NLE, { ZF=0 and SF=OF }
  741. C_LE,C_NG: { ZF=1 or SF<>OF }
  742. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  743. C_GE,C_NL, { SF=OF }
  744. C_L,C_NGE: { SF<>OF }
  745. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  746. C_NO, { OF=0 }
  747. C_O: { OF=1 }
  748. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  749. C_NP,C_PO, { PF=0 }
  750. C_P,C_PE: { PF=1 }
  751. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  752. C_NS, { SF=0 }
  753. C_S: { SF=1 }
  754. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  755. else
  756. internalerror(2017042701);
  757. end;
  758. if RegReadByInstruction then
  759. exit;
  760. end;
  761. case getsubreg(reg) of
  762. R_SUBW,R_SUBD,R_SUBQ:
  763. RegReadByInstruction :=
  764. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  765. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  766. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  767. R_SUBFLAGCARRY:
  768. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  769. R_SUBFLAGPARITY:
  770. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  771. R_SUBFLAGAUXILIARY:
  772. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  773. R_SUBFLAGZERO:
  774. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  775. R_SUBFLAGSIGN:
  776. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  777. R_SUBFLAGOVERFLOW:
  778. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  779. R_SUBFLAGINTERRUPT:
  780. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  781. R_SUBFLAGDIRECTION:
  782. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  783. else
  784. internalerror(2017042601);
  785. end;
  786. exit;
  787. end;
  788. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  789. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  790. (p.oper[0]^.reg=p.oper[1]^.reg) then
  791. exit;
  792. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  803. begin
  804. RegReadByInstruction := true;
  805. exit
  806. end;
  807. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  808. begin
  809. RegReadByInstruction := true;
  810. exit
  811. end;
  812. end;
  813. end;
  814. end;
  815. end;
  816. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  817. begin
  818. result:=false;
  819. if p1.typ<>ait_instruction then
  820. exit;
  821. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  822. exit(true);
  823. if (getregtype(reg)=R_INTREGISTER) and
  824. { change information for xmm movsd are not correct }
  825. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  826. begin
  827. case getsupreg(reg) of
  828. { RS_EAX = RS_RAX on x86-64 }
  829. RS_EAX:
  830. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  831. RS_ECX:
  832. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  833. RS_EDX:
  834. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  835. RS_EBX:
  836. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  837. RS_ESP:
  838. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  839. RS_EBP:
  840. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  841. RS_ESI:
  842. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  843. RS_EDI:
  844. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  845. else
  846. ;
  847. end;
  848. if result then
  849. exit;
  850. end
  851. else if getregtype(reg)=R_MMREGISTER then
  852. begin
  853. case getsupreg(reg) of
  854. RS_XMM0:
  855. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  856. else
  857. ;
  858. end;
  859. if result then
  860. exit;
  861. end
  862. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  863. begin
  864. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  865. exit(true);
  866. case getsubreg(reg) of
  867. R_SUBFLAGCARRY:
  868. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. R_SUBFLAGPARITY:
  870. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. R_SUBFLAGAUXILIARY:
  872. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  873. R_SUBFLAGZERO:
  874. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  875. R_SUBFLAGSIGN:
  876. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  877. R_SUBFLAGOVERFLOW:
  878. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  879. R_SUBFLAGINTERRUPT:
  880. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. R_SUBFLAGDIRECTION:
  882. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. R_SUBW,R_SUBD,R_SUBQ:
  884. { Everything except the direction bits }
  885. Result:=
  886. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  887. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  888. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  889. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  890. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  891. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  892. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. else
  894. ;
  895. end;
  896. if result then
  897. exit;
  898. end
  899. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  900. exit(true);
  901. Result:=inherited RegInInstruction(Reg, p1);
  902. end;
  903. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  904. const
  905. WriteOps: array[0..3] of set of TInsChange =
  906. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  907. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  908. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  909. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  910. var
  911. OperIdx: Integer;
  912. begin
  913. Result := False;
  914. if p1.typ <> ait_instruction then
  915. exit;
  916. with insprop[taicpu(p1).opcode] do
  917. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  918. begin
  919. case getsubreg(reg) of
  920. R_SUBW,R_SUBD,R_SUBQ:
  921. Result :=
  922. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  923. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  924. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  925. R_SUBFLAGCARRY:
  926. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  927. R_SUBFLAGPARITY:
  928. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  929. R_SUBFLAGAUXILIARY:
  930. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  931. R_SUBFLAGZERO:
  932. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  933. R_SUBFLAGSIGN:
  934. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  935. R_SUBFLAGOVERFLOW:
  936. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  937. R_SUBFLAGINTERRUPT:
  938. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  939. R_SUBFLAGDIRECTION:
  940. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  941. else
  942. internalerror(2017042602);
  943. end;
  944. exit;
  945. end;
  946. case taicpu(p1).opcode of
  947. A_CALL:
  948. { We could potentially set Result to False if the register in
  949. question is non-volatile for the subroutine's calling convention,
  950. but this would require detecting the calling convention in use and
  951. also assuming that the routine doesn't contain malformed assembly
  952. language, for example... so it could only be done under -O4 as it
  953. would be considered a side-effect. [Kit] }
  954. Result := True;
  955. A_MOVSD:
  956. { special handling for SSE MOVSD }
  957. if (taicpu(p1).ops>0) then
  958. begin
  959. if taicpu(p1).ops<>2 then
  960. internalerror(2017042703);
  961. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  962. end;
  963. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  964. so fix it here (FK)
  965. }
  966. A_VMOVSS,
  967. A_VMOVSD:
  968. begin
  969. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  970. exit;
  971. end;
  972. A_IMUL:
  973. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  974. else
  975. ;
  976. end;
  977. if Result then
  978. exit;
  979. with insprop[taicpu(p1).opcode] do
  980. begin
  981. if getregtype(reg)=R_INTREGISTER then
  982. begin
  983. case getsupreg(reg) of
  984. RS_EAX:
  985. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  986. begin
  987. Result := True;
  988. exit
  989. end;
  990. RS_ECX:
  991. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  992. begin
  993. Result := True;
  994. exit
  995. end;
  996. RS_EDX:
  997. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  998. begin
  999. Result := True;
  1000. exit
  1001. end;
  1002. RS_EBX:
  1003. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1004. begin
  1005. Result := True;
  1006. exit
  1007. end;
  1008. RS_ESP:
  1009. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1010. begin
  1011. Result := True;
  1012. exit
  1013. end;
  1014. RS_EBP:
  1015. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1016. begin
  1017. Result := True;
  1018. exit
  1019. end;
  1020. RS_ESI:
  1021. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1022. begin
  1023. Result := True;
  1024. exit
  1025. end;
  1026. RS_EDI:
  1027. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1028. begin
  1029. Result := True;
  1030. exit
  1031. end;
  1032. end;
  1033. end;
  1034. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1035. if (WriteOps[OperIdx]*Ch<>[]) and
  1036. { The register doesn't get modified inside a reference }
  1037. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1038. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1039. begin
  1040. Result := true;
  1041. exit
  1042. end;
  1043. end;
  1044. end;
  1045. {$ifdef DEBUG_AOPTCPU}
  1046. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1047. begin
  1048. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1049. end;
  1050. function debug_tostr(i: tcgint): string; inline;
  1051. begin
  1052. Result := tostr(i);
  1053. end;
  1054. function debug_regname(r: TRegister): string; inline;
  1055. begin
  1056. Result := '%' + std_regname(r);
  1057. end;
  1058. { Debug output function - creates a string representation of an operator }
  1059. function debug_operstr(oper: TOper): string;
  1060. begin
  1061. case oper.typ of
  1062. top_const:
  1063. Result := '$' + debug_tostr(oper.val);
  1064. top_reg:
  1065. Result := debug_regname(oper.reg);
  1066. top_ref:
  1067. begin
  1068. if oper.ref^.offset <> 0 then
  1069. Result := debug_tostr(oper.ref^.offset) + '('
  1070. else
  1071. Result := '(';
  1072. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1073. begin
  1074. Result := Result + debug_regname(oper.ref^.base);
  1075. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1076. Result := Result + ',' + debug_regname(oper.ref^.index);
  1077. end
  1078. else
  1079. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1080. Result := Result + debug_regname(oper.ref^.index);
  1081. if (oper.ref^.scalefactor > 1) then
  1082. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1083. else
  1084. Result := Result + ')';
  1085. end;
  1086. else
  1087. Result := '[UNKNOWN]';
  1088. end;
  1089. end;
  1090. function debug_op2str(opcode: tasmop): string; inline;
  1091. begin
  1092. Result := std_op2str[opcode];
  1093. end;
  1094. function debug_opsize2str(opsize: topsize): string; inline;
  1095. begin
  1096. Result := gas_opsize2str[opsize];
  1097. end;
  1098. {$else DEBUG_AOPTCPU}
  1099. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1100. begin
  1101. end;
  1102. function debug_tostr(i: tcgint): string; inline;
  1103. begin
  1104. Result := '';
  1105. end;
  1106. function debug_regname(r: TRegister): string; inline;
  1107. begin
  1108. Result := '';
  1109. end;
  1110. function debug_operstr(oper: TOper): string; inline;
  1111. begin
  1112. Result := '';
  1113. end;
  1114. function debug_op2str(opcode: tasmop): string; inline;
  1115. begin
  1116. Result := '';
  1117. end;
  1118. function debug_opsize2str(opsize: topsize): string; inline;
  1119. begin
  1120. Result := '';
  1121. end;
  1122. {$endif DEBUG_AOPTCPU}
  1123. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1124. begin
  1125. {$ifdef x86_64}
  1126. { Always fine on x86-64 }
  1127. Result := True;
  1128. {$else x86_64}
  1129. Result :=
  1130. {$ifdef i8086}
  1131. (current_settings.cputype >= cpu_386) and
  1132. {$endif i8086}
  1133. (
  1134. { Always accept if optimising for size }
  1135. (cs_opt_size in current_settings.optimizerswitches) or
  1136. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1137. (current_settings.optimizecputype >= cpu_Pentium2)
  1138. );
  1139. {$endif x86_64}
  1140. end;
  1141. { Attempts to allocate a volatile integer register for use between p and hp,
  1142. using AUsedRegs for the current register usage information. Returns NR_NO
  1143. if no free register could be found }
  1144. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1145. var
  1146. RegSet: TCPURegisterSet;
  1147. CurrentSuperReg: Integer;
  1148. CurrentReg: TRegister;
  1149. Currentp: tai;
  1150. Breakout: Boolean;
  1151. begin
  1152. Result := NR_NO;
  1153. RegSet :=
  1154. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1155. current_procinfo.saved_regs_int;
  1156. for CurrentSuperReg in RegSet do
  1157. begin
  1158. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1159. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1160. {$if defined(i386) or defined(i8086)}
  1161. { If the target size is 8-bit, make sure we can actually encode it }
  1162. and (
  1163. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1164. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1165. )
  1166. {$endif i386 or i8086}
  1167. then
  1168. begin
  1169. Currentp := p;
  1170. Breakout := False;
  1171. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1172. begin
  1173. case Currentp.typ of
  1174. ait_instruction:
  1175. begin
  1176. if RegInInstruction(CurrentReg, Currentp) then
  1177. begin
  1178. Breakout := True;
  1179. Break;
  1180. end;
  1181. { Cannot allocate across an unconditional jump }
  1182. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1183. Exit;
  1184. end;
  1185. ait_marker:
  1186. { Don't try anything more if a marker is hit }
  1187. Exit;
  1188. ait_regalloc:
  1189. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1190. begin
  1191. Breakout := True;
  1192. Break;
  1193. end;
  1194. else
  1195. ;
  1196. end;
  1197. end;
  1198. if Breakout then
  1199. { Try the next register }
  1200. Continue;
  1201. { We have a free register available }
  1202. Result := CurrentReg;
  1203. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1204. Exit;
  1205. end;
  1206. end;
  1207. end;
  1208. { Attempts to allocate a volatile MM register for use between p and hp,
  1209. using AUsedRegs for the current register usage information. Returns NR_NO
  1210. if no free register could be found }
  1211. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1212. var
  1213. RegSet: TCPURegisterSet;
  1214. CurrentSuperReg: Integer;
  1215. CurrentReg: TRegister;
  1216. Currentp: tai;
  1217. Breakout: Boolean;
  1218. begin
  1219. Result := NR_NO;
  1220. RegSet :=
  1221. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1222. current_procinfo.saved_regs_mm;
  1223. for CurrentSuperReg in RegSet do
  1224. begin
  1225. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1226. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1227. begin
  1228. Currentp := p;
  1229. Breakout := False;
  1230. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1231. begin
  1232. case Currentp.typ of
  1233. ait_instruction:
  1234. begin
  1235. if RegInInstruction(CurrentReg, Currentp) then
  1236. begin
  1237. Breakout := True;
  1238. Break;
  1239. end;
  1240. { Cannot allocate across an unconditional jump }
  1241. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1242. Exit;
  1243. end;
  1244. ait_marker:
  1245. { Don't try anything more if a marker is hit }
  1246. Exit;
  1247. ait_regalloc:
  1248. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1249. begin
  1250. Breakout := True;
  1251. Break;
  1252. end;
  1253. else
  1254. ;
  1255. end;
  1256. end;
  1257. if Breakout then
  1258. { Try the next register }
  1259. Continue;
  1260. { We have a free register available }
  1261. Result := CurrentReg;
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1268. begin
  1269. if not SuperRegistersEqual(reg1,reg2) then
  1270. exit(false);
  1271. if getregtype(reg1)<>R_INTREGISTER then
  1272. exit(true); {because SuperRegisterEqual is true}
  1273. case getsubreg(reg1) of
  1274. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1275. higher, it preserves the high bits, so the new value depends on
  1276. reg2's previous value. In other words, it is equivalent to doing:
  1277. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1278. R_SUBL:
  1279. exit(getsubreg(reg2)=R_SUBL);
  1280. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1281. higher, it actually does a:
  1282. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1283. R_SUBH:
  1284. exit(getsubreg(reg2)=R_SUBH);
  1285. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1286. bits of reg2:
  1287. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1288. R_SUBW:
  1289. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1290. { a write to R_SUBD always overwrites every other subregister,
  1291. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1292. R_SUBD,
  1293. R_SUBQ:
  1294. exit(true);
  1295. else
  1296. internalerror(2017042801);
  1297. end;
  1298. end;
  1299. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1300. begin
  1301. if not SuperRegistersEqual(reg1,reg2) then
  1302. exit(false);
  1303. if getregtype(reg1)<>R_INTREGISTER then
  1304. exit(true); {because SuperRegisterEqual is true}
  1305. case getsubreg(reg1) of
  1306. R_SUBL:
  1307. exit(getsubreg(reg2)<>R_SUBH);
  1308. R_SUBH:
  1309. exit(getsubreg(reg2)<>R_SUBL);
  1310. R_SUBW,
  1311. R_SUBD,
  1312. R_SUBQ:
  1313. exit(true);
  1314. else
  1315. internalerror(2017042802);
  1316. end;
  1317. end;
  1318. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1319. var
  1320. hp1 : tai;
  1321. l : TCGInt;
  1322. begin
  1323. result:=false;
  1324. { changes the code sequence
  1325. shr/sar const1, x
  1326. shl const2, x
  1327. to
  1328. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1329. if GetNextInstruction(p, hp1) and
  1330. MatchInstruction(hp1,A_SHL,[]) and
  1331. (taicpu(p).oper[0]^.typ = top_const) and
  1332. (taicpu(hp1).oper[0]^.typ = top_const) and
  1333. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1334. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1335. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1336. begin
  1337. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1338. not(cs_opt_size in current_settings.optimizerswitches) then
  1339. begin
  1340. { shr/sar const1, %reg
  1341. shl const2, %reg
  1342. with const1 > const2 }
  1343. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1344. taicpu(hp1).opcode := A_AND;
  1345. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1346. case taicpu(p).opsize Of
  1347. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1348. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1349. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1350. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1351. else
  1352. Internalerror(2017050703)
  1353. end;
  1354. end
  1355. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1356. not(cs_opt_size in current_settings.optimizerswitches) then
  1357. begin
  1358. { shr/sar const1, %reg
  1359. shl const2, %reg
  1360. with const1 < const2 }
  1361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1362. taicpu(p).opcode := A_AND;
  1363. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1364. case taicpu(p).opsize Of
  1365. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1366. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1367. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1368. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1369. else
  1370. Internalerror(2017050702)
  1371. end;
  1372. end
  1373. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1374. begin
  1375. { shr/sar const1, %reg
  1376. shl const2, %reg
  1377. with const1 = const2 }
  1378. taicpu(p).opcode := A_AND;
  1379. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1380. case taicpu(p).opsize Of
  1381. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1382. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1383. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1384. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1385. else
  1386. Internalerror(2017050701)
  1387. end;
  1388. RemoveInstruction(hp1);
  1389. end;
  1390. end;
  1391. end;
  1392. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1393. var
  1394. opsize : topsize;
  1395. hp1 : tai;
  1396. tmpref : treference;
  1397. ShiftValue : Cardinal;
  1398. BaseValue : TCGInt;
  1399. begin
  1400. result:=false;
  1401. opsize:=taicpu(p).opsize;
  1402. { changes certain "imul const, %reg"'s to lea sequences }
  1403. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1404. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1405. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1406. if (taicpu(p).oper[0]^.val = 1) then
  1407. if (taicpu(p).ops = 2) then
  1408. { remove "imul $1, reg" }
  1409. begin
  1410. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1411. Result := RemoveCurrentP(p);
  1412. end
  1413. else
  1414. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1415. begin
  1416. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1417. InsertLLItem(p.previous, p.next, hp1);
  1418. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1419. p.free;
  1420. p := hp1;
  1421. end
  1422. else if ((taicpu(p).ops <= 2) or
  1423. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1424. not(cs_opt_size in current_settings.optimizerswitches) and
  1425. (not(GetNextInstruction(p, hp1)) or
  1426. not((tai(hp1).typ = ait_instruction) and
  1427. ((taicpu(hp1).opcode=A_Jcc) and
  1428. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1429. begin
  1430. {
  1431. imul X, reg1, reg2 to
  1432. lea (reg1,reg1,Y), reg2
  1433. shl ZZ,reg2
  1434. imul XX, reg1 to
  1435. lea (reg1,reg1,YY), reg1
  1436. shl ZZ,reg2
  1437. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1438. it does not exist as a separate optimization target in FPC though.
  1439. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1440. at most two zeros
  1441. }
  1442. reference_reset(tmpref,1,[]);
  1443. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1444. begin
  1445. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1446. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1447. TmpRef.base := taicpu(p).oper[1]^.reg;
  1448. TmpRef.index := taicpu(p).oper[1]^.reg;
  1449. if not(BaseValue in [3,5,9]) then
  1450. Internalerror(2018110101);
  1451. TmpRef.ScaleFactor := BaseValue-1;
  1452. if (taicpu(p).ops = 2) then
  1453. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1454. else
  1455. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1456. AsmL.InsertAfter(hp1,p);
  1457. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1458. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1459. RemoveCurrentP(p, hp1);
  1460. if ShiftValue>0 then
  1461. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1462. end;
  1463. end;
  1464. end;
  1465. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1466. begin
  1467. Result := False;
  1468. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1470. begin
  1471. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1472. taicpu(p).opcode := A_MOV;
  1473. Result := True;
  1474. end;
  1475. end;
  1476. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1477. var
  1478. p: taicpu absolute hp; { Implicit typecast }
  1479. i: Integer;
  1480. begin
  1481. Result := False;
  1482. if not assigned(hp) or
  1483. (hp.typ <> ait_instruction) then
  1484. Exit;
  1485. Prefetch(insprop[p.opcode]);
  1486. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1487. with insprop[p.opcode] do
  1488. begin
  1489. case getsubreg(reg) of
  1490. R_SUBW,R_SUBD,R_SUBQ:
  1491. Result:=
  1492. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1493. uncommon flags are checked first }
  1494. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1495. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1496. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1497. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1498. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1499. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1500. R_SUBFLAGCARRY:
  1501. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1502. R_SUBFLAGPARITY:
  1503. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1504. R_SUBFLAGAUXILIARY:
  1505. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1506. R_SUBFLAGZERO:
  1507. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1508. R_SUBFLAGSIGN:
  1509. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1510. R_SUBFLAGOVERFLOW:
  1511. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1512. R_SUBFLAGINTERRUPT:
  1513. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1514. R_SUBFLAGDIRECTION:
  1515. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1516. else
  1517. internalerror(2017050501);
  1518. end;
  1519. exit;
  1520. end;
  1521. { Handle special cases first }
  1522. case p.opcode of
  1523. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1524. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1525. begin
  1526. Result :=
  1527. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1528. (p.oper[1]^.typ = top_reg) and
  1529. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1530. (
  1531. (p.oper[0]^.typ = top_const) or
  1532. (
  1533. (p.oper[0]^.typ = top_reg) and
  1534. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1535. ) or (
  1536. (p.oper[0]^.typ = top_ref) and
  1537. not RegInRef(reg,p.oper[0]^.ref^)
  1538. )
  1539. );
  1540. end;
  1541. A_MUL, A_IMUL:
  1542. Result :=
  1543. (
  1544. (p.ops=3) and { IMUL only }
  1545. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1546. (
  1547. (
  1548. (p.oper[1]^.typ=top_reg) and
  1549. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1550. ) or (
  1551. (p.oper[1]^.typ=top_ref) and
  1552. not RegInRef(reg,p.oper[1]^.ref^)
  1553. )
  1554. )
  1555. ) or (
  1556. (
  1557. (p.ops=1) and
  1558. (
  1559. (
  1560. (
  1561. (p.oper[0]^.typ=top_reg) and
  1562. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1563. )
  1564. ) or (
  1565. (p.oper[0]^.typ=top_ref) and
  1566. not RegInRef(reg,p.oper[0]^.ref^)
  1567. )
  1568. ) and (
  1569. (
  1570. (p.opsize=S_B) and
  1571. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1572. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1573. ) or (
  1574. (p.opsize=S_W) and
  1575. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1576. ) or (
  1577. (p.opsize=S_L) and
  1578. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1579. {$ifdef x86_64}
  1580. ) or (
  1581. (p.opsize=S_Q) and
  1582. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1583. {$endif x86_64}
  1584. )
  1585. )
  1586. )
  1587. );
  1588. A_CBW:
  1589. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1590. {$ifndef x86_64}
  1591. A_LDS:
  1592. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1593. A_LES:
  1594. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1595. {$endif not x86_64}
  1596. A_LFS:
  1597. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1598. A_LGS:
  1599. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1600. A_LSS:
  1601. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1602. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1603. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1604. A_LODSB:
  1605. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1606. A_LODSW:
  1607. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1608. {$ifdef x86_64}
  1609. A_LODSQ:
  1610. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1611. {$endif x86_64}
  1612. A_LODSD:
  1613. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1614. A_FSTSW, A_FNSTSW:
  1615. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1616. else
  1617. begin
  1618. with insprop[p.opcode] do
  1619. begin
  1620. if (
  1621. { xor %reg,%reg etc. is classed as a new value }
  1622. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1623. MatchOpType(p, top_reg, top_reg) and
  1624. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1625. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1626. ) then
  1627. begin
  1628. Result := True;
  1629. Exit;
  1630. end;
  1631. { Make sure the entire register is overwritten }
  1632. if (getregtype(reg) = R_INTREGISTER) then
  1633. begin
  1634. if (p.ops > 0) then
  1635. begin
  1636. if RegInOp(reg, p.oper[0]^) then
  1637. begin
  1638. if (p.oper[0]^.typ = top_ref) then
  1639. begin
  1640. if RegInRef(reg, p.oper[0]^.ref^) then
  1641. begin
  1642. Result := False;
  1643. Exit;
  1644. end;
  1645. end
  1646. else if (p.oper[0]^.typ = top_reg) then
  1647. begin
  1648. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1649. begin
  1650. Result := False;
  1651. Exit;
  1652. end
  1653. else if ([Ch_WOp1]*Ch<>[]) then
  1654. begin
  1655. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1656. Result := True
  1657. else
  1658. begin
  1659. Result := False;
  1660. Exit;
  1661. end;
  1662. end;
  1663. end;
  1664. end;
  1665. if (p.ops > 1) then
  1666. begin
  1667. if RegInOp(reg, p.oper[1]^) then
  1668. begin
  1669. if (p.oper[1]^.typ = top_ref) then
  1670. begin
  1671. if RegInRef(reg, p.oper[1]^.ref^) then
  1672. begin
  1673. Result := False;
  1674. Exit;
  1675. end;
  1676. end
  1677. else if (p.oper[1]^.typ = top_reg) then
  1678. begin
  1679. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1680. begin
  1681. Result := False;
  1682. Exit;
  1683. end
  1684. else if ([Ch_WOp2]*Ch<>[]) then
  1685. begin
  1686. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1687. Result := True
  1688. else
  1689. begin
  1690. Result := False;
  1691. Exit;
  1692. end;
  1693. end;
  1694. end;
  1695. end;
  1696. if (p.ops > 2) then
  1697. begin
  1698. if RegInOp(reg, p.oper[2]^) then
  1699. begin
  1700. if (p.oper[2]^.typ = top_ref) then
  1701. begin
  1702. if RegInRef(reg, p.oper[2]^.ref^) then
  1703. begin
  1704. Result := False;
  1705. Exit;
  1706. end;
  1707. end
  1708. else if (p.oper[2]^.typ = top_reg) then
  1709. begin
  1710. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1711. begin
  1712. Result := False;
  1713. Exit;
  1714. end
  1715. else if ([Ch_WOp3]*Ch<>[]) then
  1716. begin
  1717. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1718. Result := True
  1719. else
  1720. begin
  1721. Result := False;
  1722. Exit;
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1728. begin
  1729. if (p.oper[3]^.typ = top_ref) then
  1730. begin
  1731. if RegInRef(reg, p.oper[3]^.ref^) then
  1732. begin
  1733. Result := False;
  1734. Exit;
  1735. end;
  1736. end
  1737. else if (p.oper[3]^.typ = top_reg) then
  1738. begin
  1739. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1740. begin
  1741. Result := False;
  1742. Exit;
  1743. end
  1744. else if ([Ch_WOp4]*Ch<>[]) then
  1745. begin
  1746. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1747. Result := True
  1748. else
  1749. begin
  1750. Result := False;
  1751. Exit;
  1752. end;
  1753. end;
  1754. end;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1760. case getsupreg(reg) of
  1761. RS_EAX:
  1762. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1763. begin
  1764. Result := True;
  1765. Exit;
  1766. end;
  1767. RS_ECX:
  1768. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1769. begin
  1770. Result := True;
  1771. Exit;
  1772. end;
  1773. RS_EDX:
  1774. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1775. begin
  1776. Result := True;
  1777. Exit;
  1778. end;
  1779. RS_EBX:
  1780. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. RS_ESP:
  1786. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1787. begin
  1788. Result := True;
  1789. Exit;
  1790. end;
  1791. RS_EBP:
  1792. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1793. begin
  1794. Result := True;
  1795. Exit;
  1796. end;
  1797. RS_ESI:
  1798. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1799. begin
  1800. Result := True;
  1801. Exit;
  1802. end;
  1803. RS_EDI:
  1804. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1805. begin
  1806. Result := True;
  1807. Exit;
  1808. end;
  1809. else
  1810. ;
  1811. end;
  1812. end;
  1813. end;
  1814. end;
  1815. end;
  1816. end;
  1817. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1818. var
  1819. hp2,hp3 : tai;
  1820. begin
  1821. { some x86-64 issue a NOP before the real exit code }
  1822. if MatchInstruction(p,A_NOP,[]) then
  1823. GetNextInstruction(p,p);
  1824. result:=assigned(p) and (p.typ=ait_instruction) and
  1825. ((taicpu(p).opcode = A_RET) or
  1826. ((taicpu(p).opcode=A_LEAVE) and
  1827. GetNextInstruction(p,hp2) and
  1828. MatchInstruction(hp2,A_RET,[S_NO])
  1829. ) or
  1830. (((taicpu(p).opcode=A_LEA) and
  1831. MatchOpType(taicpu(p),top_ref,top_reg) and
  1832. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1833. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1834. ) and
  1835. GetNextInstruction(p,hp2) and
  1836. MatchInstruction(hp2,A_RET,[S_NO])
  1837. ) or
  1838. ((((taicpu(p).opcode=A_MOV) and
  1839. MatchOpType(taicpu(p),top_reg,top_reg) and
  1840. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1841. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1842. ((taicpu(p).opcode=A_LEA) and
  1843. MatchOpType(taicpu(p),top_ref,top_reg) and
  1844. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1845. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1846. )
  1847. ) and
  1848. GetNextInstruction(p,hp2) and
  1849. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1850. MatchOpType(taicpu(hp2),top_reg) and
  1851. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1852. GetNextInstruction(hp2,hp3) and
  1853. MatchInstruction(hp3,A_RET,[S_NO])
  1854. )
  1855. );
  1856. end;
  1857. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1858. begin
  1859. isFoldableArithOp := False;
  1860. case hp1.opcode of
  1861. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1862. isFoldableArithOp :=
  1863. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1864. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1865. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1867. (taicpu(hp1).oper[1]^.reg = reg);
  1868. A_INC,A_DEC,A_NEG,A_NOT:
  1869. isFoldableArithOp :=
  1870. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1871. (taicpu(hp1).oper[0]^.reg = reg);
  1872. else
  1873. ;
  1874. end;
  1875. end;
  1876. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1877. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1878. var
  1879. hp2: tai;
  1880. begin
  1881. hp2 := p;
  1882. repeat
  1883. hp2 := tai(hp2.previous);
  1884. if assigned(hp2) and
  1885. (hp2.typ = ait_regalloc) and
  1886. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1887. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1888. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1889. begin
  1890. RemoveInstruction(hp2);
  1891. break;
  1892. end;
  1893. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1894. end;
  1895. begin
  1896. case current_procinfo.procdef.returndef.typ of
  1897. arraydef,recorddef,pointerdef,
  1898. stringdef,enumdef,procdef,objectdef,errordef,
  1899. filedef,setdef,procvardef,
  1900. classrefdef,forwarddef:
  1901. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1902. orddef:
  1903. if current_procinfo.procdef.returndef.size <> 0 then
  1904. begin
  1905. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1906. { for int64/qword }
  1907. if current_procinfo.procdef.returndef.size = 8 then
  1908. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1909. end;
  1910. else
  1911. ;
  1912. end;
  1913. end;
  1914. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1915. var
  1916. hp1,hp2 : tai;
  1917. begin
  1918. result:=false;
  1919. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1920. begin
  1921. { vmova* reg1,reg1
  1922. =>
  1923. <nop> }
  1924. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1925. begin
  1926. RemoveCurrentP(p);
  1927. result:=true;
  1928. exit;
  1929. end
  1930. else if GetNextInstruction(p,hp1) then
  1931. begin
  1932. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1933. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1934. begin
  1935. { vmova* reg1,reg2
  1936. vmova* reg2,reg3
  1937. dealloc reg2
  1938. =>
  1939. vmova* reg1,reg3 }
  1940. TransferUsedRegs(TmpUsedRegs);
  1941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1942. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1943. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1944. begin
  1945. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1946. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1947. RemoveInstruction(hp1);
  1948. result:=true;
  1949. exit;
  1950. end
  1951. { special case:
  1952. vmova* reg1,<op>
  1953. vmova* <op>,reg1
  1954. =>
  1955. vmova* reg1,<op> }
  1956. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1957. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1958. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1959. ) then
  1960. begin
  1961. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1962. RemoveInstruction(hp1);
  1963. result:=true;
  1964. exit;
  1965. end
  1966. end
  1967. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1968. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1969. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1970. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1971. ) and
  1972. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1973. begin
  1974. { vmova* reg1,reg2
  1975. vmovs* reg2,<op>
  1976. dealloc reg2
  1977. =>
  1978. vmovs* reg1,reg3 }
  1979. TransferUsedRegs(TmpUsedRegs);
  1980. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1981. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1982. begin
  1983. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1984. taicpu(p).opcode:=taicpu(hp1).opcode;
  1985. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1986. RemoveInstruction(hp1);
  1987. result:=true;
  1988. exit;
  1989. end
  1990. end;
  1991. end;
  1992. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1993. begin
  1994. if MatchInstruction(hp1,[A_VFMADDPD,
  1995. A_VFMADD132PD,
  1996. A_VFMADD132PS,
  1997. A_VFMADD132SD,
  1998. A_VFMADD132SS,
  1999. A_VFMADD213PD,
  2000. A_VFMADD213PS,
  2001. A_VFMADD213SD,
  2002. A_VFMADD213SS,
  2003. A_VFMADD231PD,
  2004. A_VFMADD231PS,
  2005. A_VFMADD231SD,
  2006. A_VFMADD231SS,
  2007. A_VFMADDSUB132PD,
  2008. A_VFMADDSUB132PS,
  2009. A_VFMADDSUB213PD,
  2010. A_VFMADDSUB213PS,
  2011. A_VFMADDSUB231PD,
  2012. A_VFMADDSUB231PS,
  2013. A_VFMSUB132PD,
  2014. A_VFMSUB132PS,
  2015. A_VFMSUB132SD,
  2016. A_VFMSUB132SS,
  2017. A_VFMSUB213PD,
  2018. A_VFMSUB213PS,
  2019. A_VFMSUB213SD,
  2020. A_VFMSUB213SS,
  2021. A_VFMSUB231PD,
  2022. A_VFMSUB231PS,
  2023. A_VFMSUB231SD,
  2024. A_VFMSUB231SS,
  2025. A_VFMSUBADD132PD,
  2026. A_VFMSUBADD132PS,
  2027. A_VFMSUBADD213PD,
  2028. A_VFMSUBADD213PS,
  2029. A_VFMSUBADD231PD,
  2030. A_VFMSUBADD231PS,
  2031. A_VFNMADD132PD,
  2032. A_VFNMADD132PS,
  2033. A_VFNMADD132SD,
  2034. A_VFNMADD132SS,
  2035. A_VFNMADD213PD,
  2036. A_VFNMADD213PS,
  2037. A_VFNMADD213SD,
  2038. A_VFNMADD213SS,
  2039. A_VFNMADD231PD,
  2040. A_VFNMADD231PS,
  2041. A_VFNMADD231SD,
  2042. A_VFNMADD231SS,
  2043. A_VFNMSUB132PD,
  2044. A_VFNMSUB132PS,
  2045. A_VFNMSUB132SD,
  2046. A_VFNMSUB132SS,
  2047. A_VFNMSUB213PD,
  2048. A_VFNMSUB213PS,
  2049. A_VFNMSUB213SD,
  2050. A_VFNMSUB213SS,
  2051. A_VFNMSUB231PD,
  2052. A_VFNMSUB231PS,
  2053. A_VFNMSUB231SD,
  2054. A_VFNMSUB231SS],[S_NO]) and
  2055. { we mix single and double opperations here because we assume that the compiler
  2056. generates vmovapd only after double operations and vmovaps only after single operations }
  2057. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2058. GetNextInstruction(hp1,hp2) and
  2059. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2060. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2061. begin
  2062. TransferUsedRegs(TmpUsedRegs);
  2063. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2064. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2065. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2066. begin
  2067. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2068. RemoveCurrentP(p);
  2069. RemoveInstruction(hp2);
  2070. end;
  2071. end
  2072. else if (hp1.typ = ait_instruction) and
  2073. GetNextInstruction(hp1, hp2) and
  2074. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2075. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2076. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2077. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2078. (((taicpu(p).opcode=A_MOVAPS) and
  2079. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2080. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2081. ((taicpu(p).opcode=A_MOVAPD) and
  2082. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2083. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2084. ) then
  2085. { change
  2086. movapX reg,reg2
  2087. addsX/subsX/... reg3, reg2
  2088. movapX reg2,reg
  2089. to
  2090. addsX/subsX/... reg3,reg
  2091. }
  2092. begin
  2093. TransferUsedRegs(TmpUsedRegs);
  2094. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2095. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2096. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2097. begin
  2098. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2099. debug_op2str(taicpu(p).opcode)+' '+
  2100. debug_op2str(taicpu(hp1).opcode)+' '+
  2101. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2102. { we cannot eliminate the first move if
  2103. the operations uses the same register for source and dest }
  2104. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2105. { Remember that hp1 is not necessarily the immediate
  2106. next instruction }
  2107. RemoveCurrentP(p);
  2108. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2109. RemoveInstruction(hp2);
  2110. result:=true;
  2111. end;
  2112. end
  2113. else if (hp1.typ = ait_instruction) and
  2114. (((taicpu(p).opcode=A_VMOVAPD) and
  2115. (taicpu(hp1).opcode=A_VCOMISD)) or
  2116. ((taicpu(p).opcode=A_VMOVAPS) and
  2117. ((taicpu(hp1).opcode=A_VCOMISS))
  2118. )
  2119. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2120. { change
  2121. movapX reg,reg1
  2122. vcomisX reg1,reg1
  2123. to
  2124. vcomisX reg,reg
  2125. }
  2126. begin
  2127. TransferUsedRegs(TmpUsedRegs);
  2128. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2129. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2130. begin
  2131. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2132. debug_op2str(taicpu(p).opcode)+' '+
  2133. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2134. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2135. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2136. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2137. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2138. RemoveCurrentP(p);
  2139. result:=true;
  2140. exit;
  2141. end;
  2142. end
  2143. end;
  2144. end;
  2145. end;
  2146. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2147. var
  2148. hp1 : tai;
  2149. begin
  2150. result:=false;
  2151. { replace
  2152. V<Op>X %mreg1,%mreg2,%mreg3
  2153. VMovX %mreg3,%mreg4
  2154. dealloc %mreg3
  2155. by
  2156. V<Op>X %mreg1,%mreg2,%mreg4
  2157. ?
  2158. }
  2159. if GetNextInstruction(p,hp1) and
  2160. { we mix single and double operations here because we assume that the compiler
  2161. generates vmovapd only after double operations and vmovaps only after single operations }
  2162. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2163. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2164. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2165. begin
  2166. TransferUsedRegs(TmpUsedRegs);
  2167. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2168. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2169. begin
  2170. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2171. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2172. RemoveInstruction(hp1);
  2173. result:=true;
  2174. end;
  2175. end;
  2176. end;
  2177. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2178. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2179. begin
  2180. Result := False;
  2181. { For safety reasons, only check for exact register matches }
  2182. { Check base register }
  2183. if (ref.base = AOldReg) then
  2184. begin
  2185. ref.base := ANewReg;
  2186. Result := True;
  2187. end;
  2188. { Check index register }
  2189. if (ref.index = AOldReg) then
  2190. begin
  2191. ref.index := ANewReg;
  2192. Result := True;
  2193. end;
  2194. end;
  2195. { Replaces all references to AOldReg in an operand to ANewReg }
  2196. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2197. var
  2198. OldSupReg, NewSupReg: TSuperRegister;
  2199. OldSubReg, NewSubReg: TSubRegister;
  2200. OldRegType: TRegisterType;
  2201. ThisOper: POper;
  2202. begin
  2203. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2204. Result := False;
  2205. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2206. InternalError(2020011801);
  2207. OldSupReg := getsupreg(AOldReg);
  2208. OldSubReg := getsubreg(AOldReg);
  2209. OldRegType := getregtype(AOldReg);
  2210. NewSupReg := getsupreg(ANewReg);
  2211. NewSubReg := getsubreg(ANewReg);
  2212. if OldRegType <> getregtype(ANewReg) then
  2213. InternalError(2020011802);
  2214. if OldSubReg <> NewSubReg then
  2215. InternalError(2020011803);
  2216. case ThisOper^.typ of
  2217. top_reg:
  2218. if (
  2219. (ThisOper^.reg = AOldReg) or
  2220. (
  2221. (OldRegType = R_INTREGISTER) and
  2222. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2223. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2224. (
  2225. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2226. {$ifndef x86_64}
  2227. and (
  2228. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2229. don't have an 8-bit representation }
  2230. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2231. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2232. )
  2233. {$endif x86_64}
  2234. )
  2235. )
  2236. ) then
  2237. begin
  2238. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2239. Result := True;
  2240. end;
  2241. top_ref:
  2242. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2243. Result := True;
  2244. else
  2245. ;
  2246. end;
  2247. end;
  2248. { Replaces all references to AOldReg in an instruction to ANewReg }
  2249. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2250. const
  2251. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2252. var
  2253. OperIdx: Integer;
  2254. begin
  2255. Result := False;
  2256. for OperIdx := 0 to p.ops - 1 do
  2257. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2258. begin
  2259. { The shift and rotate instructions can only use CL }
  2260. if not (
  2261. (OperIdx = 0) and
  2262. { This second condition just helps to avoid unnecessarily
  2263. calling MatchInstruction for 10 different opcodes }
  2264. (p.oper[0]^.reg = NR_CL) and
  2265. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2266. ) then
  2267. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2268. end
  2269. else if p.oper[OperIdx]^.typ = top_ref then
  2270. { It's okay to replace registers in references that get written to }
  2271. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2272. end;
  2273. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2274. begin
  2275. with ref^ do
  2276. Result :=
  2277. (index = NR_NO) and
  2278. (
  2279. {$ifdef x86_64}
  2280. (
  2281. (base = NR_RIP) and
  2282. (refaddr in [addr_pic, addr_pic_no_got])
  2283. ) or
  2284. {$endif x86_64}
  2285. (base = NR_STACK_POINTER_REG) or
  2286. (base = current_procinfo.framepointer)
  2287. );
  2288. end;
  2289. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2290. var
  2291. l: asizeint;
  2292. begin
  2293. Result := False;
  2294. { Should have been checked previously }
  2295. if p.opcode <> A_LEA then
  2296. InternalError(2020072501);
  2297. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2298. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2299. not(cs_opt_size in current_settings.optimizerswitches) then
  2300. exit;
  2301. with p.oper[0]^.ref^ do
  2302. begin
  2303. if (base <> p.oper[1]^.reg) or
  2304. (index <> NR_NO) or
  2305. assigned(symbol) then
  2306. exit;
  2307. l:=offset;
  2308. if (l=1) and UseIncDec then
  2309. begin
  2310. p.opcode:=A_INC;
  2311. p.loadreg(0,p.oper[1]^.reg);
  2312. p.ops:=1;
  2313. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2314. end
  2315. else if (l=-1) and UseIncDec then
  2316. begin
  2317. p.opcode:=A_DEC;
  2318. p.loadreg(0,p.oper[1]^.reg);
  2319. p.ops:=1;
  2320. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2321. end
  2322. else
  2323. begin
  2324. if (l<0) and (l<>-2147483648) then
  2325. begin
  2326. p.opcode:=A_SUB;
  2327. p.loadConst(0,-l);
  2328. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2329. end
  2330. else
  2331. begin
  2332. p.opcode:=A_ADD;
  2333. p.loadConst(0,l);
  2334. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2335. end;
  2336. end;
  2337. end;
  2338. Result := True;
  2339. end;
  2340. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2341. var
  2342. CurrentReg, ReplaceReg: TRegister;
  2343. begin
  2344. Result := False;
  2345. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2346. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2347. case hp.opcode of
  2348. A_FSTSW, A_FNSTSW,
  2349. A_IN, A_INS, A_OUT, A_OUTS,
  2350. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2351. { These routines have explicit operands, but they are restricted in
  2352. what they can be (e.g. IN and OUT can only read from AL, AX or
  2353. EAX. }
  2354. Exit;
  2355. A_IMUL:
  2356. begin
  2357. { The 1-operand version writes to implicit registers
  2358. The 2-operand version reads from the first operator, and reads
  2359. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2360. the 3-operand version reads from a register that it doesn't write to
  2361. }
  2362. case hp.ops of
  2363. 1:
  2364. if (
  2365. (
  2366. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2367. ) or
  2368. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2369. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2370. begin
  2371. Result := True;
  2372. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2373. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2374. end;
  2375. 2:
  2376. { Only modify the first parameter }
  2377. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2378. begin
  2379. Result := True;
  2380. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2381. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2382. end;
  2383. 3:
  2384. { Only modify the second parameter }
  2385. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2386. begin
  2387. Result := True;
  2388. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2389. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2390. end;
  2391. else
  2392. InternalError(2020012901);
  2393. end;
  2394. end;
  2395. else
  2396. if (hp.ops > 0) and
  2397. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2398. begin
  2399. Result := True;
  2400. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2401. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2402. end;
  2403. end;
  2404. end;
  2405. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2406. var
  2407. hp1, hp2, hp3: tai;
  2408. DoOptimisation, TempBool: Boolean;
  2409. {$ifdef x86_64}
  2410. NewConst: TCGInt;
  2411. {$endif x86_64}
  2412. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2413. begin
  2414. if taicpu(hp1).opcode = signed_movop then
  2415. begin
  2416. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2417. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2418. end
  2419. else
  2420. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2421. end;
  2422. function TryConstMerge(var p1, p2: tai): Boolean;
  2423. var
  2424. ThisRef: TReference;
  2425. begin
  2426. Result := False;
  2427. ThisRef := taicpu(p2).oper[1]^.ref^;
  2428. { Only permit writes to the stack, since we can guarantee alignment with that }
  2429. if (ThisRef.index = NR_NO) and
  2430. (
  2431. (ThisRef.base = NR_STACK_POINTER_REG) or
  2432. (ThisRef.base = current_procinfo.framepointer)
  2433. ) then
  2434. begin
  2435. case taicpu(p).opsize of
  2436. S_B:
  2437. begin
  2438. { Word writes must be on a 2-byte boundary }
  2439. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2440. begin
  2441. { Reduce offset of second reference to see if it is sequential with the first }
  2442. Dec(ThisRef.offset, 1);
  2443. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2444. begin
  2445. { Make sure the constants aren't represented as a
  2446. negative number, as these won't merge properly }
  2447. taicpu(p1).opsize := S_W;
  2448. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2449. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2450. RemoveInstruction(p2);
  2451. Result := True;
  2452. end;
  2453. end;
  2454. end;
  2455. S_W:
  2456. begin
  2457. { Longword writes must be on a 4-byte boundary }
  2458. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2459. begin
  2460. { Reduce offset of second reference to see if it is sequential with the first }
  2461. Dec(ThisRef.offset, 2);
  2462. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2463. begin
  2464. { Make sure the constants aren't represented as a
  2465. negative number, as these won't merge properly }
  2466. taicpu(p1).opsize := S_L;
  2467. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2468. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2469. RemoveInstruction(p2);
  2470. Result := True;
  2471. end;
  2472. end;
  2473. end;
  2474. {$ifdef x86_64}
  2475. S_L:
  2476. begin
  2477. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2478. see if the constants can be encoded this way. }
  2479. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2480. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2481. { Quadword writes must be on an 8-byte boundary }
  2482. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2483. begin
  2484. { Reduce offset of second reference to see if it is sequential with the first }
  2485. Dec(ThisRef.offset, 4);
  2486. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2487. begin
  2488. { Make sure the constants aren't represented as a
  2489. negative number, as these won't merge properly }
  2490. taicpu(p1).opsize := S_Q;
  2491. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2492. taicpu(p1).oper[0]^.val := NewConst;
  2493. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2494. RemoveInstruction(p2);
  2495. Result := True;
  2496. end;
  2497. end;
  2498. end;
  2499. {$endif x86_64}
  2500. else
  2501. ;
  2502. end;
  2503. end;
  2504. end;
  2505. var
  2506. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2507. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2508. NewSize: topsize;
  2509. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2510. SourceRef, TargetRef: TReference;
  2511. MovAligned, MovUnaligned: TAsmOp;
  2512. ThisRef: TReference;
  2513. JumpTracking: TLinkedList;
  2514. begin
  2515. Result:=false;
  2516. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2517. { remove mov reg1,reg1? }
  2518. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2519. then
  2520. begin
  2521. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2522. { take care of the register (de)allocs following p }
  2523. RemoveCurrentP(p, hp1);
  2524. Result:=true;
  2525. exit;
  2526. end;
  2527. { All the next optimisations require a next instruction }
  2528. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2529. Exit;
  2530. { Prevent compiler warnings }
  2531. p_TargetReg := NR_NO;
  2532. if taicpu(p).oper[1]^.typ = top_reg then
  2533. begin
  2534. { Saves on a large number of dereferences }
  2535. p_TargetReg := taicpu(p).oper[1]^.reg;
  2536. { Look for:
  2537. mov %reg1,%reg2
  2538. ??? %reg2,r/m
  2539. Change to:
  2540. mov %reg1,%reg2
  2541. ??? %reg1,r/m
  2542. }
  2543. if taicpu(p).oper[0]^.typ = top_reg then
  2544. begin
  2545. if RegReadByInstruction(p_TargetReg, hp1) and
  2546. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2547. begin
  2548. { A change has occurred, just not in p }
  2549. Result := True;
  2550. TransferUsedRegs(TmpUsedRegs);
  2551. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2552. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2553. { Just in case something didn't get modified (e.g. an
  2554. implicit register) }
  2555. not RegReadByInstruction(p_TargetReg, hp1) then
  2556. begin
  2557. { We can remove the original MOV }
  2558. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2559. RemoveCurrentp(p, hp1);
  2560. { UsedRegs got updated by RemoveCurrentp }
  2561. Result := True;
  2562. Exit;
  2563. end;
  2564. { If we know a MOV instruction has become a null operation, we might as well
  2565. get rid of it now to save time. }
  2566. if (taicpu(hp1).opcode = A_MOV) and
  2567. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2568. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2569. { Just being a register is enough to confirm it's a null operation }
  2570. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2571. begin
  2572. Result := True;
  2573. { Speed-up to reduce a pipeline stall... if we had something like...
  2574. movl %eax,%edx
  2575. movw %dx,%ax
  2576. ... the second instruction would change to movw %ax,%ax, but
  2577. given that it is now %ax that's active rather than %eax,
  2578. penalties might occur due to a partial register write, so instead,
  2579. change it to a MOVZX instruction when optimising for speed.
  2580. }
  2581. if not (cs_opt_size in current_settings.optimizerswitches) and
  2582. IsMOVZXAcceptable and
  2583. (taicpu(hp1).opsize < taicpu(p).opsize)
  2584. {$ifdef x86_64}
  2585. { operations already implicitly set the upper 64 bits to zero }
  2586. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2587. {$endif x86_64}
  2588. then
  2589. begin
  2590. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2591. case taicpu(p).opsize of
  2592. S_W:
  2593. if taicpu(hp1).opsize = S_B then
  2594. taicpu(hp1).opsize := S_BL
  2595. else
  2596. InternalError(2020012911);
  2597. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2598. case taicpu(hp1).opsize of
  2599. S_B:
  2600. taicpu(hp1).opsize := S_BL;
  2601. S_W:
  2602. taicpu(hp1).opsize := S_WL;
  2603. else
  2604. InternalError(2020012912);
  2605. end;
  2606. else
  2607. InternalError(2020012910);
  2608. end;
  2609. taicpu(hp1).opcode := A_MOVZX;
  2610. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2611. end
  2612. else
  2613. begin
  2614. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2615. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2616. RemoveInstruction(hp1);
  2617. { The instruction after what was hp1 is now the immediate next instruction,
  2618. so we can continue to make optimisations if it's present }
  2619. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2620. Exit;
  2621. hp1 := hp2;
  2622. end;
  2623. end;
  2624. end;
  2625. end;
  2626. end;
  2627. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2628. overwrites the original destination register. e.g.
  2629. movl ###,%reg2d
  2630. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2631. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2632. }
  2633. if (taicpu(p).oper[1]^.typ = top_reg) and
  2634. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2635. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2636. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2637. begin
  2638. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2639. begin
  2640. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2641. case taicpu(p).oper[0]^.typ of
  2642. top_const:
  2643. { We have something like:
  2644. movb $x, %regb
  2645. movzbl %regb,%regd
  2646. Change to:
  2647. movl $x, %regd
  2648. }
  2649. begin
  2650. case taicpu(hp1).opsize of
  2651. S_BW:
  2652. begin
  2653. convert_mov_value(A_MOVSX, $FF);
  2654. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2655. taicpu(p).opsize := S_W;
  2656. end;
  2657. S_BL:
  2658. begin
  2659. convert_mov_value(A_MOVSX, $FF);
  2660. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2661. taicpu(p).opsize := S_L;
  2662. end;
  2663. S_WL:
  2664. begin
  2665. convert_mov_value(A_MOVSX, $FFFF);
  2666. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2667. taicpu(p).opsize := S_L;
  2668. end;
  2669. {$ifdef x86_64}
  2670. S_BQ:
  2671. begin
  2672. convert_mov_value(A_MOVSX, $FF);
  2673. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2674. taicpu(p).opsize := S_Q;
  2675. end;
  2676. S_WQ:
  2677. begin
  2678. convert_mov_value(A_MOVSX, $FFFF);
  2679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2680. taicpu(p).opsize := S_Q;
  2681. end;
  2682. S_LQ:
  2683. begin
  2684. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2685. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2686. taicpu(p).opsize := S_Q;
  2687. end;
  2688. {$endif x86_64}
  2689. else
  2690. { If hp1 was a MOV instruction, it should have been
  2691. optimised already }
  2692. InternalError(2020021001);
  2693. end;
  2694. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2695. RemoveInstruction(hp1);
  2696. Result := True;
  2697. Exit;
  2698. end;
  2699. top_ref:
  2700. begin
  2701. { We have something like:
  2702. movb mem, %regb
  2703. movzbl %regb,%regd
  2704. Change to:
  2705. movzbl mem, %regd
  2706. }
  2707. ThisRef := taicpu(p).oper[0]^.ref^;
  2708. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2709. begin
  2710. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2711. taicpu(hp1).loadref(0, ThisRef);
  2712. { Make sure any registers in the references are properly tracked }
  2713. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2714. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2715. if (ThisRef.index <> NR_NO) then
  2716. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2717. RemoveCurrentP(p, hp1);
  2718. Result := True;
  2719. Exit;
  2720. end;
  2721. end;
  2722. else
  2723. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2724. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2725. Exit;
  2726. end;
  2727. end
  2728. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2729. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2730. optimised }
  2731. else
  2732. begin
  2733. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2734. RemoveCurrentP(p, hp1);
  2735. Result := True;
  2736. Exit;
  2737. end;
  2738. end;
  2739. if (taicpu(hp1).opcode = A_AND) and
  2740. (taicpu(p).oper[1]^.typ = top_reg) and
  2741. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2742. begin
  2743. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2744. begin
  2745. case taicpu(p).opsize of
  2746. S_L:
  2747. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2748. begin
  2749. { Optimize out:
  2750. mov x, %reg
  2751. and ffffffffh, %reg
  2752. }
  2753. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2754. RemoveInstruction(hp1);
  2755. Result:=true;
  2756. exit;
  2757. end;
  2758. S_Q: { TODO: Confirm if this is even possible }
  2759. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2760. begin
  2761. { Optimize out:
  2762. mov x, %reg
  2763. and ffffffffffffffffh, %reg
  2764. }
  2765. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2766. RemoveInstruction(hp1);
  2767. Result:=true;
  2768. exit;
  2769. end;
  2770. else
  2771. ;
  2772. end;
  2773. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2774. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2775. GetNextInstruction(hp1,hp2) and
  2776. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2777. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2778. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2779. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2780. GetNextInstruction(hp2,hp3) and
  2781. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2782. (taicpu(hp3).condition in [C_E,C_NE]) then
  2783. begin
  2784. TransferUsedRegs(TmpUsedRegs);
  2785. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2786. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2787. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2788. begin
  2789. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2790. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2791. taicpu(hp1).opcode:=A_TEST;
  2792. RemoveInstruction(hp2);
  2793. RemoveCurrentP(p, hp1);
  2794. Result:=true;
  2795. exit;
  2796. end;
  2797. end;
  2798. end
  2799. else if IsMOVZXAcceptable and
  2800. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2801. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2802. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2803. then
  2804. begin
  2805. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2806. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2807. case taicpu(p).opsize of
  2808. S_B:
  2809. if (taicpu(hp1).oper[0]^.val = $ff) then
  2810. begin
  2811. { Convert:
  2812. movb x, %regl movb x, %regl
  2813. andw ffh, %regw andl ffh, %regd
  2814. To:
  2815. movzbw x, %regd movzbl x, %regd
  2816. (Identical registers, just different sizes)
  2817. }
  2818. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2819. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2820. case taicpu(hp1).opsize of
  2821. S_W: NewSize := S_BW;
  2822. S_L: NewSize := S_BL;
  2823. {$ifdef x86_64}
  2824. S_Q: NewSize := S_BQ;
  2825. {$endif x86_64}
  2826. else
  2827. InternalError(2018011510);
  2828. end;
  2829. end
  2830. else
  2831. NewSize := S_NO;
  2832. S_W:
  2833. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2834. begin
  2835. { Convert:
  2836. movw x, %regw
  2837. andl ffffh, %regd
  2838. To:
  2839. movzwl x, %regd
  2840. (Identical registers, just different sizes)
  2841. }
  2842. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2843. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2844. case taicpu(hp1).opsize of
  2845. S_L: NewSize := S_WL;
  2846. {$ifdef x86_64}
  2847. S_Q: NewSize := S_WQ;
  2848. {$endif x86_64}
  2849. else
  2850. InternalError(2018011511);
  2851. end;
  2852. end
  2853. else
  2854. NewSize := S_NO;
  2855. else
  2856. NewSize := S_NO;
  2857. end;
  2858. if NewSize <> S_NO then
  2859. begin
  2860. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2861. { The actual optimization }
  2862. taicpu(p).opcode := A_MOVZX;
  2863. taicpu(p).changeopsize(NewSize);
  2864. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2865. { Safeguard if "and" is followed by a conditional command }
  2866. TransferUsedRegs(TmpUsedRegs);
  2867. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2868. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2869. begin
  2870. { At this point, the "and" command is effectively equivalent to
  2871. "test %reg,%reg". This will be handled separately by the
  2872. Peephole Optimizer. [Kit] }
  2873. DebugMsg(SPeepholeOptimization + PreMessage +
  2874. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2875. end
  2876. else
  2877. begin
  2878. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2879. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2880. RemoveInstruction(hp1);
  2881. end;
  2882. Result := True;
  2883. Exit;
  2884. end;
  2885. end;
  2886. end;
  2887. if (taicpu(hp1).opcode = A_OR) and
  2888. (taicpu(p).oper[1]^.typ = top_reg) and
  2889. MatchOperand(taicpu(p).oper[0]^, 0) and
  2890. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2891. begin
  2892. { mov 0, %reg
  2893. or ###,%reg
  2894. Change to (only if the flags are not used):
  2895. mov ###,%reg
  2896. }
  2897. TransferUsedRegs(TmpUsedRegs);
  2898. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2899. DoOptimisation := True;
  2900. { Even if the flags are used, we might be able to do the optimisation
  2901. if the conditions are predictable }
  2902. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2903. begin
  2904. { Only perform if ### = %reg (the same register) or equal to 0,
  2905. so %reg is guaranteed to still have a value of zero }
  2906. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2907. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2908. begin
  2909. hp2 := hp1;
  2910. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2911. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2912. GetNextInstruction(hp2, hp3) do
  2913. begin
  2914. { Don't continue modifying if the flags state is getting changed }
  2915. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2916. Break;
  2917. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2918. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2919. begin
  2920. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2921. begin
  2922. { Condition is always true }
  2923. case taicpu(hp3).opcode of
  2924. A_Jcc:
  2925. begin
  2926. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2927. { Check for jump shortcuts before we destroy the condition }
  2928. DoJumpOptimizations(hp3, TempBool);
  2929. MakeUnconditional(taicpu(hp3));
  2930. Result := True;
  2931. end;
  2932. A_CMOVcc:
  2933. begin
  2934. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2935. taicpu(hp3).opcode := A_MOV;
  2936. taicpu(hp3).condition := C_None;
  2937. Result := True;
  2938. end;
  2939. A_SETcc:
  2940. begin
  2941. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2942. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2943. taicpu(hp3).opcode := A_MOV;
  2944. taicpu(hp3).ops := 2;
  2945. taicpu(hp3).condition := C_None;
  2946. taicpu(hp3).opsize := S_B;
  2947. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2948. taicpu(hp3).loadconst(0, 1);
  2949. Result := True;
  2950. end;
  2951. else
  2952. InternalError(2021090701);
  2953. end;
  2954. end
  2955. 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
  2956. begin
  2957. { Condition is always false }
  2958. case taicpu(hp3).opcode of
  2959. A_Jcc:
  2960. begin
  2961. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2962. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2963. RemoveInstruction(hp3);
  2964. Result := True;
  2965. { Since hp3 was deleted, hp2 must not be updated }
  2966. Continue;
  2967. end;
  2968. A_CMOVcc:
  2969. begin
  2970. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2971. RemoveInstruction(hp3);
  2972. Result := True;
  2973. { Since hp3 was deleted, hp2 must not be updated }
  2974. Continue;
  2975. end;
  2976. A_SETcc:
  2977. begin
  2978. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2979. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2980. taicpu(hp3).opcode := A_MOV;
  2981. taicpu(hp3).ops := 2;
  2982. taicpu(hp3).condition := C_None;
  2983. taicpu(hp3).opsize := S_B;
  2984. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2985. taicpu(hp3).loadconst(0, 0);
  2986. Result := True;
  2987. end;
  2988. else
  2989. InternalError(2021090702);
  2990. end;
  2991. end
  2992. else
  2993. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2994. DoOptimisation := False;
  2995. end;
  2996. hp2 := hp3;
  2997. end;
  2998. { Flags are still in use - don't optimise }
  2999. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3000. DoOptimisation := False;
  3001. end
  3002. else
  3003. DoOptimisation := False;
  3004. end;
  3005. if DoOptimisation then
  3006. begin
  3007. {$ifdef x86_64}
  3008. { OR only supports 32-bit sign-extended constants for 64-bit
  3009. instructions, so compensate for this if the constant is
  3010. encoded as a value greater than or equal to 2^31 }
  3011. if (taicpu(hp1).opsize = S_Q) and
  3012. (taicpu(hp1).oper[0]^.typ = top_const) and
  3013. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3014. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3015. {$endif x86_64}
  3016. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3017. taicpu(hp1).opcode := A_MOV;
  3018. RemoveCurrentP(p, hp1);
  3019. Result := True;
  3020. Exit;
  3021. end;
  3022. end;
  3023. { Next instruction is also a MOV ? }
  3024. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3025. begin
  3026. if MatchOpType(taicpu(p), top_const, top_ref) and
  3027. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3028. TryConstMerge(p, hp1) then
  3029. begin
  3030. Result := True;
  3031. { In case we have four byte writes in a row, check for 2 more
  3032. right now so we don't have to wait for another iteration of
  3033. pass 1
  3034. }
  3035. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3036. case taicpu(p).opsize of
  3037. S_W:
  3038. begin
  3039. if GetNextInstruction(p, hp1) and
  3040. MatchInstruction(hp1, A_MOV, [S_B]) and
  3041. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3042. GetNextInstruction(hp1, hp2) and
  3043. MatchInstruction(hp2, A_MOV, [S_B]) and
  3044. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3045. { Try to merge the two bytes }
  3046. TryConstMerge(hp1, hp2) then
  3047. { Now try to merge the two words (hp2 will get deleted) }
  3048. TryConstMerge(p, hp1);
  3049. end;
  3050. S_L:
  3051. begin
  3052. { Though this only really benefits x86_64 and not i386, it
  3053. gets a potential optimisation done faster and hence
  3054. reduces the number of times OptPass1MOV is entered }
  3055. if GetNextInstruction(p, hp1) and
  3056. MatchInstruction(hp1, A_MOV, [S_W]) and
  3057. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3058. GetNextInstruction(hp1, hp2) and
  3059. MatchInstruction(hp2, A_MOV, [S_W]) and
  3060. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3061. { Try to merge the two words }
  3062. TryConstMerge(hp1, hp2) then
  3063. { This will always fail on i386, so don't bother
  3064. calling it unless we're doing x86_64 }
  3065. {$ifdef x86_64}
  3066. { Now try to merge the two longwords (hp2 will get deleted) }
  3067. TryConstMerge(p, hp1)
  3068. {$endif x86_64}
  3069. ;
  3070. end;
  3071. else
  3072. ;
  3073. end;
  3074. Exit;
  3075. end;
  3076. if (taicpu(p).oper[1]^.typ = top_reg) and
  3077. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3078. begin
  3079. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3080. TransferUsedRegs(TmpUsedRegs);
  3081. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3082. { we have
  3083. mov x, %treg
  3084. mov %treg, y
  3085. }
  3086. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3087. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3088. { we've got
  3089. mov x, %treg
  3090. mov %treg, y
  3091. with %treg is not used after }
  3092. case taicpu(p).oper[0]^.typ Of
  3093. { top_reg is covered by DeepMOVOpt }
  3094. top_const:
  3095. begin
  3096. { change
  3097. mov const, %treg
  3098. mov %treg, y
  3099. to
  3100. mov const, y
  3101. }
  3102. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3103. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3104. begin
  3105. if taicpu(hp1).oper[1]^.typ=top_reg then
  3106. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3107. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3108. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3109. RemoveInstruction(hp1);
  3110. Result:=true;
  3111. Exit;
  3112. end;
  3113. end;
  3114. top_ref:
  3115. case taicpu(hp1).oper[1]^.typ of
  3116. top_reg:
  3117. begin
  3118. { change
  3119. mov mem, %treg
  3120. mov %treg, %reg
  3121. to
  3122. mov mem, %reg"
  3123. }
  3124. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3125. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3127. RemoveInstruction(hp1);
  3128. Result:=true;
  3129. Exit;
  3130. end;
  3131. top_ref:
  3132. begin
  3133. {$ifdef x86_64}
  3134. { Look for the following to simplify:
  3135. mov x(mem1), %reg
  3136. mov %reg, y(mem2)
  3137. mov x+8(mem1), %reg
  3138. mov %reg, y+8(mem2)
  3139. Change to:
  3140. movdqu x(mem1), %xmmreg
  3141. movdqu %xmmreg, y(mem2)
  3142. ...but only as long as the memory blocks don't overlap
  3143. }
  3144. SourceRef := taicpu(p).oper[0]^.ref^;
  3145. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3146. if (taicpu(p).opsize = S_Q) and
  3147. GetNextInstruction(hp1, hp2) and
  3148. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3149. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3150. begin
  3151. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3152. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3153. Inc(SourceRef.offset, 8);
  3154. if UseAVX then
  3155. begin
  3156. MovAligned := A_VMOVDQA;
  3157. MovUnaligned := A_VMOVDQU;
  3158. end
  3159. else
  3160. begin
  3161. MovAligned := A_MOVDQA;
  3162. MovUnaligned := A_MOVDQU;
  3163. end;
  3164. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3165. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3166. begin
  3167. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3168. Inc(TargetRef.offset, 8);
  3169. if GetNextInstruction(hp2, hp3) and
  3170. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3171. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3172. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3173. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3174. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3175. begin
  3176. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3177. if NewMMReg <> NR_NO then
  3178. begin
  3179. { Remember that the offsets are 8 ahead }
  3180. if ((SourceRef.offset mod 16) = 8) and
  3181. (
  3182. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3183. (SourceRef.base = current_procinfo.framepointer) or
  3184. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3185. ) then
  3186. taicpu(p).opcode := MovAligned
  3187. else
  3188. taicpu(p).opcode := MovUnaligned;
  3189. taicpu(p).opsize := S_XMM;
  3190. taicpu(p).oper[1]^.reg := NewMMReg;
  3191. if ((TargetRef.offset mod 16) = 8) and
  3192. (
  3193. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3194. (TargetRef.base = current_procinfo.framepointer) or
  3195. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3196. ) then
  3197. taicpu(hp1).opcode := MovAligned
  3198. else
  3199. taicpu(hp1).opcode := MovUnaligned;
  3200. taicpu(hp1).opsize := S_XMM;
  3201. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3202. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3203. RemoveInstruction(hp2);
  3204. RemoveInstruction(hp3);
  3205. Result := True;
  3206. Exit;
  3207. end;
  3208. end;
  3209. end
  3210. else
  3211. begin
  3212. { See if the next references are 8 less rather than 8 greater }
  3213. Dec(SourceRef.offset, 16); { -8 the other way }
  3214. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3215. begin
  3216. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3217. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3218. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3219. GetNextInstruction(hp2, hp3) and
  3220. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3221. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3222. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3223. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3224. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3225. begin
  3226. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3227. if NewMMReg <> NR_NO then
  3228. begin
  3229. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3230. if ((SourceRef.offset mod 16) = 0) and
  3231. (
  3232. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3233. (SourceRef.base = current_procinfo.framepointer) or
  3234. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3235. ) then
  3236. taicpu(hp2).opcode := MovAligned
  3237. else
  3238. taicpu(hp2).opcode := MovUnaligned;
  3239. taicpu(hp2).opsize := S_XMM;
  3240. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3241. if ((TargetRef.offset mod 16) = 0) and
  3242. (
  3243. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3244. (TargetRef.base = current_procinfo.framepointer) or
  3245. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3246. ) then
  3247. taicpu(hp3).opcode := MovAligned
  3248. else
  3249. taicpu(hp3).opcode := MovUnaligned;
  3250. taicpu(hp3).opsize := S_XMM;
  3251. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3252. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3253. RemoveInstruction(hp1);
  3254. RemoveCurrentP(p, hp2);
  3255. Result := True;
  3256. Exit;
  3257. end;
  3258. end;
  3259. end;
  3260. end;
  3261. end;
  3262. {$endif x86_64}
  3263. end;
  3264. else
  3265. { The write target should be a reg or a ref }
  3266. InternalError(2021091601);
  3267. end;
  3268. else
  3269. ;
  3270. end
  3271. else
  3272. { %treg is used afterwards, but all eventualities
  3273. other than the first MOV instruction being a constant
  3274. are covered by DeepMOVOpt, so only check for that }
  3275. if (taicpu(p).oper[0]^.typ = top_const) and
  3276. (
  3277. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3278. not (cs_opt_size in current_settings.optimizerswitches) or
  3279. (taicpu(hp1).opsize = S_B)
  3280. ) and
  3281. (
  3282. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3283. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3284. ) then
  3285. begin
  3286. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3287. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3288. end;
  3289. end;
  3290. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3291. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3292. { mov reg1, mem1 or mov mem1, reg1
  3293. mov mem2, reg2 mov reg2, mem2}
  3294. begin
  3295. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3296. { mov reg1, mem1 or mov mem1, reg1
  3297. mov mem2, reg1 mov reg2, mem1}
  3298. begin
  3299. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3300. { Removes the second statement from
  3301. mov reg1, mem1/reg2
  3302. mov mem1/reg2, reg1 }
  3303. begin
  3304. if taicpu(p).oper[0]^.typ=top_reg then
  3305. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3306. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3307. RemoveInstruction(hp1);
  3308. Result:=true;
  3309. exit;
  3310. end
  3311. else
  3312. begin
  3313. TransferUsedRegs(TmpUsedRegs);
  3314. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3315. if (taicpu(p).oper[1]^.typ = top_ref) and
  3316. { mov reg1, mem1
  3317. mov mem2, reg1 }
  3318. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3319. GetNextInstruction(hp1, hp2) and
  3320. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3321. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3322. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3323. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3324. { change to
  3325. mov reg1, mem1 mov reg1, mem1
  3326. mov mem2, reg1 cmp reg1, mem2
  3327. cmp mem1, reg1
  3328. }
  3329. begin
  3330. RemoveInstruction(hp2);
  3331. taicpu(hp1).opcode := A_CMP;
  3332. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3333. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3334. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3335. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3336. end;
  3337. end;
  3338. end
  3339. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3340. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3341. begin
  3342. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3343. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3344. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3345. end
  3346. else
  3347. begin
  3348. TransferUsedRegs(TmpUsedRegs);
  3349. if GetNextInstruction(hp1, hp2) and
  3350. MatchOpType(taicpu(p),top_ref,top_reg) and
  3351. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3352. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3353. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3354. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3355. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3356. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3357. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3358. { mov mem1, %reg1
  3359. mov %reg1, mem2
  3360. mov mem2, reg2
  3361. to:
  3362. mov mem1, reg2
  3363. mov reg2, mem2}
  3364. begin
  3365. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3366. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3367. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3368. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3369. RemoveInstruction(hp2);
  3370. Result := True;
  3371. end
  3372. {$ifdef i386}
  3373. { this is enabled for i386 only, as the rules to create the reg sets below
  3374. are too complicated for x86-64, so this makes this code too error prone
  3375. on x86-64
  3376. }
  3377. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3378. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3379. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3380. { mov mem1, reg1 mov mem1, reg1
  3381. mov reg1, mem2 mov reg1, mem2
  3382. mov mem2, reg2 mov mem2, reg1
  3383. to: to:
  3384. mov mem1, reg1 mov mem1, reg1
  3385. mov mem1, reg2 mov reg1, mem2
  3386. mov reg1, mem2
  3387. or (if mem1 depends on reg1
  3388. and/or if mem2 depends on reg2)
  3389. to:
  3390. mov mem1, reg1
  3391. mov reg1, mem2
  3392. mov reg1, reg2
  3393. }
  3394. begin
  3395. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3396. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3397. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3398. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3399. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3400. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3401. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3402. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3403. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3404. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3405. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3406. end
  3407. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3408. begin
  3409. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3410. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3411. end
  3412. else
  3413. begin
  3414. RemoveInstruction(hp2);
  3415. end
  3416. {$endif i386}
  3417. ;
  3418. end;
  3419. end
  3420. { movl [mem1],reg1
  3421. movl [mem1],reg2
  3422. to
  3423. movl [mem1],reg1
  3424. movl reg1,reg2
  3425. }
  3426. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3427. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3428. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3429. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3430. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3431. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3432. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3433. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3434. begin
  3435. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3436. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3437. end;
  3438. { movl const1,[mem1]
  3439. movl [mem1],reg1
  3440. to
  3441. movl const1,reg1
  3442. movl reg1,[mem1]
  3443. }
  3444. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3445. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3446. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3447. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3448. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3449. begin
  3450. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3451. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3452. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3453. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3454. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3455. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3456. Result:=true;
  3457. exit;
  3458. end;
  3459. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3460. { Change:
  3461. movl %reg1,%reg2
  3462. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3463. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3464. To:
  3465. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3466. movl x(%reg1),%reg1
  3467. movl %reg1,%regX
  3468. }
  3469. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3470. begin
  3471. p_SourceReg := taicpu(p).oper[0]^.reg;
  3472. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3473. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3474. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3475. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3476. GetNextInstruction(hp1, hp2) and
  3477. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3478. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3479. begin
  3480. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3481. if RegInRef(p_TargetReg, SourceRef) and
  3482. { If %reg1 also appears in the second reference, then it will
  3483. not refer to the same memory block as the first reference }
  3484. not RegInRef(p_SourceReg, SourceRef) then
  3485. begin
  3486. { Check to see if the references match if %reg2 is changed to %reg1 }
  3487. if SourceRef.base = p_TargetReg then
  3488. SourceRef.base := p_SourceReg;
  3489. if SourceRef.index = p_TargetReg then
  3490. SourceRef.index := p_SourceReg;
  3491. { RefsEqual also checks to ensure both references are non-volatile }
  3492. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3493. begin
  3494. taicpu(hp2).loadreg(0, p_SourceReg);
  3495. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3496. Result := True;
  3497. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3498. begin
  3499. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3500. RemoveCurrentP(p, hp1);
  3501. Exit;
  3502. end
  3503. else
  3504. begin
  3505. { Check to see if %reg2 is no longer in use }
  3506. TransferUsedRegs(TmpUsedRegs);
  3507. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3508. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3509. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3510. begin
  3511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3512. RemoveCurrentP(p, hp1);
  3513. Exit;
  3514. end;
  3515. end;
  3516. { If we reach this point, p and hp1 weren't actually modified,
  3517. so we can do a bit more work on this pass }
  3518. end;
  3519. end;
  3520. end;
  3521. end;
  3522. end;
  3523. { search further than the next instruction for a mov (as long as it's not a jump) }
  3524. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3525. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3526. (taicpu(p).oper[1]^.typ = top_reg) and
  3527. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3528. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3529. begin
  3530. { we work with hp2 here, so hp1 can be still used later on when
  3531. checking for GetNextInstruction_p }
  3532. hp3 := hp1;
  3533. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3534. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3535. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3536. TransferUsedRegs(TmpUsedRegs);
  3537. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3538. if NotFirstIteration then
  3539. JumpTracking := TLinkedList.Create
  3540. else
  3541. JumpTracking := nil;
  3542. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3543. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3544. (hp2.typ=ait_instruction) do
  3545. begin
  3546. case taicpu(hp2).opcode of
  3547. A_POP:
  3548. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3549. begin
  3550. if not CrossJump and
  3551. not RegUsedBetween(p_TargetReg, p, hp2) then
  3552. begin
  3553. { We can remove the original MOV since the register
  3554. wasn't used between it and its popping from the stack }
  3555. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3556. RemoveCurrentp(p, hp1);
  3557. Result := True;
  3558. JumpTracking.Free;
  3559. Exit;
  3560. end;
  3561. { Can't go any further }
  3562. Break;
  3563. end;
  3564. A_MOV:
  3565. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3566. ((taicpu(p).oper[0]^.typ=top_const) or
  3567. ((taicpu(p).oper[0]^.typ=top_reg) and
  3568. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3569. )
  3570. ) then
  3571. begin
  3572. { we have
  3573. mov x, %treg
  3574. mov %treg, y
  3575. }
  3576. { We don't need to call UpdateUsedRegs for every instruction between
  3577. p and hp2 because the register we're concerned about will not
  3578. become deallocated (otherwise GetNextInstructionUsingReg would
  3579. have stopped at an earlier instruction). [Kit] }
  3580. TempRegUsed :=
  3581. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3582. RegReadByInstruction(p_TargetReg, hp3) or
  3583. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3584. case taicpu(p).oper[0]^.typ Of
  3585. top_reg:
  3586. begin
  3587. { change
  3588. mov %reg, %treg
  3589. mov %treg, y
  3590. to
  3591. mov %reg, y
  3592. }
  3593. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3594. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3595. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3596. begin
  3597. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3598. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3599. if TempRegUsed then
  3600. begin
  3601. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3602. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3603. { Set the start of the next GetNextInstructionUsingRegCond search
  3604. to start at the entry right before hp2 (which is about to be removed) }
  3605. hp3 := tai(hp2.Previous);
  3606. RemoveInstruction(hp2);
  3607. { See if there's more we can optimise }
  3608. Continue;
  3609. end
  3610. else
  3611. begin
  3612. RemoveInstruction(hp2);
  3613. { We can remove the original MOV too }
  3614. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3615. RemoveCurrentP(p, hp1);
  3616. Result:=true;
  3617. JumpTracking.Free;
  3618. Exit;
  3619. end;
  3620. end
  3621. else
  3622. begin
  3623. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3624. taicpu(hp2).loadReg(0, p_SourceReg);
  3625. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3626. { Check to see if the register also appears in the reference }
  3627. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3628. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3629. { Don't remove the first instruction if the temporary register is in use }
  3630. if not TempRegUsed and
  3631. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3632. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3633. begin
  3634. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3635. RemoveCurrentP(p, hp1);
  3636. Result:=true;
  3637. JumpTracking.Free;
  3638. Exit;
  3639. end;
  3640. { No need to set Result to True here. If there's another instruction later
  3641. on that can be optimised, it will be detected when the main Pass 1 loop
  3642. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3643. end;
  3644. end;
  3645. top_const:
  3646. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3647. begin
  3648. { change
  3649. mov const, %treg
  3650. mov %treg, y
  3651. to
  3652. mov const, y
  3653. }
  3654. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3655. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3656. begin
  3657. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3658. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3659. if TempRegUsed then
  3660. begin
  3661. { Don't remove the first instruction if the temporary register is in use }
  3662. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3663. { No need to set Result to True. If there's another instruction later on
  3664. that can be optimised, it will be detected when the main Pass 1 loop
  3665. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3666. end
  3667. else
  3668. begin
  3669. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3670. RemoveCurrentP(p, hp1);
  3671. Result:=true;
  3672. Exit;
  3673. end;
  3674. end;
  3675. end;
  3676. else
  3677. Internalerror(2019103001);
  3678. end;
  3679. end
  3680. else
  3681. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3682. begin
  3683. if not CrossJump and
  3684. not RegUsedBetween(p_TargetReg, p, hp2) and
  3685. not RegReadByInstruction(p_TargetReg, hp2) then
  3686. begin
  3687. { Register is not used before it is overwritten }
  3688. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3689. RemoveCurrentp(p, hp1);
  3690. Result := True;
  3691. Exit;
  3692. end;
  3693. if (taicpu(p).oper[0]^.typ = top_const) and
  3694. (taicpu(hp2).oper[0]^.typ = top_const) then
  3695. begin
  3696. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3697. begin
  3698. { Same value - register hasn't changed }
  3699. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3700. RemoveInstruction(hp2);
  3701. Result := True;
  3702. { See if there's more we can optimise }
  3703. Continue;
  3704. end;
  3705. end;
  3706. end;
  3707. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3708. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3709. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3710. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3711. begin
  3712. {
  3713. Change from:
  3714. mov ###, %reg
  3715. ...
  3716. movs/z %reg,%reg (Same register, just different sizes)
  3717. To:
  3718. movs/z ###, %reg (Longer version)
  3719. ...
  3720. (remove)
  3721. }
  3722. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3723. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3724. { Keep the first instruction as mov if ### is a constant }
  3725. if taicpu(p).oper[0]^.typ = top_const then
  3726. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3727. else
  3728. begin
  3729. taicpu(p).opcode := taicpu(hp2).opcode;
  3730. taicpu(p).opsize := taicpu(hp2).opsize;
  3731. end;
  3732. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3733. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3734. RemoveInstruction(hp2);
  3735. Result := True;
  3736. JumpTracking.Free;
  3737. Exit;
  3738. end;
  3739. else
  3740. { Move down to the MatchOpType if-block below };
  3741. end;
  3742. { Also catches MOV/S/Z instructions that aren't modified }
  3743. if taicpu(p).oper[0]^.typ = top_reg then
  3744. begin
  3745. p_SourceReg := taicpu(p).oper[0]^.reg;
  3746. if
  3747. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3748. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3749. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3750. begin
  3751. Result := True;
  3752. { Just in case something didn't get modified (e.g. an
  3753. implicit register). Also, if it does read from this
  3754. register, then there's no longer an advantage to
  3755. changing the register on subsequent instructions.}
  3756. if not RegReadByInstruction(p_TargetReg, hp2) then
  3757. begin
  3758. { If a conditional jump was crossed, do not delete
  3759. the original MOV no matter what }
  3760. if not CrossJump and
  3761. { RegEndOfLife returns True if the register is
  3762. deallocated before the next instruction or has
  3763. been loaded with a new value }
  3764. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3765. begin
  3766. { We can remove the original MOV }
  3767. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3768. RemoveCurrentp(p, hp1);
  3769. JumpTracking.Free;
  3770. Result := True;
  3771. Exit;
  3772. end;
  3773. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3774. begin
  3775. { See if there's more we can optimise }
  3776. hp3 := hp2;
  3777. Continue;
  3778. end;
  3779. end;
  3780. end;
  3781. end;
  3782. { Break out of the while loop under normal circumstances }
  3783. Break;
  3784. end;
  3785. JumpTracking.Free;
  3786. end;
  3787. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3788. (taicpu(p).oper[1]^.typ = top_reg) and
  3789. (taicpu(p).opsize = S_L) and
  3790. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3791. (hp2.typ = ait_instruction) and
  3792. (taicpu(hp2).opcode = A_AND) and
  3793. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3794. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3795. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3796. ) then
  3797. begin
  3798. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3799. begin
  3800. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3801. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3802. begin
  3803. { Optimize out:
  3804. mov x, %reg
  3805. and ffffffffh, %reg
  3806. }
  3807. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3808. RemoveInstruction(hp2);
  3809. Result:=true;
  3810. exit;
  3811. end;
  3812. end;
  3813. end;
  3814. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3815. x >= RetOffset) as it doesn't do anything (it writes either to a
  3816. parameter or to the temporary storage room for the function
  3817. result)
  3818. }
  3819. if IsExitCode(hp1) and
  3820. (taicpu(p).oper[1]^.typ = top_ref) and
  3821. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3822. (
  3823. (
  3824. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3825. not (
  3826. assigned(current_procinfo.procdef.funcretsym) and
  3827. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3828. )
  3829. ) or
  3830. { Also discard writes to the stack that are below the base pointer,
  3831. as this is temporary storage rather than a function result on the
  3832. stack, say. }
  3833. (
  3834. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3835. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3836. )
  3837. ) then
  3838. begin
  3839. RemoveCurrentp(p, hp1);
  3840. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3841. RemoveLastDeallocForFuncRes(p);
  3842. Result:=true;
  3843. exit;
  3844. end;
  3845. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3846. begin
  3847. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3848. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3849. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3850. begin
  3851. { change
  3852. mov reg1, mem1
  3853. test/cmp x, mem1
  3854. to
  3855. mov reg1, mem1
  3856. test/cmp x, reg1
  3857. }
  3858. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3859. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3860. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3861. Result := True;
  3862. Exit;
  3863. end;
  3864. if DoMovCmpMemOpt(p, hp1, True) then
  3865. begin
  3866. Result := True;
  3867. Exit;
  3868. end;
  3869. end;
  3870. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3871. { If the flags register is in use, don't change the instruction to an
  3872. ADD otherwise this will scramble the flags. [Kit] }
  3873. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3874. begin
  3875. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3876. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3877. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3878. ) or
  3879. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3880. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3881. )
  3882. ) then
  3883. { mov reg1,ref
  3884. lea reg2,[reg1,reg2]
  3885. to
  3886. add reg2,ref}
  3887. begin
  3888. TransferUsedRegs(TmpUsedRegs);
  3889. { reg1 may not be used afterwards }
  3890. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3891. begin
  3892. Taicpu(hp1).opcode:=A_ADD;
  3893. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3894. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3895. RemoveCurrentp(p, hp1);
  3896. result:=true;
  3897. exit;
  3898. end;
  3899. end;
  3900. { If the LEA instruction can be converted into an arithmetic instruction,
  3901. it may be possible to then fold it in the next optimisation, otherwise
  3902. there's nothing more that can be optimised here. }
  3903. if not ConvertLEA(taicpu(hp1)) then
  3904. Exit;
  3905. end;
  3906. if (taicpu(p).oper[1]^.typ = top_reg) and
  3907. (hp1.typ = ait_instruction) and
  3908. GetNextInstruction(hp1, hp2) and
  3909. MatchInstruction(hp2,A_MOV,[]) and
  3910. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3911. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3912. (
  3913. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3914. {$ifdef x86_64}
  3915. or
  3916. (
  3917. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3918. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3919. )
  3920. {$endif x86_64}
  3921. ) then
  3922. begin
  3923. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3924. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3925. { change movsX/movzX reg/ref, reg2
  3926. add/sub/or/... reg3/$const, reg2
  3927. mov reg2 reg/ref
  3928. dealloc reg2
  3929. to
  3930. add/sub/or/... reg3/$const, reg/ref }
  3931. begin
  3932. TransferUsedRegs(TmpUsedRegs);
  3933. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3934. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3935. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3936. begin
  3937. { by example:
  3938. movswl %si,%eax movswl %si,%eax p
  3939. decl %eax addl %edx,%eax hp1
  3940. movw %ax,%si movw %ax,%si hp2
  3941. ->
  3942. movswl %si,%eax movswl %si,%eax p
  3943. decw %eax addw %edx,%eax hp1
  3944. movw %ax,%si movw %ax,%si hp2
  3945. }
  3946. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3947. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3948. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3949. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3950. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3951. {
  3952. ->
  3953. movswl %si,%eax movswl %si,%eax p
  3954. decw %si addw %dx,%si hp1
  3955. movw %ax,%si movw %ax,%si hp2
  3956. }
  3957. case taicpu(hp1).ops of
  3958. 1:
  3959. begin
  3960. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3961. if taicpu(hp1).oper[0]^.typ=top_reg then
  3962. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3963. end;
  3964. 2:
  3965. begin
  3966. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3967. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3968. (taicpu(hp1).opcode<>A_SHL) and
  3969. (taicpu(hp1).opcode<>A_SHR) and
  3970. (taicpu(hp1).opcode<>A_SAR) then
  3971. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3972. end;
  3973. else
  3974. internalerror(2008042701);
  3975. end;
  3976. {
  3977. ->
  3978. decw %si addw %dx,%si p
  3979. }
  3980. RemoveInstruction(hp2);
  3981. RemoveCurrentP(p, hp1);
  3982. Result:=True;
  3983. Exit;
  3984. end;
  3985. end;
  3986. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3987. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3988. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3989. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3990. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3991. )
  3992. {$ifdef i386}
  3993. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3994. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3995. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3996. {$endif i386}
  3997. then
  3998. { change movsX/movzX reg/ref, reg2
  3999. add/sub/or/... regX/$const, reg2
  4000. mov reg2, reg3
  4001. dealloc reg2
  4002. to
  4003. movsX/movzX reg/ref, reg3
  4004. add/sub/or/... reg3/$const, reg3
  4005. }
  4006. begin
  4007. TransferUsedRegs(TmpUsedRegs);
  4008. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4009. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4010. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4011. begin
  4012. { by example:
  4013. movswl %si,%eax movswl %si,%eax p
  4014. decl %eax addl %edx,%eax hp1
  4015. movw %ax,%si movw %ax,%si hp2
  4016. ->
  4017. movswl %si,%eax movswl %si,%eax p
  4018. decw %eax addw %edx,%eax hp1
  4019. movw %ax,%si movw %ax,%si hp2
  4020. }
  4021. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4022. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4023. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4024. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4025. { limit size of constants as well to avoid assembler errors, but
  4026. check opsize to avoid overflow when left shifting the 1 }
  4027. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4028. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4029. {$ifdef x86_64}
  4030. { Be careful of, for example:
  4031. movl %reg1,%reg2
  4032. addl %reg3,%reg2
  4033. movq %reg2,%reg4
  4034. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4035. }
  4036. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4037. begin
  4038. taicpu(hp2).changeopsize(S_L);
  4039. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4040. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4041. end;
  4042. {$endif x86_64}
  4043. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4044. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4045. if taicpu(p).oper[0]^.typ=top_reg then
  4046. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4047. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4048. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4049. {
  4050. ->
  4051. movswl %si,%eax movswl %si,%eax p
  4052. decw %si addw %dx,%si hp1
  4053. movw %ax,%si movw %ax,%si hp2
  4054. }
  4055. case taicpu(hp1).ops of
  4056. 1:
  4057. begin
  4058. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4059. if taicpu(hp1).oper[0]^.typ=top_reg then
  4060. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4061. end;
  4062. 2:
  4063. begin
  4064. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4065. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4066. (taicpu(hp1).opcode<>A_SHL) and
  4067. (taicpu(hp1).opcode<>A_SHR) and
  4068. (taicpu(hp1).opcode<>A_SAR) then
  4069. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4070. end;
  4071. else
  4072. internalerror(2018111801);
  4073. end;
  4074. {
  4075. ->
  4076. decw %si addw %dx,%si p
  4077. }
  4078. RemoveInstruction(hp2);
  4079. end;
  4080. end;
  4081. end;
  4082. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4083. GetNextInstruction(hp1, hp2) and
  4084. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4085. MatchOperand(Taicpu(p).oper[0]^,0) and
  4086. (Taicpu(p).oper[1]^.typ = top_reg) and
  4087. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4088. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4089. { mov reg1,0
  4090. bts reg1,operand1 --> mov reg1,operand2
  4091. or reg1,operand2 bts reg1,operand1}
  4092. begin
  4093. Taicpu(hp2).opcode:=A_MOV;
  4094. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4095. asml.remove(hp1);
  4096. insertllitem(hp2,hp2.next,hp1);
  4097. RemoveCurrentp(p, hp1);
  4098. Result:=true;
  4099. exit;
  4100. end;
  4101. {
  4102. mov ref,reg0
  4103. <op> reg0,reg1
  4104. dealloc reg0
  4105. to
  4106. <op> ref,reg1
  4107. }
  4108. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4110. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4111. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4112. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4113. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4114. begin
  4115. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4116. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4117. RemoveCurrentp(p, hp1);
  4118. Result:=true;
  4119. exit;
  4120. end;
  4121. {$ifdef x86_64}
  4122. { Convert:
  4123. movq x(ref),%reg64
  4124. shrq y,%reg64
  4125. To:
  4126. movl x+4(ref),%reg32
  4127. shrl y-32,%reg32 (Remove if y = 32)
  4128. }
  4129. if (taicpu(p).opsize = S_Q) and
  4130. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4131. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  4132. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  4133. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4134. (taicpu(hp1).oper[0]^.val >= 32) and
  4135. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4136. begin
  4137. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4138. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4139. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4140. { Convert to 32-bit }
  4141. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4142. taicpu(p).opsize := S_L;
  4143. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4144. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4145. if (taicpu(hp1).oper[0]^.val = 32) then
  4146. begin
  4147. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4148. RemoveInstruction(hp1);
  4149. end
  4150. else
  4151. begin
  4152. { This will potentially open up more arithmetic operations since
  4153. the peephole optimizer now has a big hint that only the lower
  4154. 32 bits are currently in use (and opcodes are smaller in size) }
  4155. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4156. taicpu(hp1).opsize := S_L;
  4157. Dec(taicpu(hp1).oper[0]^.val, 32);
  4158. DebugMsg(SPeepholeOptimization + PreMessage +
  4159. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4160. end;
  4161. Result := True;
  4162. Exit;
  4163. end;
  4164. {$endif x86_64}
  4165. { Backward optimisation. If we have:
  4166. func. %reg1,%reg2
  4167. mov %reg2,%reg3
  4168. (dealloc %reg2)
  4169. Change to:
  4170. func. %reg1,%reg3 (see comment below for what a valid func. is)
  4171. }
  4172. if MatchOpType(taicpu(p), top_reg, top_reg) then
  4173. begin
  4174. p_SourceReg := taicpu(p).oper[0]^.reg;
  4175. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4176. TransferUsedRegs(TmpUsedRegs);
  4177. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  4178. GetLastInstruction(p, hp2) and
  4179. (hp2.typ = ait_instruction) and
  4180. { Have to make sure it's an instruction that only reads from
  4181. operand 1 and only writes (not reads or modifies) from operand 2;
  4182. in essence, a one-operand pure function such as BSR or POPCNT }
  4183. (taicpu(hp2).ops = 2) and
  4184. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  4185. (taicpu(hp2).oper[1]^.typ = top_reg) and
  4186. (taicpu(hp2).oper[1]^.reg = p_SourceReg) then
  4187. begin
  4188. case taicpu(hp2).opcode of
  4189. A_FSTSW, A_FNSTSW,
  4190. A_IN, A_INS, A_OUT, A_OUTS,
  4191. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  4192. { These routines have explicit operands, but they are restricted in
  4193. what they can be (e.g. IN and OUT can only read from AL, AX or
  4194. EAX. }
  4195. ;
  4196. else
  4197. begin
  4198. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  4199. taicpu(hp2).oper[1]^.reg := p_TargetReg;
  4200. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  4201. RemoveCurrentp(p, hp1);
  4202. Result := True;
  4203. Exit;
  4204. end;
  4205. end;
  4206. end;
  4207. end;
  4208. end;
  4209. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4210. var
  4211. hp1 : tai;
  4212. begin
  4213. Result:=false;
  4214. if taicpu(p).ops <> 2 then
  4215. exit;
  4216. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4217. GetNextInstruction(p,hp1) then
  4218. begin
  4219. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4220. (taicpu(hp1).ops = 2) then
  4221. begin
  4222. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4223. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4224. { movXX reg1, mem1 or movXX mem1, reg1
  4225. movXX mem2, reg2 movXX reg2, mem2}
  4226. begin
  4227. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4228. { movXX reg1, mem1 or movXX mem1, reg1
  4229. movXX mem2, reg1 movXX reg2, mem1}
  4230. begin
  4231. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4232. begin
  4233. { Removes the second statement from
  4234. movXX reg1, mem1/reg2
  4235. movXX mem1/reg2, reg1
  4236. }
  4237. if taicpu(p).oper[0]^.typ=top_reg then
  4238. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4239. { Removes the second statement from
  4240. movXX mem1/reg1, reg2
  4241. movXX reg2, mem1/reg1
  4242. }
  4243. if (taicpu(p).oper[1]^.typ=top_reg) and
  4244. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4245. begin
  4246. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4247. RemoveInstruction(hp1);
  4248. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4249. Result:=true;
  4250. exit;
  4251. end
  4252. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4253. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4254. begin
  4255. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4256. RemoveInstruction(hp1);
  4257. Result:=true;
  4258. exit;
  4259. end;
  4260. end
  4261. end;
  4262. end;
  4263. end;
  4264. end;
  4265. end;
  4266. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4267. var
  4268. hp1 : tai;
  4269. begin
  4270. result:=false;
  4271. { replace
  4272. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4273. MovX %mreg2,%mreg1
  4274. dealloc %mreg2
  4275. by
  4276. <Op>X %mreg2,%mreg1
  4277. ?
  4278. }
  4279. if GetNextInstruction(p,hp1) and
  4280. { we mix single and double opperations here because we assume that the compiler
  4281. generates vmovapd only after double operations and vmovaps only after single operations }
  4282. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4283. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4284. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4285. (taicpu(p).oper[0]^.typ=top_reg) then
  4286. begin
  4287. TransferUsedRegs(TmpUsedRegs);
  4288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4289. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4290. begin
  4291. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4292. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4293. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4294. RemoveInstruction(hp1);
  4295. result:=true;
  4296. end;
  4297. end;
  4298. end;
  4299. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4300. var
  4301. hp1, p_label, p_dist, hp1_dist: tai;
  4302. JumpLabel, JumpLabel_dist: TAsmLabel;
  4303. FirstValue, SecondValue: TCGInt;
  4304. begin
  4305. Result := False;
  4306. if (taicpu(p).oper[0]^.typ = top_const) and
  4307. (taicpu(p).oper[0]^.val <> -1) then
  4308. begin
  4309. { Convert unsigned maximum constants to -1 to aid optimisation }
  4310. case taicpu(p).opsize of
  4311. S_B:
  4312. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4313. begin
  4314. taicpu(p).oper[0]^.val := -1;
  4315. Result := True;
  4316. Exit;
  4317. end;
  4318. S_W:
  4319. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4320. begin
  4321. taicpu(p).oper[0]^.val := -1;
  4322. Result := True;
  4323. Exit;
  4324. end;
  4325. S_L:
  4326. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4327. begin
  4328. taicpu(p).oper[0]^.val := -1;
  4329. Result := True;
  4330. Exit;
  4331. end;
  4332. {$ifdef x86_64}
  4333. S_Q:
  4334. { Storing anything greater than $7FFFFFFF is not possible so do
  4335. nothing };
  4336. {$endif x86_64}
  4337. else
  4338. InternalError(2021121001);
  4339. end;
  4340. end;
  4341. if GetNextInstruction(p, hp1) and
  4342. TrySwapMovCmp(p, hp1) then
  4343. begin
  4344. Result := True;
  4345. Exit;
  4346. end;
  4347. { Search for:
  4348. test $x,(reg/ref)
  4349. jne @lbl1
  4350. test $y,(reg/ref) (same register or reference)
  4351. jne @lbl1
  4352. Change to:
  4353. test $(x or y),(reg/ref)
  4354. jne @lbl1
  4355. (Note, this doesn't work with je instead of jne)
  4356. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4357. Also search for:
  4358. test $x,(reg/ref)
  4359. je @lbl1
  4360. test $y,(reg/ref)
  4361. je/jne @lbl2
  4362. If (x or y) = x, then the second jump is deterministic
  4363. }
  4364. if (
  4365. (
  4366. (taicpu(p).oper[0]^.typ = top_const) or
  4367. (
  4368. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4369. (taicpu(p).oper[0]^.typ = top_reg) and
  4370. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4371. )
  4372. ) and
  4373. MatchInstruction(hp1, A_JCC, [])
  4374. ) then
  4375. begin
  4376. if (taicpu(p).oper[0]^.typ = top_reg) and
  4377. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4378. FirstValue := -1
  4379. else
  4380. FirstValue := taicpu(p).oper[0]^.val;
  4381. { If we have several test/jne's in a row, it might be the case that
  4382. the second label doesn't go to the same location, but the one
  4383. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4384. so accommodate for this with a while loop.
  4385. }
  4386. hp1_dist := hp1;
  4387. if GetNextInstruction(hp1, p_dist) and
  4388. (p_dist.typ = ait_instruction) and
  4389. (
  4390. (
  4391. (taicpu(p_dist).opcode = A_TEST) and
  4392. (
  4393. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4394. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4395. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4396. )
  4397. ) or
  4398. (
  4399. { cmp 0,%reg = test %reg,%reg }
  4400. (taicpu(p_dist).opcode = A_CMP) and
  4401. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4402. )
  4403. ) and
  4404. { Make sure the destination operands are actually the same }
  4405. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4406. GetNextInstruction(p_dist, hp1_dist) and
  4407. MatchInstruction(hp1_dist, A_JCC, []) then
  4408. begin
  4409. if
  4410. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4411. (
  4412. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4413. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4414. ) then
  4415. SecondValue := -1
  4416. else
  4417. SecondValue := taicpu(p_dist).oper[0]^.val;
  4418. { If both of the TEST constants are identical, delete the second
  4419. TEST that is unnecessary. }
  4420. if (FirstValue = SecondValue) then
  4421. begin
  4422. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4423. RemoveInstruction(p_dist);
  4424. { Don't let the flags register become deallocated and reallocated between the jumps }
  4425. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4426. Result := True;
  4427. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4428. begin
  4429. { Since the second jump's condition is a subset of the first, we
  4430. know it will never branch because the first jump dominates it.
  4431. Get it out of the way now rather than wait for the jump
  4432. optimisations for a speed boost. }
  4433. if IsJumpToLabel(taicpu(hp1_dist)) then
  4434. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4435. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4436. RemoveInstruction(hp1_dist);
  4437. end
  4438. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4439. begin
  4440. { If the inverse of the first condition is a subset of the second,
  4441. the second one will definitely branch if the first one doesn't }
  4442. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4443. MakeUnconditional(taicpu(hp1_dist));
  4444. RemoveDeadCodeAfterJump(hp1_dist);
  4445. end;
  4446. Exit;
  4447. end;
  4448. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4449. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4450. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4451. then the second jump will never branch, so it can also be
  4452. removed regardless of where it goes }
  4453. (
  4454. (FirstValue = -1) or
  4455. (SecondValue = -1) or
  4456. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4457. ) then
  4458. begin
  4459. { Same jump location... can be a register since nothing's changed }
  4460. { If any of the entries are equivalent to test %reg,%reg, then the
  4461. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4462. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4463. if IsJumpToLabel(taicpu(hp1_dist)) then
  4464. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4465. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4466. RemoveInstruction(hp1_dist);
  4467. { Only remove the second test if no jumps or other conditional instructions follow }
  4468. TransferUsedRegs(TmpUsedRegs);
  4469. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4470. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4471. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4472. RemoveInstruction(p_dist);
  4473. Result := True;
  4474. Exit;
  4475. end;
  4476. end;
  4477. end;
  4478. { Search for:
  4479. test %reg,%reg
  4480. j(c1) @lbl1
  4481. ...
  4482. @lbl:
  4483. test %reg,%reg (same register)
  4484. j(c2) @lbl2
  4485. If c2 is a subset of c1, change to:
  4486. test %reg,%reg
  4487. j(c1) @lbl2
  4488. (@lbl1 may become a dead label as a result)
  4489. }
  4490. if (taicpu(p).oper[1]^.typ = top_reg) and
  4491. (taicpu(p).oper[0]^.typ = top_reg) and
  4492. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4493. MatchInstruction(hp1, A_JCC, []) and
  4494. IsJumpToLabel(taicpu(hp1)) then
  4495. begin
  4496. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4497. p_label := nil;
  4498. if Assigned(JumpLabel) then
  4499. p_label := getlabelwithsym(JumpLabel);
  4500. if Assigned(p_label) and
  4501. GetNextInstruction(p_label, p_dist) and
  4502. MatchInstruction(p_dist, A_TEST, []) and
  4503. { It's fine if the second test uses smaller sub-registers }
  4504. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4505. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4506. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4507. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4508. GetNextInstruction(p_dist, hp1_dist) and
  4509. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4510. begin
  4511. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4512. if JumpLabel = JumpLabel_dist then
  4513. { This is an infinite loop }
  4514. Exit;
  4515. { Best optimisation when the first condition is a subset (or equal) of the second }
  4516. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4517. begin
  4518. { Any registers used here will already be allocated }
  4519. if Assigned(JumpLabel) then
  4520. JumpLabel.DecRefs;
  4521. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4522. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4523. Result := True;
  4524. Exit;
  4525. end;
  4526. end;
  4527. end;
  4528. end;
  4529. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4530. var
  4531. hp1, hp2: tai;
  4532. ActiveReg: TRegister;
  4533. OldOffset: asizeint;
  4534. ThisConst: TCGInt;
  4535. function RegDeallocated: Boolean;
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4540. end;
  4541. begin
  4542. result:=false;
  4543. hp1 := nil;
  4544. { replace
  4545. addX const,%reg1
  4546. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4547. dealloc %reg1
  4548. by
  4549. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4550. }
  4551. if MatchOpType(taicpu(p),top_const,top_reg) then
  4552. begin
  4553. ActiveReg := taicpu(p).oper[1]^.reg;
  4554. { Ensures the entire register was updated }
  4555. if (taicpu(p).opsize >= S_L) and
  4556. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4557. MatchInstruction(hp1,A_LEA,[]) and
  4558. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4559. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4560. (
  4561. { Cover the case where the register in the reference is also the destination register }
  4562. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4563. (
  4564. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4565. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4566. RegDeallocated
  4567. )
  4568. ) then
  4569. begin
  4570. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4571. {$push}
  4572. {$R-}{$Q-}
  4573. { Explicitly disable overflow checking for these offset calculation
  4574. as those do not matter for the final result }
  4575. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4576. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4577. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4579. {$pop}
  4580. {$ifdef x86_64}
  4581. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4582. begin
  4583. { Overflow; abort }
  4584. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4585. end
  4586. else
  4587. {$endif x86_64}
  4588. begin
  4589. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4590. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4591. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4592. RemoveCurrentP(p, hp1)
  4593. else
  4594. RemoveCurrentP(p);
  4595. result:=true;
  4596. Exit;
  4597. end;
  4598. end;
  4599. if (
  4600. { Save calling GetNextInstructionUsingReg again }
  4601. Assigned(hp1) or
  4602. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4603. ) and
  4604. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4605. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4606. begin
  4607. if taicpu(hp1).oper[0]^.typ = top_const then
  4608. begin
  4609. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4610. if taicpu(hp1).opcode = A_ADD then
  4611. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4612. else
  4613. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4614. Result := True;
  4615. { Handle any overflows }
  4616. case taicpu(p).opsize of
  4617. S_B:
  4618. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4619. S_W:
  4620. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4621. S_L:
  4622. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4623. {$ifdef x86_64}
  4624. S_Q:
  4625. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4626. { Overflow; abort }
  4627. Result := False
  4628. else
  4629. taicpu(p).oper[0]^.val := ThisConst;
  4630. {$endif x86_64}
  4631. else
  4632. InternalError(2021102610);
  4633. end;
  4634. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4635. if Result then
  4636. begin
  4637. if (taicpu(p).oper[0]^.val < 0) and
  4638. (
  4639. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4640. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4641. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4642. ) then
  4643. begin
  4644. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4645. taicpu(p).opcode := A_SUB;
  4646. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4647. end
  4648. else
  4649. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4650. RemoveInstruction(hp1);
  4651. end;
  4652. end
  4653. else
  4654. begin
  4655. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4656. TransferUsedRegs(TmpUsedRegs);
  4657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4658. hp2 := p;
  4659. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4660. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4661. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4662. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4663. begin
  4664. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4665. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4666. Asml.Remove(p);
  4667. Asml.InsertAfter(p, hp1);
  4668. p := hp1;
  4669. Result := True;
  4670. end;
  4671. end;
  4672. end;
  4673. end;
  4674. end;
  4675. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4676. var
  4677. hp1: tai;
  4678. ref: Integer;
  4679. saveref: treference;
  4680. Multiple: TCGInt;
  4681. Adjacent: Boolean;
  4682. begin
  4683. Result:=false;
  4684. { play save and throw an error if LEA uses a seg register prefix,
  4685. this is most likely an error somewhere else }
  4686. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4687. internalerror(2022022001);
  4688. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4689. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4690. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4691. (
  4692. { do not mess with leas accessing the stack pointer
  4693. unless it's a null operation }
  4694. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4695. (
  4696. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4697. (taicpu(p).oper[0]^.ref^.offset = 0)
  4698. )
  4699. ) and
  4700. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4701. begin
  4702. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4703. begin
  4704. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4705. begin
  4706. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4707. taicpu(p).oper[1]^.reg);
  4708. InsertLLItem(p.previous,p.next, hp1);
  4709. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4710. p.free;
  4711. p:=hp1;
  4712. end
  4713. else
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4716. RemoveCurrentP(p);
  4717. end;
  4718. Result:=true;
  4719. exit;
  4720. end
  4721. else if (
  4722. { continue to use lea to adjust the stack pointer,
  4723. it is the recommended way, but only if not optimizing for size }
  4724. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4725. (cs_opt_size in current_settings.optimizerswitches)
  4726. ) and
  4727. { If the flags register is in use, don't change the instruction
  4728. to an ADD otherwise this will scramble the flags. [Kit] }
  4729. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4730. ConvertLEA(taicpu(p)) then
  4731. begin
  4732. Result:=true;
  4733. exit;
  4734. end;
  4735. end;
  4736. { Don't optimise if the stack or frame pointer is the destination register }
  4737. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  4738. Exit;
  4739. if GetNextInstruction(p,hp1) and
  4740. (hp1.typ=ait_instruction) then
  4741. begin
  4742. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  4745. begin
  4746. TransferUsedRegs(TmpUsedRegs);
  4747. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4748. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4749. begin
  4750. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4751. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4752. RemoveInstruction(hp1);
  4753. result:=true;
  4754. exit;
  4755. end;
  4756. end;
  4757. { changes
  4758. lea <ref1>, reg1
  4759. <op> ...,<ref. with reg1>,...
  4760. to
  4761. <op> ...,<ref1>,... }
  4762. { find a reference which uses reg1 }
  4763. 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
  4764. ref:=0
  4765. 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
  4766. ref:=1
  4767. else
  4768. ref:=-1;
  4769. if (ref<>-1) and
  4770. { reg1 must be either the base or the index }
  4771. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4772. begin
  4773. { reg1 can be removed from the reference }
  4774. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4775. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4776. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4777. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4778. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4779. else
  4780. Internalerror(2019111201);
  4781. { check if the can insert all data of the lea into the second instruction }
  4782. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4783. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4784. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4785. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4786. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4787. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4788. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4789. {$ifdef x86_64}
  4790. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4791. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4792. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4793. )
  4794. {$endif x86_64}
  4795. then
  4796. begin
  4797. { reg1 might not used by the second instruction after it is remove from the reference }
  4798. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4799. begin
  4800. TransferUsedRegs(TmpUsedRegs);
  4801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4802. { reg1 is not updated so it might not be used afterwards }
  4803. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4804. begin
  4805. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4806. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4807. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4808. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4809. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4810. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4811. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4812. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4813. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4814. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4815. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4816. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4817. RemoveCurrentP(p, hp1);
  4818. result:=true;
  4819. exit;
  4820. end
  4821. end;
  4822. end;
  4823. { recover }
  4824. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4825. end;
  4826. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  4827. if Adjacent or
  4828. { Check further ahead (up to 2 instructions ahead for -O2) }
  4829. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  4830. begin
  4831. { Check common LEA/LEA conditions }
  4832. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4833. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4834. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4835. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4836. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4837. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4838. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4839. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4840. (
  4841. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  4842. calling it (since it calls GetNextInstruction) }
  4843. Adjacent or
  4844. (
  4845. (
  4846. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4847. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4848. ) and (
  4849. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4850. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4851. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4852. )
  4853. )
  4854. ) then
  4855. begin
  4856. { changes
  4857. lea (regX,scale), reg1
  4858. lea offset(reg1,reg1), reg1
  4859. to
  4860. lea offset(regX,scale*2), reg1
  4861. and
  4862. lea (regX,scale1), reg1
  4863. lea offset(reg1,scale2), reg1
  4864. to
  4865. lea offset(regX,scale1*scale2), reg1
  4866. ... so long as the final scale does not exceed 8
  4867. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4868. }
  4869. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  4870. (taicpu(p).oper[0]^.ref^.offset = 0) and
  4871. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4872. (
  4873. (
  4874. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4875. ) or (
  4876. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4877. (
  4878. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4879. (
  4880. { RegUsedBetween always returns False if p and hp1 are adjacent }
  4881. Adjacent or
  4882. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4883. )
  4884. )
  4885. )
  4886. ) and (
  4887. (
  4888. { lea (reg1,scale2), reg1 variant }
  4889. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4890. (
  4891. (
  4892. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4893. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4894. ) or (
  4895. { lea (regX,regX), reg1 variant }
  4896. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4897. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4898. )
  4899. )
  4900. ) or (
  4901. { lea (reg1,reg1), reg1 variant }
  4902. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4903. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4904. )
  4905. ) then
  4906. begin
  4907. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4908. { Make everything homogeneous to make calculations easier }
  4909. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4910. begin
  4911. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4912. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4913. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4914. else
  4915. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4916. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4917. end;
  4918. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4919. begin
  4920. { Just to prevent miscalculations }
  4921. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4922. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4923. else
  4924. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4925. end
  4926. else
  4927. begin
  4928. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4929. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4930. end;
  4931. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4932. RemoveCurrentP(p);
  4933. result:=true;
  4934. exit;
  4935. end
  4936. { changes
  4937. lea offset1(regX), reg1
  4938. lea offset2(reg1), reg1
  4939. to
  4940. lea offset1+offset2(regX), reg1 }
  4941. else if
  4942. (
  4943. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4944. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4945. ) or (
  4946. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4947. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4948. (
  4949. (
  4950. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4951. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4952. ) or (
  4953. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4954. (
  4955. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4956. (
  4957. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4958. (
  4959. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4960. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4961. )
  4962. )
  4963. )
  4964. )
  4965. )
  4966. ) then
  4967. begin
  4968. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4969. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4970. begin
  4971. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4972. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4973. { if the register is used as index and base, we have to increase for base as well
  4974. and adapt base }
  4975. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4976. begin
  4977. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4978. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4979. end;
  4980. end
  4981. else
  4982. begin
  4983. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4984. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4985. end;
  4986. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4987. begin
  4988. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4989. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4990. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4991. end;
  4992. RemoveCurrentP(p);
  4993. result:=true;
  4994. exit;
  4995. end;
  4996. end;
  4997. { Change:
  4998. leal/q $x(%reg1),%reg2
  4999. ...
  5000. shll/q $y,%reg2
  5001. To:
  5002. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5003. }
  5004. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5005. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5006. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5007. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5008. (taicpu(hp1).oper[0]^.val <= 3) then
  5009. begin
  5010. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5011. TransferUsedRegs(TmpUsedRegs);
  5012. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5013. if
  5014. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5015. (this works even if scalefactor is zero) }
  5016. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5017. { Ensure offset doesn't go out of bounds }
  5018. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5019. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5020. (
  5021. (
  5022. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5023. (
  5024. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5025. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5026. (
  5027. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5028. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5029. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5030. )
  5031. )
  5032. ) or (
  5033. (
  5034. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5035. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5036. ) and
  5037. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5038. )
  5039. ) then
  5040. begin
  5041. repeat
  5042. with taicpu(p).oper[0]^.ref^ do
  5043. begin
  5044. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5045. if index = base then
  5046. begin
  5047. if Multiple > 4 then
  5048. { Optimisation will no longer work because resultant
  5049. scale factor will exceed 8 }
  5050. Break;
  5051. base := NR_NO;
  5052. scalefactor := 2;
  5053. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5054. end
  5055. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5056. begin
  5057. { Scale factor only works on the index register }
  5058. index := base;
  5059. base := NR_NO;
  5060. end;
  5061. { For safety }
  5062. if scalefactor <= 1 then
  5063. begin
  5064. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5065. scalefactor := Multiple;
  5066. end
  5067. else
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5070. scalefactor := scalefactor * Multiple;
  5071. end;
  5072. offset := offset * Multiple;
  5073. end;
  5074. RemoveInstruction(hp1);
  5075. Result := True;
  5076. Exit;
  5077. { This repeat..until loop exists for the benefit of Break }
  5078. until True;
  5079. end;
  5080. end;
  5081. end;
  5082. end;
  5083. end;
  5084. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  5085. var
  5086. hp1 : tai;
  5087. begin
  5088. DoSubAddOpt := False;
  5089. if taicpu(p).oper[0]^.typ <> top_const then
  5090. { Should have been confirmed before calling }
  5091. InternalError(2021102601);
  5092. if GetLastInstruction(p, hp1) and
  5093. (hp1.typ = ait_instruction) and
  5094. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5095. case taicpu(hp1).opcode Of
  5096. A_DEC:
  5097. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5098. begin
  5099. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  5100. RemoveInstruction(hp1);
  5101. end;
  5102. A_SUB:
  5103. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5104. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5105. begin
  5106. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  5107. RemoveInstruction(hp1);
  5108. end;
  5109. A_ADD:
  5110. begin
  5111. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5112. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5113. begin
  5114. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  5115. RemoveInstruction(hp1);
  5116. if (taicpu(p).oper[0]^.val = 0) then
  5117. begin
  5118. hp1 := tai(p.next);
  5119. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5120. if not GetLastInstruction(hp1, p) then
  5121. p := hp1;
  5122. DoSubAddOpt := True;
  5123. end
  5124. end;
  5125. end;
  5126. else
  5127. ;
  5128. end;
  5129. end;
  5130. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5131. begin
  5132. Result := False;
  5133. if UpdateTmpUsedRegs then
  5134. TransferUsedRegs(TmpUsedRegs);
  5135. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5136. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5137. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5138. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5139. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5140. (
  5141. (
  5142. (taicpu(hp1).opcode = A_TEST)
  5143. ) or (
  5144. (taicpu(hp1).opcode = A_CMP) and
  5145. { A sanity check more than anything }
  5146. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5147. )
  5148. ) then
  5149. begin
  5150. { change
  5151. mov mem, %reg
  5152. cmp/test x, %reg / test %reg,%reg
  5153. (reg deallocated)
  5154. to
  5155. cmp/test x, mem / cmp 0, mem
  5156. }
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5158. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5159. begin
  5160. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5161. if (taicpu(hp1).opcode = A_TEST) and
  5162. (
  5163. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5164. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5165. ) then
  5166. begin
  5167. taicpu(hp1).opcode := A_CMP;
  5168. taicpu(hp1).loadconst(0, 0);
  5169. end;
  5170. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5171. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5172. RemoveCurrentP(p, hp1);
  5173. Result := True;
  5174. Exit;
  5175. end;
  5176. end;
  5177. end;
  5178. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5179. var
  5180. hp2, hp3, hp4, hp5, hp6: tai;
  5181. ThisReg: TRegister;
  5182. JumpLoc: TAsmLabel;
  5183. begin
  5184. Result := False;
  5185. {
  5186. Convert:
  5187. j<c> .L1
  5188. .L2:
  5189. mov 1,reg
  5190. jmp .L3 (or ret, although it might not be a RET yet)
  5191. .L1:
  5192. mov 0,reg
  5193. jmp .L3 (or ret)
  5194. ( As long as .L3 <> .L1 or .L2)
  5195. To:
  5196. mov 0,reg
  5197. set<not(c)> reg
  5198. jmp .L3 (or ret)
  5199. .L2:
  5200. mov 1,reg
  5201. jmp .L3 (or ret)
  5202. .L1:
  5203. mov 0,reg
  5204. jmp .L3 (or ret)
  5205. }
  5206. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5207. Exit;
  5208. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5209. if GetNextInstruction(hp_label, hp2) and
  5210. MatchInstruction(hp2,A_MOV,[]) and
  5211. (taicpu(hp2).oper[0]^.typ = top_const) and
  5212. (
  5213. (
  5214. (taicpu(hp2).oper[1]^.typ = top_reg)
  5215. {$ifdef i386}
  5216. { Under i386, ESI, EDI, EBP and ESP
  5217. don't have an 8-bit representation }
  5218. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5219. {$endif i386}
  5220. ) or (
  5221. {$ifdef i386}
  5222. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5223. {$endif i386}
  5224. (taicpu(hp2).opsize = S_B)
  5225. )
  5226. ) and
  5227. GetNextInstruction(hp2, hp3) and
  5228. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5229. (
  5230. (taicpu(hp3).opcode=A_RET) or
  5231. (
  5232. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5233. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5234. )
  5235. ) and
  5236. GetNextInstruction(hp3, hp4) and
  5237. SkipAligns(hp4, hp4) and
  5238. (hp4.typ=ait_label) and
  5239. (tai_label(hp4).labsym=JumpLoc) and
  5240. (
  5241. not (cs_opt_size in current_settings.optimizerswitches) or
  5242. { If the initial jump is the label's only reference, then it will
  5243. become a dead label if the other conditions are met and hence
  5244. remove at least 2 instructions, including a jump }
  5245. (JumpLoc.getrefs = 1)
  5246. ) and
  5247. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5248. that will be optimised out }
  5249. GetNextInstruction(hp4, hp5) and
  5250. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5251. (taicpu(hp5).oper[0]^.typ = top_const) and
  5252. (
  5253. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5254. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5255. ) and
  5256. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5257. GetNextInstruction(hp5,hp6) and
  5258. (
  5259. (hp6.typ<>ait_label) or
  5260. SkipLabels(hp6, hp6)
  5261. ) and
  5262. (hp6.typ=ait_instruction) then
  5263. begin
  5264. { First, let's look at the two jumps that are hp3 and hp6 }
  5265. if not
  5266. (
  5267. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5268. (
  5269. (taicpu(hp6).opcode=A_RET) or
  5270. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5271. )
  5272. ) then
  5273. { If condition is False, then the JMP/RET instructions matched conventionally }
  5274. begin
  5275. { See if one of the jumps can be instantly converted into a RET }
  5276. if (taicpu(hp3).opcode=A_JMP) then
  5277. begin
  5278. { Reuse hp5 }
  5279. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5280. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5281. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5282. Exit;
  5283. if MatchInstruction(hp5, A_RET, []) then
  5284. begin
  5285. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5286. ConvertJumpToRET(hp3, hp5);
  5287. Result := True;
  5288. end
  5289. else
  5290. Exit;
  5291. end;
  5292. if (taicpu(hp6).opcode=A_JMP) then
  5293. begin
  5294. { Reuse hp5 }
  5295. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5296. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5297. Exit;
  5298. if MatchInstruction(hp5, A_RET, []) then
  5299. begin
  5300. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5301. ConvertJumpToRET(hp6, hp5);
  5302. Result := True;
  5303. end
  5304. else
  5305. Exit;
  5306. end;
  5307. if not
  5308. (
  5309. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5310. (
  5311. (taicpu(hp6).opcode=A_RET) or
  5312. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5313. )
  5314. ) then
  5315. { Still doesn't match }
  5316. Exit;
  5317. end;
  5318. if (taicpu(hp2).oper[0]^.val = 1) then
  5319. begin
  5320. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5321. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5322. end
  5323. else
  5324. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5325. if taicpu(hp2).opsize=S_B then
  5326. begin
  5327. if taicpu(hp2).oper[1]^.typ = top_reg then
  5328. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5329. else
  5330. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5331. hp2 := p;
  5332. end
  5333. else
  5334. begin
  5335. { Will be a register because the size can't be S_B otherwise }
  5336. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5337. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5338. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5339. { Inserting it right before p will guarantee that the flags are also tracked }
  5340. Asml.InsertBefore(hp2, p);
  5341. end;
  5342. taicpu(hp4).condition:=taicpu(p).condition;
  5343. asml.InsertBefore(hp4, hp2);
  5344. JumpLoc.decrefs;
  5345. if taicpu(hp3).opcode = A_JMP then
  5346. begin
  5347. MakeUnconditional(taicpu(p));
  5348. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5349. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5350. end
  5351. else
  5352. begin
  5353. taicpu(p).condition := C_None;
  5354. taicpu(p).opcode := A_RET;
  5355. taicpu(p).clearop(0);
  5356. taicpu(p).ops := 0;
  5357. end;
  5358. if (JumpLoc.getrefs = 0) then
  5359. RemoveDeadCodeAfterJump(hp3);
  5360. Result:=true;
  5361. exit;
  5362. end;
  5363. end;
  5364. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5365. var
  5366. hp1, hp2: tai;
  5367. ActiveReg: TRegister;
  5368. OldOffset: asizeint;
  5369. ThisConst: TCGInt;
  5370. function RegDeallocated: Boolean;
  5371. begin
  5372. TransferUsedRegs(TmpUsedRegs);
  5373. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5374. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5375. end;
  5376. begin
  5377. Result:=false;
  5378. hp1 := nil;
  5379. { replace
  5380. subX const,%reg1
  5381. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5382. dealloc %reg1
  5383. by
  5384. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5385. }
  5386. if MatchOpType(taicpu(p),top_const,top_reg) then
  5387. begin
  5388. ActiveReg := taicpu(p).oper[1]^.reg;
  5389. { Ensures the entire register was updated }
  5390. if (taicpu(p).opsize >= S_L) and
  5391. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5392. MatchInstruction(hp1,A_LEA,[]) and
  5393. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5394. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5395. (
  5396. { Cover the case where the register in the reference is also the destination register }
  5397. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5398. (
  5399. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5400. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5401. RegDeallocated
  5402. )
  5403. ) then
  5404. begin
  5405. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5406. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5407. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5408. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5409. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5410. {$ifdef x86_64}
  5411. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5412. begin
  5413. { Overflow; abort }
  5414. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5415. end
  5416. else
  5417. {$endif x86_64}
  5418. begin
  5419. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5420. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5421. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5422. RemoveCurrentP(p, hp1)
  5423. else
  5424. RemoveCurrentP(p);
  5425. result:=true;
  5426. Exit;
  5427. end;
  5428. end;
  5429. if (
  5430. { Save calling GetNextInstructionUsingReg again }
  5431. Assigned(hp1) or
  5432. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5433. ) and
  5434. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5435. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5436. begin
  5437. if taicpu(hp1).oper[0]^.typ = top_const then
  5438. begin
  5439. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5440. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5441. Result := True;
  5442. { Handle any overflows }
  5443. case taicpu(p).opsize of
  5444. S_B:
  5445. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5446. S_W:
  5447. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5448. S_L:
  5449. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5450. {$ifdef x86_64}
  5451. S_Q:
  5452. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5453. { Overflow; abort }
  5454. Result := False
  5455. else
  5456. taicpu(p).oper[0]^.val := ThisConst;
  5457. {$endif x86_64}
  5458. else
  5459. InternalError(2021102610);
  5460. end;
  5461. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5462. if Result then
  5463. begin
  5464. if (taicpu(p).oper[0]^.val < 0) and
  5465. (
  5466. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5467. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5468. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5469. ) then
  5470. begin
  5471. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5472. taicpu(p).opcode := A_SUB;
  5473. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5474. end
  5475. else
  5476. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5477. RemoveInstruction(hp1);
  5478. end;
  5479. end
  5480. else
  5481. begin
  5482. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5483. TransferUsedRegs(TmpUsedRegs);
  5484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5485. hp2 := p;
  5486. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5487. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5488. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5489. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5490. begin
  5491. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5492. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5493. Asml.Remove(p);
  5494. Asml.InsertAfter(p, hp1);
  5495. p := hp1;
  5496. Result := True;
  5497. Exit;
  5498. end;
  5499. end;
  5500. end;
  5501. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5502. { * change "sub/add const1, reg" or "dec reg" followed by
  5503. "sub const2, reg" to one "sub ..., reg" }
  5504. {$ifdef i386}
  5505. if (taicpu(p).oper[0]^.val = 2) and
  5506. (ActiveReg = NR_ESP) and
  5507. { Don't do the sub/push optimization if the sub }
  5508. { comes from setting up the stack frame (JM) }
  5509. (not(GetLastInstruction(p,hp1)) or
  5510. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5511. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5512. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5513. begin
  5514. hp1 := tai(p.next);
  5515. while Assigned(hp1) and
  5516. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5517. not RegReadByInstruction(NR_ESP,hp1) and
  5518. not RegModifiedByInstruction(NR_ESP,hp1) do
  5519. hp1 := tai(hp1.next);
  5520. if Assigned(hp1) and
  5521. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5522. begin
  5523. taicpu(hp1).changeopsize(S_L);
  5524. if taicpu(hp1).oper[0]^.typ=top_reg then
  5525. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5526. hp1 := tai(p.next);
  5527. RemoveCurrentp(p, hp1);
  5528. Result:=true;
  5529. exit;
  5530. end;
  5531. end;
  5532. {$endif i386}
  5533. if DoSubAddOpt(p) then
  5534. Result:=true;
  5535. end;
  5536. end;
  5537. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5538. var
  5539. TmpBool1,TmpBool2 : Boolean;
  5540. tmpref : treference;
  5541. hp1,hp2: tai;
  5542. mask: tcgint;
  5543. begin
  5544. Result:=false;
  5545. { All these optimisations work on "shl/sal const,%reg" }
  5546. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5547. Exit;
  5548. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5549. (taicpu(p).oper[0]^.val <= 3) then
  5550. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5551. begin
  5552. { should we check the next instruction? }
  5553. TmpBool1 := True;
  5554. { have we found an add/sub which could be
  5555. integrated in the lea? }
  5556. TmpBool2 := False;
  5557. reference_reset(tmpref,2,[]);
  5558. TmpRef.index := taicpu(p).oper[1]^.reg;
  5559. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5560. while TmpBool1 and
  5561. GetNextInstruction(p, hp1) and
  5562. (tai(hp1).typ = ait_instruction) and
  5563. ((((taicpu(hp1).opcode = A_ADD) or
  5564. (taicpu(hp1).opcode = A_SUB)) and
  5565. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5566. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5567. (((taicpu(hp1).opcode = A_INC) or
  5568. (taicpu(hp1).opcode = A_DEC)) and
  5569. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5570. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5571. ((taicpu(hp1).opcode = A_LEA) and
  5572. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5573. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5574. (not GetNextInstruction(hp1,hp2) or
  5575. not instrReadsFlags(hp2)) Do
  5576. begin
  5577. TmpBool1 := False;
  5578. if taicpu(hp1).opcode=A_LEA then
  5579. begin
  5580. if (TmpRef.base = NR_NO) and
  5581. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5582. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5583. { Segment register isn't a concern here }
  5584. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5585. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5586. begin
  5587. TmpBool1 := True;
  5588. TmpBool2 := True;
  5589. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5590. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5591. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5592. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5593. RemoveInstruction(hp1);
  5594. end
  5595. end
  5596. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5597. begin
  5598. TmpBool1 := True;
  5599. TmpBool2 := True;
  5600. case taicpu(hp1).opcode of
  5601. A_ADD:
  5602. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5603. A_SUB:
  5604. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5605. else
  5606. internalerror(2019050536);
  5607. end;
  5608. RemoveInstruction(hp1);
  5609. end
  5610. else
  5611. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5612. (((taicpu(hp1).opcode = A_ADD) and
  5613. (TmpRef.base = NR_NO)) or
  5614. (taicpu(hp1).opcode = A_INC) or
  5615. (taicpu(hp1).opcode = A_DEC)) then
  5616. begin
  5617. TmpBool1 := True;
  5618. TmpBool2 := True;
  5619. case taicpu(hp1).opcode of
  5620. A_ADD:
  5621. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5622. A_INC:
  5623. inc(TmpRef.offset);
  5624. A_DEC:
  5625. dec(TmpRef.offset);
  5626. else
  5627. internalerror(2019050535);
  5628. end;
  5629. RemoveInstruction(hp1);
  5630. end;
  5631. end;
  5632. if TmpBool2
  5633. {$ifndef x86_64}
  5634. or
  5635. ((current_settings.optimizecputype < cpu_Pentium2) and
  5636. (taicpu(p).oper[0]^.val <= 3) and
  5637. not(cs_opt_size in current_settings.optimizerswitches))
  5638. {$endif x86_64}
  5639. then
  5640. begin
  5641. if not(TmpBool2) and
  5642. (taicpu(p).oper[0]^.val=1) then
  5643. begin
  5644. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5645. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5646. end
  5647. else
  5648. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5649. taicpu(p).oper[1]^.reg);
  5650. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5651. InsertLLItem(p.previous, p.next, hp1);
  5652. p.free;
  5653. p := hp1;
  5654. end;
  5655. end
  5656. {$ifndef x86_64}
  5657. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5658. begin
  5659. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5660. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5661. (unlike shl, which is only Tairable in the U pipe) }
  5662. if taicpu(p).oper[0]^.val=1 then
  5663. begin
  5664. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5665. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5666. InsertLLItem(p.previous, p.next, hp1);
  5667. p.free;
  5668. p := hp1;
  5669. end
  5670. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5671. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5672. else if (taicpu(p).opsize = S_L) and
  5673. (taicpu(p).oper[0]^.val<= 3) then
  5674. begin
  5675. reference_reset(tmpref,2,[]);
  5676. TmpRef.index := taicpu(p).oper[1]^.reg;
  5677. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5678. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5679. InsertLLItem(p.previous, p.next, hp1);
  5680. p.free;
  5681. p := hp1;
  5682. end;
  5683. end
  5684. {$endif x86_64}
  5685. else if
  5686. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5687. (
  5688. (
  5689. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5690. SetAndTest(hp1, hp2)
  5691. {$ifdef x86_64}
  5692. ) or
  5693. (
  5694. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5695. GetNextInstruction(hp1, hp2) and
  5696. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5697. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5698. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5699. {$endif x86_64}
  5700. )
  5701. ) and
  5702. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5703. begin
  5704. { Change:
  5705. shl x, %reg1
  5706. mov -(1<<x), %reg2
  5707. and %reg2, %reg1
  5708. Or:
  5709. shl x, %reg1
  5710. and -(1<<x), %reg1
  5711. To just:
  5712. shl x, %reg1
  5713. Since the and operation only zeroes bits that are already zero from the shl operation
  5714. }
  5715. case taicpu(p).oper[0]^.val of
  5716. 8:
  5717. mask:=$FFFFFFFFFFFFFF00;
  5718. 16:
  5719. mask:=$FFFFFFFFFFFF0000;
  5720. 32:
  5721. mask:=$FFFFFFFF00000000;
  5722. 63:
  5723. { Constant pre-calculated to prevent overflow errors with Int64 }
  5724. mask:=$8000000000000000;
  5725. else
  5726. begin
  5727. if taicpu(p).oper[0]^.val >= 64 then
  5728. { Shouldn't happen realistically, since the register
  5729. is guaranteed to be set to zero at this point }
  5730. mask := 0
  5731. else
  5732. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5733. end;
  5734. end;
  5735. if taicpu(hp1).oper[0]^.val = mask then
  5736. begin
  5737. { Everything checks out, perform the optimisation, as long as
  5738. the FLAGS register isn't being used}
  5739. TransferUsedRegs(TmpUsedRegs);
  5740. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5741. {$ifdef x86_64}
  5742. if (hp1 <> hp2) then
  5743. begin
  5744. { "shl/mov/and" version }
  5745. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5746. { Don't do the optimisation if the FLAGS register is in use }
  5747. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5748. begin
  5749. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5750. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5751. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5752. begin
  5753. RemoveInstruction(hp1);
  5754. Result := True;
  5755. end;
  5756. { Only set Result to True if the 'mov' instruction was removed }
  5757. RemoveInstruction(hp2);
  5758. end;
  5759. end
  5760. else
  5761. {$endif x86_64}
  5762. begin
  5763. { "shl/and" version }
  5764. { Don't do the optimisation if the FLAGS register is in use }
  5765. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5766. begin
  5767. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5768. RemoveInstruction(hp1);
  5769. Result := True;
  5770. end;
  5771. end;
  5772. Exit;
  5773. end
  5774. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5775. begin
  5776. { Even if the mask doesn't allow for its removal, we might be
  5777. able to optimise the mask for the "shl/and" version, which
  5778. may permit other peephole optimisations }
  5779. {$ifdef DEBUG_AOPTCPU}
  5780. mask := taicpu(hp1).oper[0]^.val and mask;
  5781. if taicpu(hp1).oper[0]^.val <> mask then
  5782. begin
  5783. DebugMsg(
  5784. SPeepholeOptimization +
  5785. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5786. ' to $' + debug_tostr(mask) +
  5787. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5788. taicpu(hp1).oper[0]^.val := mask;
  5789. end;
  5790. {$else DEBUG_AOPTCPU}
  5791. { If debugging is off, just set the operand even if it's the same }
  5792. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5793. {$endif DEBUG_AOPTCPU}
  5794. end;
  5795. end;
  5796. {
  5797. change
  5798. shl/sal const,reg
  5799. <op> ...(...,reg,1),...
  5800. into
  5801. <op> ...(...,reg,1 shl const),...
  5802. if const in 1..3
  5803. }
  5804. if MatchOpType(taicpu(p), top_const, top_reg) and
  5805. (taicpu(p).oper[0]^.val in [1..3]) and
  5806. GetNextInstruction(p, hp1) and
  5807. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5808. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5809. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5810. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5811. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5812. begin
  5813. TransferUsedRegs(TmpUsedRegs);
  5814. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5815. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5816. begin
  5817. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5818. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5819. RemoveCurrentP(p);
  5820. Result:=true;
  5821. end;
  5822. end;
  5823. end;
  5824. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5825. var
  5826. CurrentRef: TReference;
  5827. FullReg: TRegister;
  5828. hp1, hp2: tai;
  5829. begin
  5830. Result := False;
  5831. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5832. Exit;
  5833. { We assume you've checked if the operand is actually a reference by
  5834. this point. If it isn't, you'll most likely get an access violation }
  5835. CurrentRef := first_mov.oper[1]^.ref^;
  5836. { Memory must be aligned }
  5837. if (CurrentRef.offset mod 4) <> 0 then
  5838. Exit;
  5839. Inc(CurrentRef.offset);
  5840. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5841. if MatchOperand(second_mov.oper[0]^, 0) and
  5842. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5843. GetNextInstruction(second_mov, hp1) and
  5844. (hp1.typ = ait_instruction) and
  5845. (taicpu(hp1).opcode = A_MOV) and
  5846. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5847. (taicpu(hp1).oper[0]^.val = 0) then
  5848. begin
  5849. Inc(CurrentRef.offset);
  5850. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5851. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5852. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5853. begin
  5854. case taicpu(hp1).opsize of
  5855. S_B:
  5856. if GetNextInstruction(hp1, hp2) and
  5857. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5858. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5859. (taicpu(hp2).oper[0]^.val = 0) then
  5860. begin
  5861. Inc(CurrentRef.offset);
  5862. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5863. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5864. (taicpu(hp2).opsize = S_B) then
  5865. begin
  5866. RemoveInstruction(hp1);
  5867. RemoveInstruction(hp2);
  5868. first_mov.opsize := S_L;
  5869. if first_mov.oper[0]^.typ = top_reg then
  5870. begin
  5871. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5872. { Reuse second_mov as a MOVZX instruction }
  5873. second_mov.opcode := A_MOVZX;
  5874. second_mov.opsize := S_BL;
  5875. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5876. second_mov.loadreg(1, FullReg);
  5877. first_mov.oper[0]^.reg := FullReg;
  5878. asml.Remove(second_mov);
  5879. asml.InsertBefore(second_mov, first_mov);
  5880. end
  5881. else
  5882. { It's a value }
  5883. begin
  5884. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5885. RemoveInstruction(second_mov);
  5886. end;
  5887. Result := True;
  5888. Exit;
  5889. end;
  5890. end;
  5891. S_W:
  5892. begin
  5893. RemoveInstruction(hp1);
  5894. first_mov.opsize := S_L;
  5895. if first_mov.oper[0]^.typ = top_reg then
  5896. begin
  5897. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5898. { Reuse second_mov as a MOVZX instruction }
  5899. second_mov.opcode := A_MOVZX;
  5900. second_mov.opsize := S_BL;
  5901. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5902. second_mov.loadreg(1, FullReg);
  5903. first_mov.oper[0]^.reg := FullReg;
  5904. asml.Remove(second_mov);
  5905. asml.InsertBefore(second_mov, first_mov);
  5906. end
  5907. else
  5908. { It's a value }
  5909. begin
  5910. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5911. RemoveInstruction(second_mov);
  5912. end;
  5913. Result := True;
  5914. Exit;
  5915. end;
  5916. else
  5917. ;
  5918. end;
  5919. end;
  5920. end;
  5921. end;
  5922. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5923. { returns true if a "continue" should be done after this optimization }
  5924. var
  5925. hp1, hp2: tai;
  5926. begin
  5927. Result := false;
  5928. if MatchOpType(taicpu(p),top_ref) and
  5929. GetNextInstruction(p, hp1) and
  5930. (hp1.typ = ait_instruction) and
  5931. (((taicpu(hp1).opcode = A_FLD) and
  5932. (taicpu(p).opcode = A_FSTP)) or
  5933. ((taicpu(p).opcode = A_FISTP) and
  5934. (taicpu(hp1).opcode = A_FILD))) and
  5935. MatchOpType(taicpu(hp1),top_ref) and
  5936. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5937. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5938. begin
  5939. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5940. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5941. GetNextInstruction(hp1, hp2) and
  5942. (hp2.typ = ait_instruction) and
  5943. IsExitCode(hp2) and
  5944. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5945. not(assigned(current_procinfo.procdef.funcretsym) and
  5946. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5947. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5948. begin
  5949. RemoveInstruction(hp1);
  5950. RemoveCurrentP(p, hp2);
  5951. RemoveLastDeallocForFuncRes(p);
  5952. Result := true;
  5953. end
  5954. else
  5955. { we can do this only in fast math mode as fstp is rounding ...
  5956. ... still disabled as it breaks the compiler and/or rtl }
  5957. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5958. { ... or if another fstp equal to the first one follows }
  5959. (GetNextInstruction(hp1,hp2) and
  5960. (hp2.typ = ait_instruction) and
  5961. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5962. (taicpu(p).opsize=taicpu(hp2).opsize))
  5963. ) and
  5964. { fst can't store an extended/comp value }
  5965. (taicpu(p).opsize <> S_FX) and
  5966. (taicpu(p).opsize <> S_IQ) then
  5967. begin
  5968. if (taicpu(p).opcode = A_FSTP) then
  5969. taicpu(p).opcode := A_FST
  5970. else
  5971. taicpu(p).opcode := A_FIST;
  5972. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5973. RemoveInstruction(hp1);
  5974. end;
  5975. end;
  5976. end;
  5977. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5978. var
  5979. hp1, hp2: tai;
  5980. begin
  5981. result:=false;
  5982. if MatchOpType(taicpu(p),top_reg) and
  5983. GetNextInstruction(p, hp1) and
  5984. (hp1.typ = Ait_Instruction) and
  5985. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5986. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5987. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5988. { change to
  5989. fld reg fxxx reg,st
  5990. fxxxp st, st1 (hp1)
  5991. Remark: non commutative operations must be reversed!
  5992. }
  5993. begin
  5994. case taicpu(hp1).opcode Of
  5995. A_FMULP,A_FADDP,
  5996. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5997. begin
  5998. case taicpu(hp1).opcode Of
  5999. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6000. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6001. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6002. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6003. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6004. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6005. else
  6006. internalerror(2019050534);
  6007. end;
  6008. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6009. taicpu(hp1).oper[1]^.reg := NR_ST;
  6010. RemoveCurrentP(p, hp1);
  6011. Result:=true;
  6012. exit;
  6013. end;
  6014. else
  6015. ;
  6016. end;
  6017. end
  6018. else
  6019. if MatchOpType(taicpu(p),top_ref) and
  6020. GetNextInstruction(p, hp2) and
  6021. (hp2.typ = Ait_Instruction) and
  6022. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6023. (taicpu(p).opsize in [S_FS, S_FL]) and
  6024. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6025. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6026. if GetLastInstruction(p, hp1) and
  6027. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6028. MatchOpType(taicpu(hp1),top_ref) and
  6029. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6030. if ((taicpu(hp2).opcode = A_FMULP) or
  6031. (taicpu(hp2).opcode = A_FADDP)) then
  6032. { change to
  6033. fld/fst mem1 (hp1) fld/fst mem1
  6034. fld mem1 (p) fadd/
  6035. faddp/ fmul st, st
  6036. fmulp st, st1 (hp2) }
  6037. begin
  6038. RemoveCurrentP(p, hp1);
  6039. if (taicpu(hp2).opcode = A_FADDP) then
  6040. taicpu(hp2).opcode := A_FADD
  6041. else
  6042. taicpu(hp2).opcode := A_FMUL;
  6043. taicpu(hp2).oper[1]^.reg := NR_ST;
  6044. end
  6045. else
  6046. { change to
  6047. fld/fst mem1 (hp1) fld/fst mem1
  6048. fld mem1 (p) fld st}
  6049. begin
  6050. taicpu(p).changeopsize(S_FL);
  6051. taicpu(p).loadreg(0,NR_ST);
  6052. end
  6053. else
  6054. begin
  6055. case taicpu(hp2).opcode Of
  6056. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6057. { change to
  6058. fld/fst mem1 (hp1) fld/fst mem1
  6059. fld mem2 (p) fxxx mem2
  6060. fxxxp st, st1 (hp2) }
  6061. begin
  6062. case taicpu(hp2).opcode Of
  6063. A_FADDP: taicpu(p).opcode := A_FADD;
  6064. A_FMULP: taicpu(p).opcode := A_FMUL;
  6065. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6066. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6067. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6068. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6069. else
  6070. internalerror(2019050533);
  6071. end;
  6072. RemoveInstruction(hp2);
  6073. end
  6074. else
  6075. ;
  6076. end
  6077. end
  6078. end;
  6079. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6080. begin
  6081. Result := condition_in(cond1, cond2) or
  6082. { Not strictly subsets due to the actual flags checked, but because we're
  6083. comparing integers, E is a subset of AE and GE and their aliases }
  6084. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6085. end;
  6086. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6087. var
  6088. v: TCGInt;
  6089. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6090. FirstMatch: Boolean;
  6091. NewReg: TRegister;
  6092. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6093. begin
  6094. Result:=false;
  6095. { All these optimisations need a next instruction }
  6096. if not GetNextInstruction(p, hp1) then
  6097. Exit;
  6098. { Search for:
  6099. cmp ###,###
  6100. j(c1) @lbl1
  6101. ...
  6102. @lbl:
  6103. cmp ###,### (same comparison as above)
  6104. j(c2) @lbl2
  6105. If c1 is a subset of c2, change to:
  6106. cmp ###,###
  6107. j(c1) @lbl2
  6108. (@lbl1 may become a dead label as a result)
  6109. }
  6110. { Also handle cases where there are multiple jumps in a row }
  6111. p_jump := hp1;
  6112. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6113. begin
  6114. if IsJumpToLabel(taicpu(p_jump)) then
  6115. begin
  6116. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6117. p_label := nil;
  6118. if Assigned(JumpLabel) then
  6119. p_label := getlabelwithsym(JumpLabel);
  6120. if Assigned(p_label) and
  6121. GetNextInstruction(p_label, p_dist) and
  6122. MatchInstruction(p_dist, A_CMP, []) and
  6123. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6124. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6125. GetNextInstruction(p_dist, hp1_dist) and
  6126. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6127. begin
  6128. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6129. if JumpLabel = JumpLabel_dist then
  6130. { This is an infinite loop }
  6131. Exit;
  6132. { Best optimisation when the first condition is a subset (or equal) of the second }
  6133. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6134. begin
  6135. { Any registers used here will already be allocated }
  6136. if Assigned(JumpLabel) then
  6137. JumpLabel.DecRefs;
  6138. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6139. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6140. Result := True;
  6141. { Don't exit yet. Since p and p_jump haven't actually been
  6142. removed, we can check for more on this iteration }
  6143. end
  6144. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6145. GetNextInstruction(hp1_dist, hp1_label) and
  6146. SkipAligns(hp1_label, hp1_label) and
  6147. (hp1_label.typ = ait_label) then
  6148. begin
  6149. JumpLabel_far := tai_label(hp1_label).labsym;
  6150. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6151. { This is an infinite loop }
  6152. Exit;
  6153. if Assigned(JumpLabel_far) then
  6154. begin
  6155. { In this situation, if the first jump branches, the second one will never,
  6156. branch so change the destination label to after the second jump }
  6157. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6158. if Assigned(JumpLabel) then
  6159. JumpLabel.DecRefs;
  6160. JumpLabel_far.IncRefs;
  6161. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6162. Result := True;
  6163. { Don't exit yet. Since p and p_jump haven't actually been
  6164. removed, we can check for more on this iteration }
  6165. Continue;
  6166. end;
  6167. end;
  6168. end;
  6169. end;
  6170. { Search for:
  6171. cmp ###,###
  6172. j(c1) @lbl1
  6173. cmp ###,### (same as first)
  6174. Remove second cmp
  6175. }
  6176. if GetNextInstruction(p_jump, hp2) and
  6177. (
  6178. (
  6179. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6180. (
  6181. (
  6182. MatchOpType(taicpu(p), top_const, top_reg) and
  6183. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6184. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6185. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6186. ) or (
  6187. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6188. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6189. )
  6190. )
  6191. ) or (
  6192. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6193. MatchOperand(taicpu(p).oper[0]^, 0) and
  6194. (taicpu(p).oper[1]^.typ = top_reg) and
  6195. MatchInstruction(hp2, A_TEST, []) and
  6196. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6197. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6198. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6199. )
  6200. ) then
  6201. begin
  6202. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6203. RemoveInstruction(hp2);
  6204. Result := True;
  6205. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6206. end;
  6207. GetNextInstruction(p_jump, p_jump);
  6208. end;
  6209. {
  6210. Try to optimise the following:
  6211. cmp $x,### ($x and $y can be registers or constants)
  6212. je @lbl1 (only reference)
  6213. cmp $y,### (### are identical)
  6214. @Lbl:
  6215. sete %reg1
  6216. Change to:
  6217. cmp $x,###
  6218. sete %reg2 (allocate new %reg2)
  6219. cmp $y,###
  6220. sete %reg1
  6221. orb %reg2,%reg1
  6222. (dealloc %reg2)
  6223. This adds an instruction (so don't perform under -Os), but it removes
  6224. a conditional branch.
  6225. }
  6226. if not (cs_opt_size in current_settings.optimizerswitches) and
  6227. (
  6228. (hp1 = p_jump) or
  6229. GetNextInstruction(p, hp1)
  6230. ) and
  6231. MatchInstruction(hp1, A_Jcc, []) and
  6232. IsJumpToLabel(taicpu(hp1)) and
  6233. (taicpu(hp1).condition in [C_E, C_Z]) and
  6234. GetNextInstruction(hp1, hp2) and
  6235. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6236. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6237. { The first operand of CMP instructions can only be a register or
  6238. immediate anyway, so no need to check }
  6239. GetNextInstruction(hp2, p_label) and
  6240. (
  6241. (p_label.typ = ait_label) or
  6242. (
  6243. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6244. to potentially cut down on the iterations of Pass 1 }
  6245. MatchInstruction(p_label, A_Jcc, []) and
  6246. IsJumpToLabel(taicpu(p_label)) and
  6247. { Use p_dist to hold the jump briefly }
  6248. SetAndTest(p_label, p_dist) and
  6249. GetNextInstruction(p_dist, p_label) and
  6250. (p_label.typ = ait_label) and
  6251. (tai_label(p_label).labsym.getrefs >= 2) and
  6252. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6253. { We might as well collapse the jump now }
  6254. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6255. )
  6256. ) and
  6257. (tai_label(p_label).labsym.getrefs = 1) and
  6258. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6259. GetNextInstruction(p_label, p_dist) and
  6260. MatchInstruction(p_dist, A_SETcc, []) and
  6261. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6262. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6263. { Get the instruction after the SETcc instruction so we can
  6264. allocate a new register over the entire range }
  6265. GetNextInstruction(p_dist, hp1_dist) then
  6266. begin
  6267. TransferUsedRegs(TmpUsedRegs);
  6268. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6269. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6270. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6271. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6272. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6273. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6274. begin
  6275. { Register can appear in p if it's not used afterwards, so only
  6276. allocate between hp1 and hp1_dist }
  6277. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6278. if NewReg <> NR_NO then
  6279. begin
  6280. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6281. { Change the jump instruction into a SETcc instruction }
  6282. taicpu(hp1).opcode := A_SETcc;
  6283. taicpu(hp1).opsize := S_B;
  6284. taicpu(hp1).loadreg(0, NewReg);
  6285. { This is now a dead label }
  6286. tai_label(p_label).labsym.decrefs;
  6287. { Prefer adding before the next instruction so the FLAGS
  6288. register is deallocated first }
  6289. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6290. AsmL.InsertBefore(
  6291. hp2,
  6292. hp1_dist
  6293. );
  6294. { Make sure the new register is in use over the new instruction
  6295. (long-winded, but things work best when the FLAGS register
  6296. is not allocated here) }
  6297. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6298. Result := True;
  6299. { Don't exit yet, as p wasn't changed and hp1, while
  6300. modified, is still intact and might be optimised by the
  6301. SETcc optimisation below }
  6302. end;
  6303. end;
  6304. end;
  6305. if taicpu(p).oper[0]^.typ = top_const then
  6306. begin
  6307. if (taicpu(p).oper[0]^.val = 0) and
  6308. (taicpu(p).oper[1]^.typ = top_reg) and
  6309. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6310. begin
  6311. hp2 := p;
  6312. FirstMatch := True;
  6313. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6314. anything meaningful once it's converted to "test %reg,%reg";
  6315. additionally, some jumps will always (or never) branch, so
  6316. evaluate every jump immediately following the
  6317. comparison, optimising the conditions if possible.
  6318. Similarly with SETcc... those that are always set to 0 or 1
  6319. are changed to MOV instructions }
  6320. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6321. (
  6322. GetNextInstruction(hp2, hp1) and
  6323. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6324. ) do
  6325. begin
  6326. FirstMatch := False;
  6327. case taicpu(hp1).condition of
  6328. C_B, C_C, C_NAE, C_O:
  6329. { For B/NAE:
  6330. Will never branch since an unsigned integer can never be below zero
  6331. For C/O:
  6332. Result cannot overflow because 0 is being subtracted
  6333. }
  6334. begin
  6335. if taicpu(hp1).opcode = A_Jcc then
  6336. begin
  6337. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6338. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6339. RemoveInstruction(hp1);
  6340. { Since hp1 was deleted, hp2 must not be updated }
  6341. Continue;
  6342. end
  6343. else
  6344. begin
  6345. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6346. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6347. taicpu(hp1).opcode := A_MOV;
  6348. taicpu(hp1).ops := 2;
  6349. taicpu(hp1).condition := C_None;
  6350. taicpu(hp1).opsize := S_B;
  6351. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6352. taicpu(hp1).loadconst(0, 0);
  6353. end;
  6354. end;
  6355. C_BE, C_NA:
  6356. begin
  6357. { Will only branch if equal to zero }
  6358. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6359. taicpu(hp1).condition := C_E;
  6360. end;
  6361. C_A, C_NBE:
  6362. begin
  6363. { Will only branch if not equal to zero }
  6364. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6365. taicpu(hp1).condition := C_NE;
  6366. end;
  6367. C_AE, C_NB, C_NC, C_NO:
  6368. begin
  6369. { Will always branch }
  6370. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6371. if taicpu(hp1).opcode = A_Jcc then
  6372. begin
  6373. MakeUnconditional(taicpu(hp1));
  6374. { Any jumps/set that follow will now be dead code }
  6375. RemoveDeadCodeAfterJump(taicpu(hp1));
  6376. Break;
  6377. end
  6378. else
  6379. begin
  6380. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6381. taicpu(hp1).opcode := A_MOV;
  6382. taicpu(hp1).ops := 2;
  6383. taicpu(hp1).condition := C_None;
  6384. taicpu(hp1).opsize := S_B;
  6385. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6386. taicpu(hp1).loadconst(0, 1);
  6387. end;
  6388. end;
  6389. C_None:
  6390. InternalError(2020012201);
  6391. C_P, C_PE, C_NP, C_PO:
  6392. { We can't handle parity checks and they should never be generated
  6393. after a general-purpose CMP (it's used in some floating-point
  6394. comparisons that don't use CMP) }
  6395. InternalError(2020012202);
  6396. else
  6397. { Zero/Equality, Sign, their complements and all of the
  6398. signed comparisons do not need to be converted };
  6399. end;
  6400. hp2 := hp1;
  6401. end;
  6402. { Convert the instruction to a TEST }
  6403. taicpu(p).opcode := A_TEST;
  6404. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6405. Result := True;
  6406. Exit;
  6407. end
  6408. else if (taicpu(p).oper[0]^.val = 1) and
  6409. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6410. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6411. begin
  6412. { Convert; To:
  6413. cmp $1,r/m cmp $0,r/m
  6414. jl @lbl jle @lbl
  6415. }
  6416. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6417. taicpu(p).oper[0]^.val := 0;
  6418. taicpu(hp1).condition := C_LE;
  6419. { If the instruction is now "cmp $0,%reg", convert it to a
  6420. TEST (and effectively do the work of the "cmp $0,%reg" in
  6421. the block above)
  6422. If it's a reference, we can get away with not setting
  6423. Result to True because he haven't evaluated the jump
  6424. in this pass yet.
  6425. }
  6426. if (taicpu(p).oper[1]^.typ = top_reg) then
  6427. begin
  6428. taicpu(p).opcode := A_TEST;
  6429. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6430. Result := True;
  6431. end;
  6432. Exit;
  6433. end
  6434. else if (taicpu(p).oper[1]^.typ = top_reg)
  6435. {$ifdef x86_64}
  6436. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6437. {$endif x86_64}
  6438. then
  6439. begin
  6440. { cmp register,$8000 neg register
  6441. je target --> jo target
  6442. .... only if register is deallocated before jump.}
  6443. case Taicpu(p).opsize of
  6444. S_B: v:=$80;
  6445. S_W: v:=$8000;
  6446. S_L: v:=qword($80000000);
  6447. else
  6448. internalerror(2013112905);
  6449. end;
  6450. if (taicpu(p).oper[0]^.val=v) and
  6451. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6452. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6453. begin
  6454. TransferUsedRegs(TmpUsedRegs);
  6455. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6456. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6457. begin
  6458. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6459. Taicpu(p).opcode:=A_NEG;
  6460. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6461. Taicpu(p).clearop(1);
  6462. Taicpu(p).ops:=1;
  6463. if Taicpu(hp1).condition=C_E then
  6464. Taicpu(hp1).condition:=C_O
  6465. else
  6466. Taicpu(hp1).condition:=C_NO;
  6467. Result:=true;
  6468. exit;
  6469. end;
  6470. end;
  6471. end;
  6472. end;
  6473. if TrySwapMovCmp(p, hp1) then
  6474. begin
  6475. Result := True;
  6476. Exit;
  6477. end;
  6478. end;
  6479. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6480. var
  6481. hp1: tai;
  6482. begin
  6483. {
  6484. remove the second (v)pxor from
  6485. pxor reg,reg
  6486. ...
  6487. pxor reg,reg
  6488. }
  6489. Result:=false;
  6490. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6491. MatchOpType(taicpu(p),top_reg,top_reg) and
  6492. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6493. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6494. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6495. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6496. begin
  6497. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6498. RemoveInstruction(hp1);
  6499. Result:=true;
  6500. Exit;
  6501. end
  6502. {
  6503. replace
  6504. pxor reg1,reg1
  6505. movapd/s reg1,reg2
  6506. dealloc reg1
  6507. by
  6508. pxor reg2,reg2
  6509. }
  6510. else if GetNextInstruction(p,hp1) and
  6511. { we mix single and double opperations here because we assume that the compiler
  6512. generates vmovapd only after double operations and vmovaps only after single operations }
  6513. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6514. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6515. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6516. (taicpu(p).oper[0]^.typ=top_reg) then
  6517. begin
  6518. TransferUsedRegs(TmpUsedRegs);
  6519. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6520. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6521. begin
  6522. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6523. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6524. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6525. RemoveInstruction(hp1);
  6526. result:=true;
  6527. end;
  6528. end;
  6529. end;
  6530. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6531. var
  6532. hp1: tai;
  6533. begin
  6534. {
  6535. remove the second (v)pxor from
  6536. (v)pxor reg,reg
  6537. ...
  6538. (v)pxor reg,reg
  6539. }
  6540. Result:=false;
  6541. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6542. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6543. begin
  6544. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6545. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6546. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6547. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6548. begin
  6549. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  6550. RemoveInstruction(hp1);
  6551. Result:=true;
  6552. Exit;
  6553. end;
  6554. {$ifdef x86_64}
  6555. if GetNextInstruction(p,hp1) and
  6556. MatchInstruction(hp1,A_VMOVSD,[]) and
  6557. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6558. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  6559. begin
  6560. TransferUsedRegs(TmpUsedRegs);
  6561. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6562. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6563. begin
  6564. taicpu(hp1).loadconst(0,0);
  6565. taicpu(hp1).opcode:=A_MOV;
  6566. taicpu(hp1).opsize:=S_Q;
  6567. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  6568. RemoveCurrentP(p);
  6569. result:=true;
  6570. Exit;
  6571. end;
  6572. end;
  6573. {$endif x86_64}
  6574. end
  6575. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6576. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  6577. begin
  6578. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  6579. { avoid unncessary data dependency }
  6580. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  6581. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  6582. result:=true;
  6583. exit;
  6584. end;
  6585. Result:=OptPass1VOP(p);
  6586. end;
  6587. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6588. var
  6589. hp1 : tai;
  6590. begin
  6591. result:=false;
  6592. { replace
  6593. IMul const,%mreg1,%mreg2
  6594. Mov %reg2,%mreg3
  6595. dealloc %mreg3
  6596. by
  6597. Imul const,%mreg1,%mreg23
  6598. }
  6599. if (taicpu(p).ops=3) and
  6600. GetNextInstruction(p,hp1) and
  6601. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6602. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6603. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6604. begin
  6605. TransferUsedRegs(TmpUsedRegs);
  6606. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6607. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6608. begin
  6609. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6610. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6611. RemoveInstruction(hp1);
  6612. result:=true;
  6613. end;
  6614. end;
  6615. end;
  6616. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6617. var
  6618. hp1 : tai;
  6619. begin
  6620. result:=false;
  6621. { replace
  6622. IMul %reg0,%reg1,%reg2
  6623. Mov %reg2,%reg3
  6624. dealloc %reg2
  6625. by
  6626. Imul %reg0,%reg1,%reg3
  6627. }
  6628. if GetNextInstruction(p,hp1) and
  6629. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6630. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6631. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6632. begin
  6633. TransferUsedRegs(TmpUsedRegs);
  6634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6635. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6636. begin
  6637. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6638. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6639. RemoveInstruction(hp1);
  6640. result:=true;
  6641. end;
  6642. end;
  6643. end;
  6644. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6645. var
  6646. hp1: tai;
  6647. begin
  6648. Result:=false;
  6649. { get rid of
  6650. (v)cvtss2sd reg0,<reg1,>reg2
  6651. (v)cvtss2sd reg2,<reg2,>reg0
  6652. }
  6653. if GetNextInstruction(p,hp1) and
  6654. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6655. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6656. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6657. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6658. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6659. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6660. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6661. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6662. )
  6663. ) then
  6664. begin
  6665. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6666. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6667. begin
  6668. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6669. RemoveCurrentP(p);
  6670. RemoveInstruction(hp1);
  6671. end
  6672. else
  6673. begin
  6674. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6675. if taicpu(hp1).opcode=A_CVTSD2SS then
  6676. begin
  6677. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6678. taicpu(p).opcode:=A_MOVAPS;
  6679. end
  6680. else
  6681. begin
  6682. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6683. taicpu(p).opcode:=A_VMOVAPS;
  6684. end;
  6685. taicpu(p).ops:=2;
  6686. RemoveInstruction(hp1);
  6687. end;
  6688. Result:=true;
  6689. Exit;
  6690. end;
  6691. end;
  6692. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6693. var
  6694. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6695. ThisReg: TRegister;
  6696. begin
  6697. Result := False;
  6698. if not GetNextInstruction(p,hp1) then
  6699. Exit;
  6700. {
  6701. convert
  6702. j<c> .L1
  6703. mov 1,reg
  6704. jmp .L2
  6705. .L1
  6706. mov 0,reg
  6707. .L2
  6708. into
  6709. mov 0,reg
  6710. set<not(c)> reg
  6711. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6712. would destroy the flag contents
  6713. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6714. executed at the same time as a previous comparison.
  6715. set<not(c)> reg
  6716. movzx reg, reg
  6717. }
  6718. if MatchInstruction(hp1,A_MOV,[]) and
  6719. (taicpu(hp1).oper[0]^.typ = top_const) and
  6720. (
  6721. (
  6722. (taicpu(hp1).oper[1]^.typ = top_reg)
  6723. {$ifdef i386}
  6724. { Under i386, ESI, EDI, EBP and ESP
  6725. don't have an 8-bit representation }
  6726. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6727. {$endif i386}
  6728. ) or (
  6729. {$ifdef i386}
  6730. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6731. {$endif i386}
  6732. (taicpu(hp1).opsize = S_B)
  6733. )
  6734. ) and
  6735. GetNextInstruction(hp1,hp2) and
  6736. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6737. GetNextInstruction(hp2,hp3) and
  6738. SkipAligns(hp3, hp3) and
  6739. (hp3.typ=ait_label) and
  6740. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6741. GetNextInstruction(hp3,hp4) and
  6742. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6743. (taicpu(hp4).oper[0]^.typ = top_const) and
  6744. (
  6745. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6746. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6747. ) and
  6748. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6749. GetNextInstruction(hp4,hp5) and
  6750. SkipAligns(hp5, hp5) and
  6751. (hp5.typ=ait_label) and
  6752. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6753. begin
  6754. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6755. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6756. tai_label(hp3).labsym.DecRefs;
  6757. { If this isn't the only reference to the middle label, we can
  6758. still make a saving - only that the first jump and everything
  6759. that follows will remain. }
  6760. if (tai_label(hp3).labsym.getrefs = 0) then
  6761. begin
  6762. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6763. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6764. else
  6765. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6766. { remove jump, first label and second MOV (also catching any aligns) }
  6767. repeat
  6768. if not GetNextInstruction(hp2, hp3) then
  6769. InternalError(2021040810);
  6770. RemoveInstruction(hp2);
  6771. hp2 := hp3;
  6772. until hp2 = hp5;
  6773. { Don't decrement reference count before the removal loop
  6774. above, otherwise GetNextInstruction won't stop on the
  6775. the label }
  6776. tai_label(hp5).labsym.DecRefs;
  6777. end
  6778. else
  6779. begin
  6780. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6781. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6782. else
  6783. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6784. end;
  6785. taicpu(p).opcode:=A_SETcc;
  6786. taicpu(p).opsize:=S_B;
  6787. taicpu(p).is_jmp:=False;
  6788. if taicpu(hp1).opsize=S_B then
  6789. begin
  6790. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6791. if taicpu(hp1).oper[1]^.typ = top_reg then
  6792. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6793. RemoveInstruction(hp1);
  6794. end
  6795. else
  6796. begin
  6797. { Will be a register because the size can't be S_B otherwise }
  6798. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6799. taicpu(p).loadreg(0, ThisReg);
  6800. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6801. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6802. begin
  6803. case taicpu(hp1).opsize of
  6804. S_W:
  6805. taicpu(hp1).opsize := S_BW;
  6806. S_L:
  6807. taicpu(hp1).opsize := S_BL;
  6808. {$ifdef x86_64}
  6809. S_Q:
  6810. begin
  6811. taicpu(hp1).opsize := S_BL;
  6812. { Change the destination register to 32-bit }
  6813. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6814. end;
  6815. {$endif x86_64}
  6816. else
  6817. InternalError(2021040820);
  6818. end;
  6819. taicpu(hp1).opcode := A_MOVZX;
  6820. taicpu(hp1).loadreg(0, ThisReg);
  6821. end
  6822. else
  6823. begin
  6824. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6825. { hp1 is already a MOV instruction with the correct register }
  6826. taicpu(hp1).loadconst(0, 0);
  6827. { Inserting it right before p will guarantee that the flags are also tracked }
  6828. asml.Remove(hp1);
  6829. asml.InsertBefore(hp1, p);
  6830. end;
  6831. end;
  6832. Result:=true;
  6833. exit;
  6834. end
  6835. else if (hp1.typ = ait_label) then
  6836. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6837. end;
  6838. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6839. var
  6840. hp1, hp2, hp3: tai;
  6841. SourceRef, TargetRef: TReference;
  6842. CurrentReg: TRegister;
  6843. begin
  6844. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6845. if not UseAVX then
  6846. InternalError(2021100501);
  6847. Result := False;
  6848. { Look for the following to simplify:
  6849. vmovdqa/u x(mem1), %xmmreg
  6850. vmovdqa/u %xmmreg, y(mem2)
  6851. vmovdqa/u x+16(mem1), %xmmreg
  6852. vmovdqa/u %xmmreg, y+16(mem2)
  6853. Change to:
  6854. vmovdqa/u x(mem1), %ymmreg
  6855. vmovdqa/u %ymmreg, y(mem2)
  6856. vpxor %ymmreg, %ymmreg, %ymmreg
  6857. ( The VPXOR instruction is to zero the upper half, thus removing the
  6858. need to call the potentially expensive VZEROUPPER instruction. Other
  6859. peephole optimisations can remove VPXOR if it's unnecessary )
  6860. }
  6861. TransferUsedRegs(TmpUsedRegs);
  6862. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6863. { NOTE: In the optimisations below, if the references dictate that an
  6864. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6865. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6866. if (taicpu(p).opsize = S_XMM) and
  6867. MatchOpType(taicpu(p), top_ref, top_reg) and
  6868. GetNextInstruction(p, hp1) and
  6869. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6870. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6871. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6872. begin
  6873. SourceRef := taicpu(p).oper[0]^.ref^;
  6874. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6875. if GetNextInstruction(hp1, hp2) and
  6876. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6877. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6878. begin
  6879. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6880. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6881. Inc(SourceRef.offset, 16);
  6882. { Reuse the register in the first block move }
  6883. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6884. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  6885. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  6886. begin
  6887. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6888. Inc(TargetRef.offset, 16);
  6889. if GetNextInstruction(hp2, hp3) and
  6890. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6891. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6892. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6893. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6894. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6895. begin
  6896. { Update the register tracking to the new size }
  6897. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6898. { Remember that the offsets are 16 ahead }
  6899. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6900. if not (
  6901. ((SourceRef.offset mod 32) = 16) and
  6902. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6903. ) then
  6904. taicpu(p).opcode := A_VMOVDQU;
  6905. taicpu(p).opsize := S_YMM;
  6906. taicpu(p).oper[1]^.reg := CurrentReg;
  6907. if not (
  6908. ((TargetRef.offset mod 32) = 16) and
  6909. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6910. ) then
  6911. taicpu(hp1).opcode := A_VMOVDQU;
  6912. taicpu(hp1).opsize := S_YMM;
  6913. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6914. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6915. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6916. if (pi_uses_ymm in current_procinfo.flags) then
  6917. RemoveInstruction(hp2)
  6918. else
  6919. begin
  6920. taicpu(hp2).opcode := A_VPXOR;
  6921. taicpu(hp2).opsize := S_YMM;
  6922. taicpu(hp2).loadreg(0, CurrentReg);
  6923. taicpu(hp2).loadreg(1, CurrentReg);
  6924. taicpu(hp2).loadreg(2, CurrentReg);
  6925. taicpu(hp2).ops := 3;
  6926. end;
  6927. RemoveInstruction(hp3);
  6928. Result := True;
  6929. Exit;
  6930. end;
  6931. end
  6932. else
  6933. begin
  6934. { See if the next references are 16 less rather than 16 greater }
  6935. Dec(SourceRef.offset, 32); { -16 the other way }
  6936. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6937. begin
  6938. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6939. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6940. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  6941. GetNextInstruction(hp2, hp3) and
  6942. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6943. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6944. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6945. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6946. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6947. begin
  6948. { Update the register tracking to the new size }
  6949. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6950. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6951. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6952. if not(
  6953. ((SourceRef.offset mod 32) = 0) and
  6954. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6955. ) then
  6956. taicpu(hp2).opcode := A_VMOVDQU;
  6957. taicpu(hp2).opsize := S_YMM;
  6958. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6959. if not (
  6960. ((TargetRef.offset mod 32) = 0) and
  6961. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6962. ) then
  6963. taicpu(hp3).opcode := A_VMOVDQU;
  6964. taicpu(hp3).opsize := S_YMM;
  6965. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6966. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6967. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6968. if (pi_uses_ymm in current_procinfo.flags) then
  6969. RemoveInstruction(hp1)
  6970. else
  6971. begin
  6972. taicpu(hp1).opcode := A_VPXOR;
  6973. taicpu(hp1).opsize := S_YMM;
  6974. taicpu(hp1).loadreg(0, CurrentReg);
  6975. taicpu(hp1).loadreg(1, CurrentReg);
  6976. taicpu(hp1).loadreg(2, CurrentReg);
  6977. taicpu(hp1).ops := 3;
  6978. Asml.Remove(hp1);
  6979. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6980. end;
  6981. RemoveCurrentP(p, hp2);
  6982. Result := True;
  6983. Exit;
  6984. end;
  6985. end;
  6986. end;
  6987. end;
  6988. end;
  6989. end;
  6990. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6991. var
  6992. hp2, hp3, first_assignment: tai;
  6993. IncCount, OperIdx: Integer;
  6994. OrigLabel: TAsmLabel;
  6995. begin
  6996. Count := 0;
  6997. Result := False;
  6998. first_assignment := nil;
  6999. if (LoopCount >= 20) then
  7000. begin
  7001. { Guard against infinite loops }
  7002. Exit;
  7003. end;
  7004. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7005. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7006. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7007. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7008. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7009. Exit;
  7010. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7011. {
  7012. change
  7013. jmp .L1
  7014. ...
  7015. .L1:
  7016. mov ##, ## ( multiple movs possible )
  7017. jmp/ret
  7018. into
  7019. mov ##, ##
  7020. jmp/ret
  7021. }
  7022. if not Assigned(hp1) then
  7023. begin
  7024. hp1 := GetLabelWithSym(OrigLabel);
  7025. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7026. Exit;
  7027. end;
  7028. hp2 := hp1;
  7029. while Assigned(hp2) do
  7030. begin
  7031. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7032. SkipLabels(hp2,hp2);
  7033. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7034. Break;
  7035. case taicpu(hp2).opcode of
  7036. A_MOVSS:
  7037. begin
  7038. if taicpu(hp2).ops = 0 then
  7039. { Wrong MOVSS }
  7040. Break;
  7041. Inc(Count);
  7042. if Count >= 5 then
  7043. { Too many to be worthwhile }
  7044. Break;
  7045. GetNextInstruction(hp2, hp2);
  7046. Continue;
  7047. end;
  7048. A_MOV,
  7049. A_MOVD,
  7050. A_MOVQ,
  7051. A_MOVSX,
  7052. {$ifdef x86_64}
  7053. A_MOVSXD,
  7054. {$endif x86_64}
  7055. A_MOVZX,
  7056. A_MOVAPS,
  7057. A_MOVUPS,
  7058. A_MOVSD,
  7059. A_MOVAPD,
  7060. A_MOVUPD,
  7061. A_MOVDQA,
  7062. A_MOVDQU,
  7063. A_VMOVSS,
  7064. A_VMOVAPS,
  7065. A_VMOVUPS,
  7066. A_VMOVSD,
  7067. A_VMOVAPD,
  7068. A_VMOVUPD,
  7069. A_VMOVDQA,
  7070. A_VMOVDQU:
  7071. begin
  7072. Inc(Count);
  7073. if Count >= 5 then
  7074. { Too many to be worthwhile }
  7075. Break;
  7076. GetNextInstruction(hp2, hp2);
  7077. Continue;
  7078. end;
  7079. A_JMP:
  7080. begin
  7081. { Guard against infinite loops }
  7082. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7083. Exit;
  7084. { Analyse this jump first in case it also duplicates assignments }
  7085. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7086. begin
  7087. { Something did change! }
  7088. Result := True;
  7089. Inc(Count, IncCount);
  7090. if Count >= 5 then
  7091. begin
  7092. { Too many to be worthwhile }
  7093. Exit;
  7094. end;
  7095. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7096. Break;
  7097. end;
  7098. Result := True;
  7099. Break;
  7100. end;
  7101. A_RET:
  7102. begin
  7103. Result := True;
  7104. Break;
  7105. end;
  7106. else
  7107. Break;
  7108. end;
  7109. end;
  7110. if Result then
  7111. begin
  7112. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7113. if Count = 0 then
  7114. begin
  7115. Result := False;
  7116. Exit;
  7117. end;
  7118. hp3 := p;
  7119. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7120. while True do
  7121. begin
  7122. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7123. SkipLabels(hp1,hp1);
  7124. if (hp1.typ <> ait_instruction) then
  7125. InternalError(2021040720);
  7126. case taicpu(hp1).opcode of
  7127. A_JMP:
  7128. begin
  7129. { Change the original jump to the new destination }
  7130. OrigLabel.decrefs;
  7131. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7132. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7133. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7134. if not Assigned(first_assignment) then
  7135. InternalError(2021040810)
  7136. else
  7137. p := first_assignment;
  7138. Exit;
  7139. end;
  7140. A_RET:
  7141. begin
  7142. { Now change the jump into a RET instruction }
  7143. ConvertJumpToRET(p, hp1);
  7144. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7145. if not Assigned(first_assignment) then
  7146. InternalError(2021040811)
  7147. else
  7148. p := first_assignment;
  7149. Exit;
  7150. end;
  7151. else
  7152. begin
  7153. { Duplicate the MOV instruction }
  7154. hp3:=tai(hp1.getcopy);
  7155. if first_assignment = nil then
  7156. first_assignment := hp3;
  7157. asml.InsertBefore(hp3, p);
  7158. { Make sure the compiler knows about any final registers written here }
  7159. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7160. with taicpu(hp3).oper[OperIdx]^ do
  7161. begin
  7162. case typ of
  7163. top_ref:
  7164. begin
  7165. if (ref^.base <> NR_NO) and
  7166. (getsupreg(ref^.base) <> RS_ESP) and
  7167. (getsupreg(ref^.base) <> RS_EBP)
  7168. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7169. then
  7170. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7171. if (ref^.index <> NR_NO) and
  7172. (getsupreg(ref^.index) <> RS_ESP) and
  7173. (getsupreg(ref^.index) <> RS_EBP)
  7174. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7175. (ref^.index <> ref^.base) then
  7176. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7177. end;
  7178. top_reg:
  7179. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7180. else
  7181. ;
  7182. end;
  7183. end;
  7184. end;
  7185. end;
  7186. if not GetNextInstruction(hp1, hp1) then
  7187. { Should have dropped out earlier }
  7188. InternalError(2021040710);
  7189. end;
  7190. end;
  7191. end;
  7192. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7193. var
  7194. hp2: tai;
  7195. X: Integer;
  7196. const
  7197. WriteOp: array[0..3] of set of TInsChange = (
  7198. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7199. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7200. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7201. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7202. RegWriteFlags: array[0..7] of set of TInsChange = (
  7203. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7204. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7205. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7206. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7207. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7208. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7209. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7210. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7211. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7212. begin
  7213. { If we have something like:
  7214. cmp ###,%reg1
  7215. mov 0,%reg2
  7216. And no modified registers are shared, move the instruction to before
  7217. the comparison as this means it can be optimised without worrying
  7218. about the FLAGS register. (CMP/MOV is generated by
  7219. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7220. As long as the second instruction doesn't use the flags or one of the
  7221. registers used by CMP or TEST (also check any references that use the
  7222. registers), then it can be moved prior to the comparison.
  7223. }
  7224. Result := False;
  7225. if (hp1.typ <> ait_instruction) or
  7226. taicpu(hp1).is_jmp or
  7227. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7228. Exit;
  7229. { NOP is a pipeline fence, likely marking the beginning of the function
  7230. epilogue, so drop out. Similarly, drop out if POP or RET are
  7231. encountered }
  7232. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7233. Exit;
  7234. if (taicpu(hp1).opcode = A_MOVSS) and
  7235. (taicpu(hp1).ops = 0) then
  7236. { Wrong MOVSS }
  7237. Exit;
  7238. { Check for writes to specific registers first }
  7239. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7240. for X := 0 to 7 do
  7241. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7242. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7243. Exit;
  7244. for X := 0 to taicpu(hp1).ops - 1 do
  7245. begin
  7246. { Check to see if this operand writes to something }
  7247. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7248. { And matches something in the CMP/TEST instruction }
  7249. (
  7250. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7251. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7252. (
  7253. { If it's a register, make sure the register written to doesn't
  7254. appear in the cmp instruction as part of a reference }
  7255. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7256. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7257. )
  7258. ) then
  7259. Exit;
  7260. end;
  7261. { The instruction can be safely moved }
  7262. asml.Remove(hp1);
  7263. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7264. can be optimised into "xor %reg,%reg" later }
  7265. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7266. asml.InsertBefore(hp1, hp2)
  7267. else
  7268. { Note, if p.Previous is nil (even if it should logically never be the
  7269. case), FindRegAllocBackward immediately exits with False and so we
  7270. safely land here (we can't just pass p because FindRegAllocBackward
  7271. immediately exits on an instruction). [Kit] }
  7272. asml.InsertBefore(hp1, p);
  7273. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7274. for X := 0 to taicpu(hp1).ops - 1 do
  7275. case taicpu(hp1).oper[X]^.typ of
  7276. top_reg:
  7277. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7278. top_ref:
  7279. begin
  7280. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7281. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7282. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7283. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7284. end;
  7285. else
  7286. ;
  7287. end;
  7288. if taicpu(hp1).opcode = A_LEA then
  7289. { The flags will be overwritten by the CMP/TEST instruction }
  7290. ConvertLEA(taicpu(hp1));
  7291. Result := True;
  7292. end;
  7293. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7294. function IsXCHGAcceptable: Boolean; inline;
  7295. begin
  7296. { Always accept if optimising for size }
  7297. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7298. (
  7299. {$ifdef x86_64}
  7300. { XCHG takes 3 cycles on AMD Athlon64 }
  7301. (current_settings.optimizecputype >= cpu_core_i)
  7302. {$else x86_64}
  7303. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7304. than 3, so it becomes a saving compared to three MOVs with two of
  7305. them able to execute simultaneously. [Kit] }
  7306. (current_settings.optimizecputype >= cpu_PentiumM)
  7307. {$endif x86_64}
  7308. );
  7309. end;
  7310. var
  7311. NewRef: TReference;
  7312. hp1, hp2, hp3, hp4: Tai;
  7313. {$ifndef x86_64}
  7314. OperIdx: Integer;
  7315. {$endif x86_64}
  7316. NewInstr : Taicpu;
  7317. NewAligh : Tai_align;
  7318. DestLabel: TAsmLabel;
  7319. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7320. var
  7321. NextInstr: tai;
  7322. begin
  7323. Result := False;
  7324. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7325. if not GetNextInstruction(InputInstr, NextInstr) or
  7326. (
  7327. { The FLAGS register isn't always tracked properly, so do not
  7328. perform this optimisation if a conditional statement follows }
  7329. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7330. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7331. ) then
  7332. begin
  7333. reference_reset(NewRef, 1, []);
  7334. NewRef.base := taicpu(p).oper[0]^.reg;
  7335. NewRef.scalefactor := 1;
  7336. if taicpu(InputInstr).opcode = A_ADD then
  7337. begin
  7338. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7339. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7340. end
  7341. else
  7342. begin
  7343. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7344. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7345. end;
  7346. taicpu(p).opcode := A_LEA;
  7347. taicpu(p).loadref(0, NewRef);
  7348. RemoveInstruction(InputInstr);
  7349. Result := True;
  7350. end;
  7351. end;
  7352. begin
  7353. Result:=false;
  7354. { This optimisation adds an instruction, so only do it for speed }
  7355. if not (cs_opt_size in current_settings.optimizerswitches) and
  7356. MatchOpType(taicpu(p), top_const, top_reg) and
  7357. (taicpu(p).oper[0]^.val = 0) then
  7358. begin
  7359. { To avoid compiler warning }
  7360. DestLabel := nil;
  7361. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7362. InternalError(2021040750);
  7363. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7364. Exit;
  7365. case hp1.typ of
  7366. ait_label:
  7367. begin
  7368. { Change:
  7369. mov $0,%reg mov $0,%reg
  7370. @Lbl1: @Lbl1:
  7371. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7372. je @Lbl2 jne @Lbl2
  7373. To: To:
  7374. mov $0,%reg mov $0,%reg
  7375. jmp @Lbl2 jmp @Lbl3
  7376. (align) (align)
  7377. @Lbl1: @Lbl1:
  7378. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7379. je @Lbl2 je @Lbl2
  7380. @Lbl3: <-- Only if label exists
  7381. (Not if it's optimised for size)
  7382. }
  7383. if not GetNextInstruction(hp1, hp2) then
  7384. Exit;
  7385. if not (cs_opt_size in current_settings.optimizerswitches) and
  7386. (hp2.typ = ait_instruction) and
  7387. (
  7388. { Register sizes must exactly match }
  7389. (
  7390. (taicpu(hp2).opcode = A_CMP) and
  7391. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7392. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7393. ) or (
  7394. (taicpu(hp2).opcode = A_TEST) and
  7395. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7396. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7397. )
  7398. ) and GetNextInstruction(hp2, hp3) and
  7399. (hp3.typ = ait_instruction) and
  7400. (taicpu(hp3).opcode = A_JCC) and
  7401. (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
  7402. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7403. begin
  7404. { Check condition of jump }
  7405. { Always true? }
  7406. if condition_in(C_E, taicpu(hp3).condition) then
  7407. begin
  7408. { Copy label symbol and obtain matching label entry for the
  7409. conditional jump, as this will be our destination}
  7410. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7411. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7412. Result := True;
  7413. end
  7414. { Always false? }
  7415. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7416. begin
  7417. { This is only worth it if there's a jump to take }
  7418. case hp2.typ of
  7419. ait_instruction:
  7420. begin
  7421. if taicpu(hp2).opcode = A_JMP then
  7422. begin
  7423. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7424. { An unconditional jump follows the conditional jump which will always be false,
  7425. so use this jump's destination for the new jump }
  7426. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7427. Result := True;
  7428. end
  7429. else if taicpu(hp2).opcode = A_JCC then
  7430. begin
  7431. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7432. if condition_in(C_E, taicpu(hp2).condition) then
  7433. begin
  7434. { A second conditional jump follows the conditional jump which will always be false,
  7435. while the second jump is always True, so use this jump's destination for the new jump }
  7436. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7437. Result := True;
  7438. end;
  7439. { Don't risk it if the jump isn't always true (Result remains False) }
  7440. end;
  7441. end;
  7442. else
  7443. { If anything else don't optimise };
  7444. end;
  7445. end;
  7446. if Result then
  7447. begin
  7448. { Just so we have something to insert as a paremeter}
  7449. reference_reset(NewRef, 1, []);
  7450. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7451. { Now actually load the correct parameter (this also
  7452. increases the reference count) }
  7453. NewInstr.loadsymbol(0, DestLabel, 0);
  7454. { Get instruction before original label (may not be p under -O3) }
  7455. if not GetLastInstruction(hp1, hp2) then
  7456. { Shouldn't fail here }
  7457. InternalError(2021040701);
  7458. AsmL.InsertAfter(NewInstr, hp2);
  7459. { Add new alignment field }
  7460. (* AsmL.InsertAfter(
  7461. cai_align.create_max(
  7462. current_settings.alignment.jumpalign,
  7463. current_settings.alignment.jumpalignskipmax
  7464. ),
  7465. NewInstr
  7466. ); *)
  7467. end;
  7468. Exit;
  7469. end;
  7470. end;
  7471. else
  7472. ;
  7473. end;
  7474. end;
  7475. if not GetNextInstruction(p, hp1) then
  7476. Exit;
  7477. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7478. and DoMovCmpMemOpt(p, hp1, True) then
  7479. begin
  7480. Result := True;
  7481. Exit;
  7482. end
  7483. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7484. begin
  7485. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7486. further, but we can't just put this jump optimisation in pass 1
  7487. because it tends to perform worse when conditional jumps are
  7488. nearby (e.g. when converting CMOV instructions). [Kit] }
  7489. if OptPass2JMP(hp1) then
  7490. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7491. Result := OptPass1MOV(p)
  7492. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7493. returned True and the instruction is still a MOV, thus checking
  7494. the optimisations below }
  7495. { If OptPass2JMP returned False, no optimisations were done to
  7496. the jump and there are no further optimisations that can be done
  7497. to the MOV instruction on this pass }
  7498. end
  7499. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7500. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7501. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7502. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7503. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7504. begin
  7505. { Change:
  7506. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7507. addl/q $x,%reg2 subl/q $x,%reg2
  7508. To:
  7509. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7510. }
  7511. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7512. { be lazy, checking separately for sub would be slightly better }
  7513. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7514. begin
  7515. TransferUsedRegs(TmpUsedRegs);
  7516. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7517. if TryMovArith2Lea(hp1) then
  7518. begin
  7519. Result := True;
  7520. Exit;
  7521. end
  7522. end
  7523. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7524. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7525. { Same as above, but also adds or subtracts to %reg2 in between.
  7526. It's still valid as long as the flags aren't in use }
  7527. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7528. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7529. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7530. { be lazy, checking separately for sub would be slightly better }
  7531. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7532. begin
  7533. TransferUsedRegs(TmpUsedRegs);
  7534. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7535. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7536. if TryMovArith2Lea(hp2) then
  7537. begin
  7538. Result := True;
  7539. Exit;
  7540. end;
  7541. end;
  7542. end
  7543. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7544. {$ifdef x86_64}
  7545. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7546. {$else x86_64}
  7547. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7548. {$endif x86_64}
  7549. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7550. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7551. { mov reg1, reg2 mov reg1, reg2
  7552. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7553. begin
  7554. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7555. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7556. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7557. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7558. TransferUsedRegs(TmpUsedRegs);
  7559. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7560. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7561. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7562. then
  7563. begin
  7564. RemoveCurrentP(p, hp1);
  7565. Result:=true;
  7566. end;
  7567. exit;
  7568. end
  7569. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7570. IsXCHGAcceptable and
  7571. { XCHG doesn't support 8-byte registers }
  7572. (taicpu(p).opsize <> S_B) and
  7573. MatchInstruction(hp1, A_MOV, []) and
  7574. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7575. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7576. GetNextInstruction(hp1, hp2) and
  7577. MatchInstruction(hp2, A_MOV, []) and
  7578. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7579. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7580. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7581. begin
  7582. { mov %reg1,%reg2
  7583. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7584. mov %reg2,%reg3
  7585. (%reg2 not used afterwards)
  7586. Note that xchg takes 3 cycles to execute, and generally mov's take
  7587. only one cycle apiece, but the first two mov's can be executed in
  7588. parallel, only taking 2 cycles overall. Older processors should
  7589. therefore only optimise for size. [Kit]
  7590. }
  7591. TransferUsedRegs(TmpUsedRegs);
  7592. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7593. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7594. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7595. begin
  7596. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7597. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7598. taicpu(hp1).opcode := A_XCHG;
  7599. RemoveCurrentP(p, hp1);
  7600. RemoveInstruction(hp2);
  7601. Result := True;
  7602. Exit;
  7603. end;
  7604. end
  7605. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7606. MatchInstruction(hp1, A_SAR, []) then
  7607. begin
  7608. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7609. begin
  7610. { the use of %edx also covers the opsize being S_L }
  7611. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7612. begin
  7613. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7614. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7615. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7616. begin
  7617. { Change:
  7618. movl %eax,%edx
  7619. sarl $31,%edx
  7620. To:
  7621. cltd
  7622. }
  7623. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7624. RemoveInstruction(hp1);
  7625. taicpu(p).opcode := A_CDQ;
  7626. taicpu(p).opsize := S_NO;
  7627. taicpu(p).clearop(1);
  7628. taicpu(p).clearop(0);
  7629. taicpu(p).ops:=0;
  7630. Result := True;
  7631. end
  7632. else if (cs_opt_size in current_settings.optimizerswitches) and
  7633. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7634. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7635. begin
  7636. { Change:
  7637. movl %edx,%eax
  7638. sarl $31,%edx
  7639. To:
  7640. movl %edx,%eax
  7641. cltd
  7642. Note that this creates a dependency between the two instructions,
  7643. so only perform if optimising for size.
  7644. }
  7645. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7646. taicpu(hp1).opcode := A_CDQ;
  7647. taicpu(hp1).opsize := S_NO;
  7648. taicpu(hp1).clearop(1);
  7649. taicpu(hp1).clearop(0);
  7650. taicpu(hp1).ops:=0;
  7651. end;
  7652. {$ifndef x86_64}
  7653. end
  7654. { Don't bother if CMOV is supported, because a more optimal
  7655. sequence would have been generated for the Abs() intrinsic }
  7656. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7657. { the use of %eax also covers the opsize being S_L }
  7658. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7659. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7660. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7661. GetNextInstruction(hp1, hp2) and
  7662. MatchInstruction(hp2, A_XOR, [S_L]) and
  7663. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7664. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7665. GetNextInstruction(hp2, hp3) and
  7666. MatchInstruction(hp3, A_SUB, [S_L]) and
  7667. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7668. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7669. begin
  7670. { Change:
  7671. movl %eax,%edx
  7672. sarl $31,%eax
  7673. xorl %eax,%edx
  7674. subl %eax,%edx
  7675. (Instruction that uses %edx)
  7676. (%eax deallocated)
  7677. (%edx deallocated)
  7678. To:
  7679. cltd
  7680. xorl %edx,%eax <-- Note the registers have swapped
  7681. subl %edx,%eax
  7682. (Instruction that uses %eax) <-- %eax rather than %edx
  7683. }
  7684. TransferUsedRegs(TmpUsedRegs);
  7685. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7686. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7687. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7688. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7689. begin
  7690. if GetNextInstruction(hp3, hp4) and
  7691. not RegModifiedByInstruction(NR_EDX, hp4) and
  7692. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7693. begin
  7694. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7695. taicpu(p).opcode := A_CDQ;
  7696. taicpu(p).clearop(1);
  7697. taicpu(p).clearop(0);
  7698. taicpu(p).ops:=0;
  7699. RemoveInstruction(hp1);
  7700. taicpu(hp2).loadreg(0, NR_EDX);
  7701. taicpu(hp2).loadreg(1, NR_EAX);
  7702. taicpu(hp3).loadreg(0, NR_EDX);
  7703. taicpu(hp3).loadreg(1, NR_EAX);
  7704. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7705. { Convert references in the following instruction (hp4) from %edx to %eax }
  7706. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7707. with taicpu(hp4).oper[OperIdx]^ do
  7708. case typ of
  7709. top_reg:
  7710. if getsupreg(reg) = RS_EDX then
  7711. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7712. top_ref:
  7713. begin
  7714. if getsupreg(reg) = RS_EDX then
  7715. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7716. if getsupreg(reg) = RS_EDX then
  7717. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7718. end;
  7719. else
  7720. ;
  7721. end;
  7722. end;
  7723. end;
  7724. {$else x86_64}
  7725. end;
  7726. end
  7727. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7728. { the use of %rdx also covers the opsize being S_Q }
  7729. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7730. begin
  7731. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7732. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7733. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7734. begin
  7735. { Change:
  7736. movq %rax,%rdx
  7737. sarq $63,%rdx
  7738. To:
  7739. cqto
  7740. }
  7741. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7742. RemoveInstruction(hp1);
  7743. taicpu(p).opcode := A_CQO;
  7744. taicpu(p).opsize := S_NO;
  7745. taicpu(p).clearop(1);
  7746. taicpu(p).clearop(0);
  7747. taicpu(p).ops:=0;
  7748. Result := True;
  7749. end
  7750. else if (cs_opt_size in current_settings.optimizerswitches) and
  7751. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7752. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7753. begin
  7754. { Change:
  7755. movq %rdx,%rax
  7756. sarq $63,%rdx
  7757. To:
  7758. movq %rdx,%rax
  7759. cqto
  7760. Note that this creates a dependency between the two instructions,
  7761. so only perform if optimising for size.
  7762. }
  7763. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7764. taicpu(hp1).opcode := A_CQO;
  7765. taicpu(hp1).opsize := S_NO;
  7766. taicpu(hp1).clearop(1);
  7767. taicpu(hp1).clearop(0);
  7768. taicpu(hp1).ops:=0;
  7769. {$endif x86_64}
  7770. end;
  7771. end;
  7772. end
  7773. else if MatchInstruction(hp1, A_MOV, []) and
  7774. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7775. { Though "GetNextInstruction" could be factored out, along with
  7776. the instructions that depend on hp2, it is an expensive call that
  7777. should be delayed for as long as possible, hence we do cheaper
  7778. checks first that are likely to be False. [Kit] }
  7779. begin
  7780. if (
  7781. (
  7782. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7783. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7784. (
  7785. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7786. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7787. )
  7788. ) or
  7789. (
  7790. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7791. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7792. (
  7793. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7794. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7795. )
  7796. )
  7797. ) and
  7798. GetNextInstruction(hp1, hp2) and
  7799. MatchInstruction(hp2, A_SAR, []) and
  7800. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7801. begin
  7802. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7803. begin
  7804. { Change:
  7805. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7806. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7807. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7808. To:
  7809. movl r/m,%eax <- Note the change in register
  7810. cltd
  7811. }
  7812. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7813. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7814. taicpu(p).loadreg(1, NR_EAX);
  7815. taicpu(hp1).opcode := A_CDQ;
  7816. taicpu(hp1).clearop(1);
  7817. taicpu(hp1).clearop(0);
  7818. taicpu(hp1).ops:=0;
  7819. RemoveInstruction(hp2);
  7820. (*
  7821. {$ifdef x86_64}
  7822. end
  7823. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7824. { This code sequence does not get generated - however it might become useful
  7825. if and when 128-bit signed integer types make an appearance, so the code
  7826. is kept here for when it is eventually needed. [Kit] }
  7827. (
  7828. (
  7829. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7830. (
  7831. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7832. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7833. )
  7834. ) or
  7835. (
  7836. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7837. (
  7838. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7839. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7840. )
  7841. )
  7842. ) and
  7843. GetNextInstruction(hp1, hp2) and
  7844. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7845. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7846. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7847. begin
  7848. { Change:
  7849. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7850. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7851. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7852. To:
  7853. movq r/m,%rax <- Note the change in register
  7854. cqto
  7855. }
  7856. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7857. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7858. taicpu(p).loadreg(1, NR_RAX);
  7859. taicpu(hp1).opcode := A_CQO;
  7860. taicpu(hp1).clearop(1);
  7861. taicpu(hp1).clearop(0);
  7862. taicpu(hp1).ops:=0;
  7863. RemoveInstruction(hp2);
  7864. {$endif x86_64}
  7865. *)
  7866. end;
  7867. end;
  7868. {$ifdef x86_64}
  7869. end
  7870. else if (taicpu(p).opsize = S_L) and
  7871. (taicpu(p).oper[1]^.typ = top_reg) and
  7872. (
  7873. MatchInstruction(hp1, A_MOV,[]) and
  7874. (taicpu(hp1).opsize = S_L) and
  7875. (taicpu(hp1).oper[1]^.typ = top_reg)
  7876. ) and (
  7877. GetNextInstruction(hp1, hp2) and
  7878. (tai(hp2).typ=ait_instruction) and
  7879. (taicpu(hp2).opsize = S_Q) and
  7880. (
  7881. (
  7882. MatchInstruction(hp2, A_ADD,[]) and
  7883. (taicpu(hp2).opsize = S_Q) and
  7884. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7885. (
  7886. (
  7887. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7888. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7889. ) or (
  7890. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7891. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7892. )
  7893. )
  7894. ) or (
  7895. MatchInstruction(hp2, A_LEA,[]) and
  7896. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7897. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7898. (
  7899. (
  7900. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7901. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7902. ) or (
  7903. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7904. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7905. )
  7906. ) and (
  7907. (
  7908. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7909. ) or (
  7910. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7911. )
  7912. )
  7913. )
  7914. )
  7915. ) and (
  7916. GetNextInstruction(hp2, hp3) and
  7917. MatchInstruction(hp3, A_SHR,[]) and
  7918. (taicpu(hp3).opsize = S_Q) and
  7919. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7920. (taicpu(hp3).oper[0]^.val = 1) and
  7921. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7922. ) then
  7923. begin
  7924. { Change movl x, reg1d movl x, reg1d
  7925. movl y, reg2d movl y, reg2d
  7926. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7927. shrq $1, reg1q shrq $1, reg1q
  7928. ( reg1d and reg2d can be switched around in the first two instructions )
  7929. To movl x, reg1d
  7930. addl y, reg1d
  7931. rcrl $1, reg1d
  7932. This corresponds to the common expression (x + y) shr 1, where
  7933. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7934. smaller code, but won't account for x + y causing an overflow). [Kit]
  7935. }
  7936. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7937. { Change first MOV command to have the same register as the final output }
  7938. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7939. else
  7940. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7941. { Change second MOV command to an ADD command. This is easier than
  7942. converting the existing command because it means we don't have to
  7943. touch 'y', which might be a complicated reference, and also the
  7944. fact that the third command might either be ADD or LEA. [Kit] }
  7945. taicpu(hp1).opcode := A_ADD;
  7946. { Delete old ADD/LEA instruction }
  7947. RemoveInstruction(hp2);
  7948. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7949. taicpu(hp3).opcode := A_RCR;
  7950. taicpu(hp3).changeopsize(S_L);
  7951. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7952. {$endif x86_64}
  7953. end;
  7954. end;
  7955. {$push}
  7956. {$q-}{$r-}
  7957. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7958. var
  7959. ThisReg: TRegister;
  7960. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7961. TargetSubReg: TSubRegister;
  7962. hp1, hp2: tai;
  7963. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  7964. { Store list of found instructions so we don't have to call
  7965. GetNextInstructionUsingReg multiple times }
  7966. InstrList: array of taicpu;
  7967. InstrMax, Index: Integer;
  7968. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7969. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7970. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7971. WorkingValue: TCgInt;
  7972. PreMessage: string;
  7973. { Data flow analysis }
  7974. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7975. BitwiseOnly, OrXorUsed,
  7976. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7977. function CheckOverflowConditions: Boolean;
  7978. begin
  7979. Result := True;
  7980. if (TestValSignedMax > SignedUpperLimit) then
  7981. UpperSignedOverflow := True;
  7982. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7983. LowerSignedOverflow := True;
  7984. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7985. LowerUnsignedOverflow := True;
  7986. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7987. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7988. begin
  7989. { Absolute overflow }
  7990. Result := False;
  7991. Exit;
  7992. end;
  7993. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7994. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7995. ShiftDownOverflow := True;
  7996. if (TestValMin < 0) or (TestValMax < 0) then
  7997. begin
  7998. LowerUnsignedOverflow := True;
  7999. UpperUnsignedOverflow := True;
  8000. end;
  8001. end;
  8002. function AdjustInitialLoadAndSize: Boolean;
  8003. begin
  8004. Result := False;
  8005. if not p_removed then
  8006. begin
  8007. if TargetSize = MinSize then
  8008. begin
  8009. { Convert the input MOVZX to a MOV }
  8010. if (taicpu(p).oper[0]^.typ = top_reg) and
  8011. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8012. begin
  8013. { Or remove it completely! }
  8014. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8015. RemoveCurrentP(p);
  8016. p_removed := True;
  8017. end
  8018. else
  8019. begin
  8020. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8021. taicpu(p).opcode := A_MOV;
  8022. taicpu(p).oper[1]^.reg := ThisReg;
  8023. taicpu(p).opsize := TargetSize;
  8024. end;
  8025. Result := True;
  8026. end
  8027. else if TargetSize <> MaxSize then
  8028. begin
  8029. case MaxSize of
  8030. S_L:
  8031. if TargetSize = S_W then
  8032. begin
  8033. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8034. taicpu(p).opsize := S_BW;
  8035. taicpu(p).oper[1]^.reg := ThisReg;
  8036. Result := True;
  8037. end
  8038. else
  8039. InternalError(2020112341);
  8040. S_W:
  8041. if TargetSize = S_L then
  8042. begin
  8043. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8044. taicpu(p).opsize := S_BL;
  8045. taicpu(p).oper[1]^.reg := ThisReg;
  8046. Result := True;
  8047. end
  8048. else
  8049. InternalError(2020112342);
  8050. else
  8051. ;
  8052. end;
  8053. end
  8054. else if not hp1_removed and not RegInUse then
  8055. begin
  8056. { If we have something like:
  8057. movzbl (oper),%regd
  8058. add x, %regd
  8059. movzbl %regb, %regd
  8060. We can reduce the register size to the input of the final
  8061. movzbl instruction. Overflows won't have any effect.
  8062. }
  8063. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8064. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8065. begin
  8066. TargetSize := S_B;
  8067. setsubreg(ThisReg, R_SUBL);
  8068. Result := True;
  8069. end
  8070. else if (taicpu(p).opsize = S_WL) and
  8071. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8072. begin
  8073. TargetSize := S_W;
  8074. setsubreg(ThisReg, R_SUBW);
  8075. Result := True;
  8076. end;
  8077. if Result then
  8078. begin
  8079. { Convert the input MOVZX to a MOV }
  8080. if (taicpu(p).oper[0]^.typ = top_reg) and
  8081. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8082. begin
  8083. { Or remove it completely! }
  8084. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8085. RemoveCurrentP(p);
  8086. p_removed := True;
  8087. end
  8088. else
  8089. begin
  8090. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8091. taicpu(p).opcode := A_MOV;
  8092. taicpu(p).oper[1]^.reg := ThisReg;
  8093. taicpu(p).opsize := TargetSize;
  8094. end;
  8095. end;
  8096. end;
  8097. end;
  8098. end;
  8099. procedure AdjustFinalLoad;
  8100. begin
  8101. if not LowerUnsignedOverflow then
  8102. begin
  8103. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8104. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8105. begin
  8106. { Convert the output MOVZX to a MOV }
  8107. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8108. begin
  8109. { Or remove it completely! }
  8110. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8111. { Be careful; if p = hp1 and p was also removed, p
  8112. will become a dangling pointer }
  8113. if p = hp1 then
  8114. begin
  8115. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8116. p_removed := True;
  8117. end
  8118. else
  8119. RemoveInstruction(hp1);
  8120. hp1_removed := True;
  8121. end
  8122. else
  8123. begin
  8124. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8125. taicpu(hp1).opcode := A_MOV;
  8126. taicpu(hp1).oper[0]^.reg := ThisReg;
  8127. taicpu(hp1).opsize := TargetSize;
  8128. end;
  8129. end
  8130. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8131. begin
  8132. { Need to change the size of the output }
  8133. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8134. taicpu(hp1).oper[0]^.reg := ThisReg;
  8135. taicpu(hp1).opsize := S_BL;
  8136. end;
  8137. end;
  8138. end;
  8139. function CompressInstructions: Boolean;
  8140. var
  8141. LocalIndex: Integer;
  8142. begin
  8143. Result := False;
  8144. { The objective here is to try to find a combination that
  8145. removes one of the MOV/Z instructions. }
  8146. if (
  8147. (taicpu(p).oper[0]^.typ <> top_reg) or
  8148. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8149. ) and
  8150. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8151. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8152. begin
  8153. { Make a preference to remove the second MOVZX instruction }
  8154. case taicpu(hp1).opsize of
  8155. S_BL, S_WL:
  8156. begin
  8157. TargetSize := S_L;
  8158. TargetSubReg := R_SUBD;
  8159. end;
  8160. S_BW:
  8161. begin
  8162. TargetSize := S_W;
  8163. TargetSubReg := R_SUBW;
  8164. end;
  8165. else
  8166. InternalError(2020112302);
  8167. end;
  8168. end
  8169. else
  8170. begin
  8171. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8172. begin
  8173. { Exceeded lower bound but not upper bound }
  8174. TargetSize := MaxSize;
  8175. end
  8176. else if not LowerUnsignedOverflow then
  8177. begin
  8178. { Size didn't exceed lower bound }
  8179. TargetSize := MinSize;
  8180. end
  8181. else
  8182. Exit;
  8183. end;
  8184. case TargetSize of
  8185. S_B:
  8186. TargetSubReg := R_SUBL;
  8187. S_W:
  8188. TargetSubReg := R_SUBW;
  8189. S_L:
  8190. TargetSubReg := R_SUBD;
  8191. else
  8192. InternalError(2020112350);
  8193. end;
  8194. { Update the register to its new size }
  8195. setsubreg(ThisReg, TargetSubReg);
  8196. RegInUse := False;
  8197. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8198. begin
  8199. { Check to see if the active register is used afterwards;
  8200. if not, we can change it and make a saving. }
  8201. TransferUsedRegs(TmpUsedRegs);
  8202. { The target register may be marked as in use to cross
  8203. a jump to a distant label, so exclude it }
  8204. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8205. hp2 := p;
  8206. repeat
  8207. { Explicitly check for the excluded register (don't include the first
  8208. instruction as it may be reading from here }
  8209. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8210. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8211. begin
  8212. RegInUse := True;
  8213. Break;
  8214. end;
  8215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8216. if not GetNextInstruction(hp2, hp2) then
  8217. InternalError(2020112340);
  8218. until (hp2 = hp1);
  8219. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8220. { We might still be able to get away with this }
  8221. RegInUse := not
  8222. (
  8223. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8224. (hp2.typ = ait_instruction) and
  8225. (
  8226. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8227. instruction that doesn't actually contain ThisReg }
  8228. (cs_opt_level3 in current_settings.optimizerswitches) or
  8229. RegInInstruction(ThisReg, hp2)
  8230. ) and
  8231. RegLoadedWithNewValue(ThisReg, hp2)
  8232. );
  8233. if not RegInUse then
  8234. begin
  8235. { Force the register size to the same as this instruction so it can be removed}
  8236. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8237. begin
  8238. TargetSize := S_L;
  8239. TargetSubReg := R_SUBD;
  8240. end
  8241. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8242. begin
  8243. TargetSize := S_W;
  8244. TargetSubReg := R_SUBW;
  8245. end;
  8246. ThisReg := taicpu(hp1).oper[1]^.reg;
  8247. setsubreg(ThisReg, TargetSubReg);
  8248. RegChanged := True;
  8249. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8250. TransferUsedRegs(TmpUsedRegs);
  8251. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8252. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8253. if p = hp1 then
  8254. begin
  8255. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8256. p_removed := True;
  8257. end
  8258. else
  8259. RemoveInstruction(hp1);
  8260. hp1_removed := True;
  8261. { Instruction will become "mov %reg,%reg" }
  8262. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8263. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8264. begin
  8265. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8266. RemoveCurrentP(p);
  8267. p_removed := True;
  8268. end
  8269. else
  8270. taicpu(p).oper[1]^.reg := ThisReg;
  8271. Result := True;
  8272. end
  8273. else
  8274. begin
  8275. if TargetSize <> MaxSize then
  8276. begin
  8277. { Since the register is in use, we have to force it to
  8278. MaxSize otherwise part of it may become undefined later on }
  8279. TargetSize := MaxSize;
  8280. case TargetSize of
  8281. S_B:
  8282. TargetSubReg := R_SUBL;
  8283. S_W:
  8284. TargetSubReg := R_SUBW;
  8285. S_L:
  8286. TargetSubReg := R_SUBD;
  8287. else
  8288. InternalError(2020112351);
  8289. end;
  8290. setsubreg(ThisReg, TargetSubReg);
  8291. end;
  8292. AdjustFinalLoad;
  8293. end;
  8294. end
  8295. else
  8296. AdjustFinalLoad;
  8297. Result := AdjustInitialLoadAndSize or Result;
  8298. { Now go through every instruction we found and change the
  8299. size. If TargetSize = MaxSize, then almost no changes are
  8300. needed and Result can remain False if it hasn't been set
  8301. yet.
  8302. If RegChanged is True, then the register requires changing
  8303. and so the point about TargetSize = MaxSize doesn't apply. }
  8304. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8305. begin
  8306. for LocalIndex := 0 to InstrMax do
  8307. begin
  8308. { If p_removed is true, then the original MOV/Z was removed
  8309. and removing the AND instruction may not be safe if it
  8310. appears first }
  8311. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8312. InternalError(2020112310);
  8313. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8314. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8315. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8316. InstrList[LocalIndex].opsize := TargetSize;
  8317. end;
  8318. Result := True;
  8319. end;
  8320. end;
  8321. begin
  8322. Result := False;
  8323. p_removed := False;
  8324. hp1_removed := False;
  8325. ThisReg := taicpu(p).oper[1]^.reg;
  8326. { Check for:
  8327. movs/z ###,%ecx (or %cx or %rcx)
  8328. ...
  8329. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8330. (dealloc %ecx)
  8331. Change to:
  8332. mov ###,%cl (if ### = %cl, then remove completely)
  8333. ...
  8334. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8335. }
  8336. if (getsupreg(ThisReg) = RS_ECX) and
  8337. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8338. (hp1.typ = ait_instruction) and
  8339. (
  8340. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8341. instruction that doesn't actually contain ECX }
  8342. (cs_opt_level3 in current_settings.optimizerswitches) or
  8343. RegInInstruction(NR_ECX, hp1) or
  8344. (
  8345. { It's common for the shift/rotate's read/write register to be
  8346. initialised in between, so under -O2 and under, search ahead
  8347. one more instruction
  8348. }
  8349. GetNextInstruction(hp1, hp1) and
  8350. (hp1.typ = ait_instruction) and
  8351. RegInInstruction(NR_ECX, hp1)
  8352. )
  8353. ) and
  8354. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8355. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8356. begin
  8357. TransferUsedRegs(TmpUsedRegs);
  8358. hp2 := p;
  8359. repeat
  8360. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8361. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8362. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8363. begin
  8364. case taicpu(p).opsize of
  8365. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8366. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8367. begin
  8368. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8369. RemoveCurrentP(p);
  8370. end
  8371. else
  8372. begin
  8373. taicpu(p).opcode := A_MOV;
  8374. taicpu(p).opsize := S_B;
  8375. taicpu(p).oper[1]^.reg := NR_CL;
  8376. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8377. end;
  8378. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8379. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8380. begin
  8381. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8382. RemoveCurrentP(p);
  8383. end
  8384. else
  8385. begin
  8386. taicpu(p).opcode := A_MOV;
  8387. taicpu(p).opsize := S_W;
  8388. taicpu(p).oper[1]^.reg := NR_CX;
  8389. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8390. end;
  8391. {$ifdef x86_64}
  8392. S_LQ:
  8393. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8394. begin
  8395. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8396. RemoveCurrentP(p);
  8397. end
  8398. else
  8399. begin
  8400. taicpu(p).opcode := A_MOV;
  8401. taicpu(p).opsize := S_L;
  8402. taicpu(p).oper[1]^.reg := NR_ECX;
  8403. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8404. end;
  8405. {$endif x86_64}
  8406. else
  8407. InternalError(2021120401);
  8408. end;
  8409. Result := True;
  8410. Exit;
  8411. end;
  8412. end;
  8413. { This is anything but quick! }
  8414. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8415. Exit;
  8416. SetLength(InstrList, 0);
  8417. InstrMax := -1;
  8418. case taicpu(p).opsize of
  8419. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8420. begin
  8421. {$if defined(i386) or defined(i8086)}
  8422. { If the target size is 8-bit, make sure we can actually encode it }
  8423. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8424. Exit;
  8425. {$endif i386 or i8086}
  8426. LowerLimit := $FF;
  8427. SignedLowerLimit := $7F;
  8428. SignedLowerLimitBottom := -128;
  8429. MinSize := S_B;
  8430. if taicpu(p).opsize = S_BW then
  8431. begin
  8432. MaxSize := S_W;
  8433. UpperLimit := $FFFF;
  8434. SignedUpperLimit := $7FFF;
  8435. SignedUpperLimitBottom := -32768;
  8436. end
  8437. else
  8438. begin
  8439. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8440. MaxSize := S_L;
  8441. UpperLimit := $FFFFFFFF;
  8442. SignedUpperLimit := $7FFFFFFF;
  8443. SignedUpperLimitBottom := -2147483648;
  8444. end;
  8445. end;
  8446. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8447. begin
  8448. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8449. LowerLimit := $FFFF;
  8450. SignedLowerLimit := $7FFF;
  8451. SignedLowerLimitBottom := -32768;
  8452. UpperLimit := $FFFFFFFF;
  8453. SignedUpperLimit := $7FFFFFFF;
  8454. SignedUpperLimitBottom := -2147483648;
  8455. MinSize := S_W;
  8456. MaxSize := S_L;
  8457. end;
  8458. {$ifdef x86_64}
  8459. S_LQ:
  8460. begin
  8461. { Both the lower and upper limits are set to 32-bit. If a limit
  8462. is breached, then optimisation is impossible }
  8463. LowerLimit := $FFFFFFFF;
  8464. SignedLowerLimit := $7FFFFFFF;
  8465. SignedLowerLimitBottom := -2147483648;
  8466. UpperLimit := $FFFFFFFF;
  8467. SignedUpperLimit := $7FFFFFFF;
  8468. SignedUpperLimitBottom := -2147483648;
  8469. MinSize := S_L;
  8470. MaxSize := S_L;
  8471. end;
  8472. {$endif x86_64}
  8473. else
  8474. InternalError(2020112301);
  8475. end;
  8476. TestValMin := 0;
  8477. TestValMax := LowerLimit;
  8478. TestValSignedMax := SignedLowerLimit;
  8479. TryShiftDownLimit := LowerLimit;
  8480. TryShiftDown := S_NO;
  8481. ShiftDownOverflow := False;
  8482. RegChanged := False;
  8483. BitwiseOnly := True;
  8484. OrXorUsed := False;
  8485. UpperSignedOverflow := False;
  8486. LowerSignedOverflow := False;
  8487. UpperUnsignedOverflow := False;
  8488. LowerUnsignedOverflow := False;
  8489. hp1 := p;
  8490. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8491. (hp1.typ = ait_instruction) and
  8492. (
  8493. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8494. instruction that doesn't actually contain ThisReg }
  8495. (cs_opt_level3 in current_settings.optimizerswitches) or
  8496. { This allows this Movx optimisation to work through the SETcc instructions
  8497. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8498. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8499. skip over these SETcc instructions). }
  8500. (taicpu(hp1).opcode = A_SETcc) or
  8501. RegInInstruction(ThisReg, hp1)
  8502. ) do
  8503. begin
  8504. case taicpu(hp1).opcode of
  8505. A_INC,A_DEC:
  8506. begin
  8507. { Has to be an exact match on the register }
  8508. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8509. Break;
  8510. if taicpu(hp1).opcode = A_INC then
  8511. begin
  8512. Inc(TestValMin);
  8513. Inc(TestValMax);
  8514. Inc(TestValSignedMax);
  8515. end
  8516. else
  8517. begin
  8518. Dec(TestValMin);
  8519. Dec(TestValMax);
  8520. Dec(TestValSignedMax);
  8521. end;
  8522. end;
  8523. A_TEST, A_CMP:
  8524. begin
  8525. if (
  8526. { Too high a risk of non-linear behaviour that breaks DFA
  8527. here, unless it's cmp $0,%reg, which is equivalent to
  8528. test %reg,%reg }
  8529. OrXorUsed and
  8530. (taicpu(hp1).opcode = A_CMP) and
  8531. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8532. ) or
  8533. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8534. { Has to be an exact match on the register }
  8535. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8536. (
  8537. { Permit "test %reg,%reg" }
  8538. (taicpu(hp1).opcode = A_TEST) and
  8539. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8540. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8541. ) or
  8542. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8543. { Make sure the comparison value is not smaller than the
  8544. smallest allowed signed value for the minimum size (e.g.
  8545. -128 for 8-bit) }
  8546. not (
  8547. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8548. { Is it in the negative range? }
  8549. (
  8550. (taicpu(hp1).oper[0]^.val < 0) and
  8551. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8552. )
  8553. ) then
  8554. Break;
  8555. { Check to see if the active register is used afterwards }
  8556. TransferUsedRegs(TmpUsedRegs);
  8557. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8558. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8559. begin
  8560. { Make sure the comparison or any previous instructions
  8561. hasn't pushed the test values outside of the range of
  8562. MinSize }
  8563. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8564. begin
  8565. { Exceeded lower bound but not upper bound }
  8566. Exit;
  8567. end
  8568. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8569. begin
  8570. { Size didn't exceed lower bound }
  8571. TargetSize := MinSize;
  8572. end
  8573. else
  8574. Break;
  8575. case TargetSize of
  8576. S_B:
  8577. TargetSubReg := R_SUBL;
  8578. S_W:
  8579. TargetSubReg := R_SUBW;
  8580. S_L:
  8581. TargetSubReg := R_SUBD;
  8582. else
  8583. InternalError(2021051002);
  8584. end;
  8585. if TargetSize <> MaxSize then
  8586. begin
  8587. { Update the register to its new size }
  8588. setsubreg(ThisReg, TargetSubReg);
  8589. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8590. taicpu(hp1).oper[1]^.reg := ThisReg;
  8591. taicpu(hp1).opsize := TargetSize;
  8592. { Convert the input MOVZX to a MOV if necessary }
  8593. AdjustInitialLoadAndSize;
  8594. if (InstrMax >= 0) then
  8595. begin
  8596. for Index := 0 to InstrMax do
  8597. begin
  8598. { If p_removed is true, then the original MOV/Z was removed
  8599. and removing the AND instruction may not be safe if it
  8600. appears first }
  8601. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8602. InternalError(2020112311);
  8603. if InstrList[Index].oper[0]^.typ = top_reg then
  8604. InstrList[Index].oper[0]^.reg := ThisReg;
  8605. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8606. InstrList[Index].opsize := MinSize;
  8607. end;
  8608. end;
  8609. Result := True;
  8610. end;
  8611. Exit;
  8612. end;
  8613. end;
  8614. A_SETcc:
  8615. begin
  8616. { This allows this Movx optimisation to work through the SETcc instructions
  8617. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8618. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8619. skip over these SETcc instructions). }
  8620. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8621. { Of course, break out if the current register is used }
  8622. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8623. Break
  8624. else
  8625. { We must use Continue so the instruction doesn't get added
  8626. to InstrList }
  8627. Continue;
  8628. end;
  8629. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8630. begin
  8631. if
  8632. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8633. { Has to be an exact match on the register }
  8634. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8635. (
  8636. (
  8637. (taicpu(hp1).oper[0]^.typ = top_const) and
  8638. (
  8639. (
  8640. (taicpu(hp1).opcode = A_SHL) and
  8641. (
  8642. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8643. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8644. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8645. )
  8646. ) or (
  8647. (taicpu(hp1).opcode <> A_SHL) and
  8648. (
  8649. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8650. { Is it in the negative range? }
  8651. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8652. )
  8653. )
  8654. )
  8655. ) or (
  8656. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8657. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8658. )
  8659. ) then
  8660. Break;
  8661. { Only process OR and XOR if there are only bitwise operations,
  8662. since otherwise they can too easily fool the data flow
  8663. analysis (they can cause non-linear behaviour) }
  8664. case taicpu(hp1).opcode of
  8665. A_ADD:
  8666. begin
  8667. if OrXorUsed then
  8668. { Too high a risk of non-linear behaviour that breaks DFA here }
  8669. Break
  8670. else
  8671. BitwiseOnly := False;
  8672. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8673. begin
  8674. TestValMin := TestValMin * 2;
  8675. TestValMax := TestValMax * 2;
  8676. TestValSignedMax := TestValSignedMax * 2;
  8677. end
  8678. else
  8679. begin
  8680. WorkingValue := taicpu(hp1).oper[0]^.val;
  8681. TestValMin := TestValMin + WorkingValue;
  8682. TestValMax := TestValMax + WorkingValue;
  8683. TestValSignedMax := TestValSignedMax + WorkingValue;
  8684. end;
  8685. end;
  8686. A_SUB:
  8687. begin
  8688. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8689. begin
  8690. TestValMin := 0;
  8691. TestValMax := 0;
  8692. TestValSignedMax := 0;
  8693. end
  8694. else
  8695. begin
  8696. if OrXorUsed then
  8697. { Too high a risk of non-linear behaviour that breaks DFA here }
  8698. Break
  8699. else
  8700. BitwiseOnly := False;
  8701. WorkingValue := taicpu(hp1).oper[0]^.val;
  8702. TestValMin := TestValMin - WorkingValue;
  8703. TestValMax := TestValMax - WorkingValue;
  8704. TestValSignedMax := TestValSignedMax - WorkingValue;
  8705. end;
  8706. end;
  8707. A_AND:
  8708. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8709. begin
  8710. { we might be able to go smaller if AND appears first }
  8711. if InstrMax = -1 then
  8712. case MinSize of
  8713. S_B:
  8714. ;
  8715. S_W:
  8716. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8717. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8718. begin
  8719. TryShiftDown := S_B;
  8720. TryShiftDownLimit := $FF;
  8721. end;
  8722. S_L:
  8723. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8724. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8725. begin
  8726. TryShiftDown := S_B;
  8727. TryShiftDownLimit := $FF;
  8728. end
  8729. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8730. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8731. begin
  8732. TryShiftDown := S_W;
  8733. TryShiftDownLimit := $FFFF;
  8734. end;
  8735. else
  8736. InternalError(2020112320);
  8737. end;
  8738. WorkingValue := taicpu(hp1).oper[0]^.val;
  8739. TestValMin := TestValMin and WorkingValue;
  8740. TestValMax := TestValMax and WorkingValue;
  8741. TestValSignedMax := TestValSignedMax and WorkingValue;
  8742. end;
  8743. A_OR:
  8744. begin
  8745. if not BitwiseOnly then
  8746. Break;
  8747. OrXorUsed := True;
  8748. WorkingValue := taicpu(hp1).oper[0]^.val;
  8749. TestValMin := TestValMin or WorkingValue;
  8750. TestValMax := TestValMax or WorkingValue;
  8751. TestValSignedMax := TestValSignedMax or WorkingValue;
  8752. end;
  8753. A_XOR:
  8754. begin
  8755. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8756. begin
  8757. TestValMin := 0;
  8758. TestValMax := 0;
  8759. TestValSignedMax := 0;
  8760. end
  8761. else
  8762. begin
  8763. if not BitwiseOnly then
  8764. Break;
  8765. OrXorUsed := True;
  8766. WorkingValue := taicpu(hp1).oper[0]^.val;
  8767. TestValMin := TestValMin xor WorkingValue;
  8768. TestValMax := TestValMax xor WorkingValue;
  8769. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8770. end;
  8771. end;
  8772. A_SHL:
  8773. begin
  8774. BitwiseOnly := False;
  8775. WorkingValue := taicpu(hp1).oper[0]^.val;
  8776. TestValMin := TestValMin shl WorkingValue;
  8777. TestValMax := TestValMax shl WorkingValue;
  8778. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8779. end;
  8780. A_SHR,
  8781. { The first instruction was MOVZX, so the value won't be negative }
  8782. A_SAR:
  8783. begin
  8784. if InstrMax <> -1 then
  8785. BitwiseOnly := False
  8786. else
  8787. { we might be able to go smaller if SHR appears first }
  8788. case MinSize of
  8789. S_B:
  8790. ;
  8791. S_W:
  8792. if (taicpu(hp1).oper[0]^.val >= 8) then
  8793. begin
  8794. TryShiftDown := S_B;
  8795. TryShiftDownLimit := $FF;
  8796. TryShiftDownSignedLimit := $7F;
  8797. TryShiftDownSignedLimitLower := -128;
  8798. end;
  8799. S_L:
  8800. if (taicpu(hp1).oper[0]^.val >= 24) then
  8801. begin
  8802. TryShiftDown := S_B;
  8803. TryShiftDownLimit := $FF;
  8804. TryShiftDownSignedLimit := $7F;
  8805. TryShiftDownSignedLimitLower := -128;
  8806. end
  8807. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8808. begin
  8809. TryShiftDown := S_W;
  8810. TryShiftDownLimit := $FFFF;
  8811. TryShiftDownSignedLimit := $7FFF;
  8812. TryShiftDownSignedLimitLower := -32768;
  8813. end;
  8814. else
  8815. InternalError(2020112321);
  8816. end;
  8817. WorkingValue := taicpu(hp1).oper[0]^.val;
  8818. if taicpu(hp1).opcode = A_SAR then
  8819. begin
  8820. TestValMin := SarInt64(TestValMin, WorkingValue);
  8821. TestValMax := SarInt64(TestValMax, WorkingValue);
  8822. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8823. end
  8824. else
  8825. begin
  8826. TestValMin := TestValMin shr WorkingValue;
  8827. TestValMax := TestValMax shr WorkingValue;
  8828. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8829. end;
  8830. end;
  8831. else
  8832. InternalError(2020112303);
  8833. end;
  8834. end;
  8835. (*
  8836. A_IMUL:
  8837. case taicpu(hp1).ops of
  8838. 2:
  8839. begin
  8840. if not MatchOpType(hp1, top_reg, top_reg) or
  8841. { Has to be an exact match on the register }
  8842. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8843. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8844. Break;
  8845. TestValMin := TestValMin * TestValMin;
  8846. TestValMax := TestValMax * TestValMax;
  8847. TestValSignedMax := TestValSignedMax * TestValMax;
  8848. end;
  8849. 3:
  8850. begin
  8851. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8852. { Has to be an exact match on the register }
  8853. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8854. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8855. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8856. { Is it in the negative range? }
  8857. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8858. Break;
  8859. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8860. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8861. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8862. end;
  8863. else
  8864. Break;
  8865. end;
  8866. A_IDIV:
  8867. case taicpu(hp1).ops of
  8868. 3:
  8869. begin
  8870. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8871. { Has to be an exact match on the register }
  8872. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8873. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8874. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8875. { Is it in the negative range? }
  8876. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8877. Break;
  8878. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8879. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8880. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8881. end;
  8882. else
  8883. Break;
  8884. end;
  8885. *)
  8886. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8887. begin
  8888. { If there are no instructions in between, then we might be able to make a saving }
  8889. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8890. Break;
  8891. { We have something like:
  8892. movzbw %dl,%dx
  8893. ...
  8894. movswl %dx,%edx
  8895. Change the latter to a zero-extension then enter the
  8896. A_MOVZX case branch.
  8897. }
  8898. {$ifdef x86_64}
  8899. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8900. begin
  8901. { this becomes a zero extension from 32-bit to 64-bit, but
  8902. the upper 32 bits are already zero, so just delete the
  8903. instruction }
  8904. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8905. RemoveInstruction(hp1);
  8906. Result := True;
  8907. Exit;
  8908. end
  8909. else
  8910. {$endif x86_64}
  8911. begin
  8912. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8913. taicpu(hp1).opcode := A_MOVZX;
  8914. {$ifdef x86_64}
  8915. case taicpu(hp1).opsize of
  8916. S_BQ:
  8917. begin
  8918. taicpu(hp1).opsize := S_BL;
  8919. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8920. end;
  8921. S_WQ:
  8922. begin
  8923. taicpu(hp1).opsize := S_WL;
  8924. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8925. end;
  8926. S_LQ:
  8927. begin
  8928. taicpu(hp1).opcode := A_MOV;
  8929. taicpu(hp1).opsize := S_L;
  8930. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8931. { In this instance, we need to break out because the
  8932. instruction is no longer MOVZX or MOVSXD }
  8933. Result := True;
  8934. Exit;
  8935. end;
  8936. else
  8937. ;
  8938. end;
  8939. {$endif x86_64}
  8940. Result := CompressInstructions;
  8941. Exit;
  8942. end;
  8943. end;
  8944. A_MOVZX:
  8945. begin
  8946. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8947. Break;
  8948. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8949. begin
  8950. if (InstrMax = -1) and
  8951. { Will return false if the second parameter isn't ThisReg
  8952. (can happen on -O2 and under) }
  8953. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8954. begin
  8955. { The two MOVZX instructions are adjacent, so remove the first one }
  8956. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8957. RemoveCurrentP(p);
  8958. Result := True;
  8959. Exit;
  8960. end;
  8961. Break;
  8962. end;
  8963. Result := CompressInstructions;
  8964. Exit;
  8965. end;
  8966. else
  8967. { This includes ADC, SBB and IDIV }
  8968. Break;
  8969. end;
  8970. if not CheckOverflowConditions then
  8971. Break;
  8972. { Contains highest index (so instruction count - 1) }
  8973. Inc(InstrMax);
  8974. if InstrMax > High(InstrList) then
  8975. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8976. InstrList[InstrMax] := taicpu(hp1);
  8977. end;
  8978. end;
  8979. {$pop}
  8980. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8981. var
  8982. hp1 : tai;
  8983. begin
  8984. Result:=false;
  8985. if (taicpu(p).ops >= 2) and
  8986. ((taicpu(p).oper[0]^.typ = top_const) or
  8987. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8988. (taicpu(p).oper[1]^.typ = top_reg) and
  8989. ((taicpu(p).ops = 2) or
  8990. ((taicpu(p).oper[2]^.typ = top_reg) and
  8991. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8992. GetLastInstruction(p,hp1) and
  8993. MatchInstruction(hp1,A_MOV,[]) and
  8994. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8995. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8996. begin
  8997. TransferUsedRegs(TmpUsedRegs);
  8998. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8999. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9000. { change
  9001. mov reg1,reg2
  9002. imul y,reg2 to imul y,reg1,reg2 }
  9003. begin
  9004. taicpu(p).ops := 3;
  9005. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9006. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9007. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9008. RemoveInstruction(hp1);
  9009. result:=true;
  9010. end;
  9011. end;
  9012. end;
  9013. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9014. var
  9015. ThisLabel: TAsmLabel;
  9016. begin
  9017. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9018. ThisLabel.decrefs;
  9019. taicpu(p).opcode := A_RET;
  9020. taicpu(p).is_jmp := false;
  9021. taicpu(p).ops := taicpu(ret_p).ops;
  9022. case taicpu(ret_p).ops of
  9023. 0:
  9024. taicpu(p).clearop(0);
  9025. 1:
  9026. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9027. else
  9028. internalerror(2016041301);
  9029. end;
  9030. { If the original label is now dead, it might turn out that the label
  9031. immediately follows p. As a result, everything beyond it, which will
  9032. be just some final register configuration and a RET instruction, is
  9033. now dead code. [Kit] }
  9034. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9035. running RemoveDeadCodeAfterJump for each RET instruction, because
  9036. this optimisation rarely happens and most RETs appear at the end of
  9037. routines where there is nothing that can be stripped. [Kit] }
  9038. if not ThisLabel.is_used then
  9039. RemoveDeadCodeAfterJump(p);
  9040. end;
  9041. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9042. var
  9043. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9044. Unconditional, PotentialModified: Boolean;
  9045. OperPtr: POper;
  9046. NewRef: TReference;
  9047. InstrList: array of taicpu;
  9048. InstrMax, Index: Integer;
  9049. const
  9050. {$ifdef DEBUG_AOPTCPU}
  9051. SNoFlags: shortstring = ' so the flags aren''t modified';
  9052. {$else DEBUG_AOPTCPU}
  9053. SNoFlags = '';
  9054. {$endif DEBUG_AOPTCPU}
  9055. begin
  9056. Result:=false;
  9057. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9058. begin
  9059. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9060. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9061. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9062. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9063. GetNextInstruction(hp1, hp2) and
  9064. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9065. { Change from: To:
  9066. set(C) %reg j(~C) label
  9067. test %reg,%reg/cmp $0,%reg
  9068. je label
  9069. set(C) %reg j(C) label
  9070. test %reg,%reg/cmp $0,%reg
  9071. jne label
  9072. (Also do something similar with sete/setne instead of je/jne)
  9073. }
  9074. begin
  9075. { Before we do anything else, we need to check the instructions
  9076. in between SETcc and TEST to make sure they don't modify the
  9077. FLAGS register - if -O2 or under, there won't be any
  9078. instructions between SET and TEST }
  9079. TransferUsedRegs(TmpUsedRegs);
  9080. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9081. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9082. begin
  9083. next := p;
  9084. SetLength(InstrList, 0);
  9085. InstrMax := -1;
  9086. PotentialModified := False;
  9087. { Make a note of every instruction that modifies the FLAGS
  9088. register }
  9089. while GetNextInstruction(next, next) and (next <> hp1) do
  9090. begin
  9091. if next.typ <> ait_instruction then
  9092. { GetNextInstructionUsingReg should have returned False }
  9093. InternalError(2021051701);
  9094. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9095. begin
  9096. case taicpu(next).opcode of
  9097. A_SETcc,
  9098. A_CMOVcc,
  9099. A_Jcc:
  9100. begin
  9101. if PotentialModified then
  9102. { Not safe because the flags were modified earlier }
  9103. Exit
  9104. else
  9105. { Condition is the same as the initial SETcc, so this is safe
  9106. (don't add to instruction list though) }
  9107. Continue;
  9108. end;
  9109. A_ADD:
  9110. begin
  9111. if (taicpu(next).opsize = S_B) or
  9112. { LEA doesn't support 8-bit operands }
  9113. (taicpu(next).oper[1]^.typ <> top_reg) or
  9114. { Must write to a register }
  9115. (taicpu(next).oper[0]^.typ = top_ref) then
  9116. { Require a constant or a register }
  9117. Exit;
  9118. PotentialModified := True;
  9119. end;
  9120. A_SUB:
  9121. begin
  9122. if (taicpu(next).opsize = S_B) or
  9123. { LEA doesn't support 8-bit operands }
  9124. (taicpu(next).oper[1]^.typ <> top_reg) or
  9125. { Must write to a register }
  9126. (taicpu(next).oper[0]^.typ <> top_const) or
  9127. (taicpu(next).oper[0]^.val = $80000000) then
  9128. { Can't subtract a register with LEA - also
  9129. check that the value isn't -2^31, as this
  9130. can't be negated }
  9131. Exit;
  9132. PotentialModified := True;
  9133. end;
  9134. A_SAL,
  9135. A_SHL:
  9136. begin
  9137. if (taicpu(next).opsize = S_B) or
  9138. { LEA doesn't support 8-bit operands }
  9139. (taicpu(next).oper[1]^.typ <> top_reg) or
  9140. { Must write to a register }
  9141. (taicpu(next).oper[0]^.typ <> top_const) or
  9142. (taicpu(next).oper[0]^.val < 0) or
  9143. (taicpu(next).oper[0]^.val > 3) then
  9144. Exit;
  9145. PotentialModified := True;
  9146. end;
  9147. A_IMUL:
  9148. begin
  9149. if (taicpu(next).ops <> 3) or
  9150. (taicpu(next).oper[1]^.typ <> top_reg) or
  9151. { Must write to a register }
  9152. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9153. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9154. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9155. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9156. Exit
  9157. else
  9158. PotentialModified := True;
  9159. end;
  9160. else
  9161. { Don't know how to change this, so abort }
  9162. Exit;
  9163. end;
  9164. { Contains highest index (so instruction count - 1) }
  9165. Inc(InstrMax);
  9166. if InstrMax > High(InstrList) then
  9167. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9168. InstrList[InstrMax] := taicpu(next);
  9169. end;
  9170. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9171. end;
  9172. if not Assigned(next) or (next <> hp1) then
  9173. { It should be equal to hp1 }
  9174. InternalError(2021051702);
  9175. { Cycle through each instruction and check to see if we can
  9176. change them to versions that don't modify the flags }
  9177. if (InstrMax >= 0) then
  9178. begin
  9179. for Index := 0 to InstrMax do
  9180. case InstrList[Index].opcode of
  9181. A_ADD:
  9182. begin
  9183. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9184. InstrList[Index].opcode := A_LEA;
  9185. reference_reset(NewRef, 1, []);
  9186. NewRef.base := InstrList[Index].oper[1]^.reg;
  9187. if InstrList[Index].oper[0]^.typ = top_reg then
  9188. begin
  9189. NewRef.index := InstrList[Index].oper[0]^.reg;
  9190. NewRef.scalefactor := 1;
  9191. end
  9192. else
  9193. NewRef.offset := InstrList[Index].oper[0]^.val;
  9194. InstrList[Index].loadref(0, NewRef);
  9195. end;
  9196. A_SUB:
  9197. begin
  9198. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9199. InstrList[Index].opcode := A_LEA;
  9200. reference_reset(NewRef, 1, []);
  9201. NewRef.base := InstrList[Index].oper[1]^.reg;
  9202. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9203. InstrList[Index].loadref(0, NewRef);
  9204. end;
  9205. A_SHL,
  9206. A_SAL:
  9207. begin
  9208. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9209. InstrList[Index].opcode := A_LEA;
  9210. reference_reset(NewRef, 1, []);
  9211. NewRef.index := InstrList[Index].oper[1]^.reg;
  9212. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9213. InstrList[Index].loadref(0, NewRef);
  9214. end;
  9215. A_IMUL:
  9216. begin
  9217. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9218. InstrList[Index].opcode := A_LEA;
  9219. reference_reset(NewRef, 1, []);
  9220. NewRef.index := InstrList[Index].oper[1]^.reg;
  9221. case InstrList[Index].oper[0]^.val of
  9222. 2, 4, 8:
  9223. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9224. else {3, 5 and 9}
  9225. begin
  9226. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9227. NewRef.base := InstrList[Index].oper[1]^.reg;
  9228. end;
  9229. end;
  9230. InstrList[Index].loadref(0, NewRef);
  9231. end;
  9232. else
  9233. InternalError(2021051710);
  9234. end;
  9235. end;
  9236. { Mark the FLAGS register as used across this whole block }
  9237. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9238. end;
  9239. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9240. JumpC := taicpu(hp2).condition;
  9241. Unconditional := False;
  9242. if conditions_equal(JumpC, C_E) then
  9243. SetC := inverse_cond(taicpu(p).condition)
  9244. else if conditions_equal(JumpC, C_NE) then
  9245. SetC := taicpu(p).condition
  9246. else
  9247. { We've got something weird here (and inefficent) }
  9248. begin
  9249. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9250. SetC := C_NONE;
  9251. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9252. if condition_in(C_AE, JumpC) then
  9253. Unconditional := True
  9254. else
  9255. { Not sure what to do with this jump - drop out }
  9256. Exit;
  9257. end;
  9258. RemoveInstruction(hp1);
  9259. if Unconditional then
  9260. MakeUnconditional(taicpu(hp2))
  9261. else
  9262. begin
  9263. if SetC = C_NONE then
  9264. InternalError(2018061402);
  9265. taicpu(hp2).SetCondition(SetC);
  9266. end;
  9267. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9268. TmpUsedRegs }
  9269. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9270. begin
  9271. RemoveCurrentp(p, hp2);
  9272. if taicpu(hp2).opcode = A_SETcc then
  9273. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9274. else
  9275. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9276. end
  9277. else
  9278. if taicpu(hp2).opcode = A_SETcc then
  9279. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9280. else
  9281. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9282. Result := True;
  9283. end
  9284. else if
  9285. { Make sure the instructions are adjacent }
  9286. (
  9287. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9288. GetNextInstruction(p, hp1)
  9289. ) and
  9290. MatchInstruction(hp1, A_MOV, [S_B]) and
  9291. { Writing to memory is allowed }
  9292. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9293. begin
  9294. {
  9295. Watch out for sequences such as:
  9296. set(c)b %regb
  9297. movb %regb,(ref)
  9298. movb $0,1(ref)
  9299. movb $0,2(ref)
  9300. movb $0,3(ref)
  9301. Much more efficient to turn it into:
  9302. movl $0,%regl
  9303. set(c)b %regb
  9304. movl %regl,(ref)
  9305. Or:
  9306. set(c)b %regb
  9307. movzbl %regb,%regl
  9308. movl %regl,(ref)
  9309. }
  9310. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9311. GetNextInstruction(hp1, hp2) and
  9312. MatchInstruction(hp2, A_MOV, [S_B]) and
  9313. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9314. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9315. begin
  9316. { Don't do anything else except set Result to True }
  9317. end
  9318. else
  9319. begin
  9320. if taicpu(p).oper[0]^.typ = top_reg then
  9321. begin
  9322. TransferUsedRegs(TmpUsedRegs);
  9323. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9324. end;
  9325. { If it's not a register, it's a memory address }
  9326. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9327. begin
  9328. { Even if the register is still in use, we can minimise the
  9329. pipeline stall by changing the MOV into another SETcc. }
  9330. taicpu(hp1).opcode := A_SETcc;
  9331. taicpu(hp1).condition := taicpu(p).condition;
  9332. if taicpu(hp1).oper[1]^.typ = top_ref then
  9333. begin
  9334. { Swapping the operand pointers like this is probably a
  9335. bit naughty, but it is far faster than using loadoper
  9336. to transfer the reference from oper[1] to oper[0] if
  9337. you take into account the extra procedure calls and
  9338. the memory allocation and deallocation required }
  9339. OperPtr := taicpu(hp1).oper[1];
  9340. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9341. taicpu(hp1).oper[0] := OperPtr;
  9342. end
  9343. else
  9344. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9345. taicpu(hp1).clearop(1);
  9346. taicpu(hp1).ops := 1;
  9347. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9348. end
  9349. else
  9350. begin
  9351. if taicpu(hp1).oper[1]^.typ = top_reg then
  9352. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9353. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9354. RemoveInstruction(hp1);
  9355. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9356. end
  9357. end;
  9358. Result := True;
  9359. end;
  9360. end;
  9361. end;
  9362. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9363. var
  9364. hp1: tai;
  9365. Count: Integer;
  9366. OrigLabel: TAsmLabel;
  9367. begin
  9368. result := False;
  9369. { Sometimes, the optimisations below can permit this }
  9370. RemoveDeadCodeAfterJump(p);
  9371. 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
  9372. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9373. begin
  9374. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9375. { Also a side-effect of optimisations }
  9376. if CollapseZeroDistJump(p, OrigLabel) then
  9377. begin
  9378. Result := True;
  9379. Exit;
  9380. end;
  9381. hp1 := GetLabelWithSym(OrigLabel);
  9382. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9383. begin
  9384. if taicpu(hp1).opcode = A_RET then
  9385. begin
  9386. {
  9387. change
  9388. jmp .L1
  9389. ...
  9390. .L1:
  9391. ret
  9392. into
  9393. ret
  9394. }
  9395. begin
  9396. ConvertJumpToRET(p, hp1);
  9397. result:=true;
  9398. end;
  9399. end
  9400. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9401. not (cs_opt_size in current_settings.optimizerswitches) and
  9402. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9403. begin
  9404. Result := True;
  9405. Exit;
  9406. end;
  9407. end;
  9408. end;
  9409. end;
  9410. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9411. begin
  9412. CanBeCMOV:=assigned(p) and
  9413. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9414. { we can't use cmov ref,reg because
  9415. ref could be nil and cmov still throws an exception
  9416. if ref=nil but the mov isn't done (FK)
  9417. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9418. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9419. }
  9420. (taicpu(p).oper[1]^.typ = top_reg) and
  9421. (
  9422. (taicpu(p).oper[0]^.typ = top_reg) or
  9423. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9424. it is not expected that this can cause a seg. violation }
  9425. (
  9426. (taicpu(p).oper[0]^.typ = top_ref) and
  9427. IsRefSafe(taicpu(p).oper[0]^.ref)
  9428. )
  9429. );
  9430. end;
  9431. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9432. var
  9433. hp1,hp2: tai;
  9434. {$ifndef i8086}
  9435. hp3,hp4,hpmov2, hp5: tai;
  9436. l : Longint;
  9437. condition : TAsmCond;
  9438. {$endif i8086}
  9439. carryadd_opcode : TAsmOp;
  9440. symbol: TAsmSymbol;
  9441. increg, tmpreg: TRegister;
  9442. begin
  9443. result:=false;
  9444. if GetNextInstruction(p,hp1) then
  9445. begin
  9446. if (hp1.typ=ait_label) then
  9447. begin
  9448. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9449. Exit;
  9450. end
  9451. else if (hp1.typ<>ait_instruction) then
  9452. Exit;
  9453. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9454. if (
  9455. (
  9456. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9457. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9458. (Taicpu(hp1).oper[0]^.val=1)
  9459. ) or
  9460. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9461. ) and
  9462. GetNextInstruction(hp1,hp2) and
  9463. SkipAligns(hp2, hp2) and
  9464. (hp2.typ = ait_label) and
  9465. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9466. { jb @@1 cmc
  9467. inc/dec operand --> adc/sbb operand,0
  9468. @@1:
  9469. ... and ...
  9470. jnb @@1
  9471. inc/dec operand --> adc/sbb operand,0
  9472. @@1: }
  9473. begin
  9474. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9475. begin
  9476. case taicpu(hp1).opcode of
  9477. A_INC,
  9478. A_ADD:
  9479. carryadd_opcode:=A_ADC;
  9480. A_DEC,
  9481. A_SUB:
  9482. carryadd_opcode:=A_SBB;
  9483. else
  9484. InternalError(2021011001);
  9485. end;
  9486. Taicpu(p).clearop(0);
  9487. Taicpu(p).ops:=0;
  9488. Taicpu(p).is_jmp:=false;
  9489. Taicpu(p).opcode:=A_CMC;
  9490. Taicpu(p).condition:=C_NONE;
  9491. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9492. Taicpu(hp1).ops:=2;
  9493. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9494. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9495. else
  9496. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9497. Taicpu(hp1).loadconst(0,0);
  9498. Taicpu(hp1).opcode:=carryadd_opcode;
  9499. result:=true;
  9500. exit;
  9501. end
  9502. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9503. begin
  9504. case taicpu(hp1).opcode of
  9505. A_INC,
  9506. A_ADD:
  9507. carryadd_opcode:=A_ADC;
  9508. A_DEC,
  9509. A_SUB:
  9510. carryadd_opcode:=A_SBB;
  9511. else
  9512. InternalError(2021011002);
  9513. end;
  9514. Taicpu(hp1).ops:=2;
  9515. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9516. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9517. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9518. else
  9519. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9520. Taicpu(hp1).loadconst(0,0);
  9521. Taicpu(hp1).opcode:=carryadd_opcode;
  9522. RemoveCurrentP(p, hp1);
  9523. result:=true;
  9524. exit;
  9525. end
  9526. {
  9527. jcc @@1 setcc tmpreg
  9528. inc/dec/add/sub operand -> (movzx tmpreg)
  9529. @@1: add/sub tmpreg,operand
  9530. While this increases code size slightly, it makes the code much faster if the
  9531. jump is unpredictable
  9532. }
  9533. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9534. begin
  9535. { search for an available register which is volatile }
  9536. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9537. if increg <> NR_NO then
  9538. begin
  9539. { We don't need to check if tmpreg is in hp1 or not, because
  9540. it will be marked as in use at p (if not, this is
  9541. indictive of a compiler bug). }
  9542. TAsmLabel(symbol).decrefs;
  9543. Taicpu(p).clearop(0);
  9544. Taicpu(p).ops:=1;
  9545. Taicpu(p).is_jmp:=false;
  9546. Taicpu(p).opcode:=A_SETcc;
  9547. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9548. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9549. Taicpu(p).loadreg(0,increg);
  9550. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9551. begin
  9552. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9553. R_SUBW:
  9554. begin
  9555. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9556. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9557. end;
  9558. R_SUBD:
  9559. begin
  9560. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9561. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9562. end;
  9563. {$ifdef x86_64}
  9564. R_SUBQ:
  9565. begin
  9566. { MOVZX doesn't have a 64-bit variant, because
  9567. the 32-bit version implicitly zeroes the
  9568. upper 32-bits of the destination register }
  9569. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9570. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9571. setsubreg(tmpreg, R_SUBQ);
  9572. end;
  9573. {$endif x86_64}
  9574. else
  9575. Internalerror(2020030601);
  9576. end;
  9577. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9578. asml.InsertAfter(hp2,p);
  9579. end
  9580. else
  9581. tmpreg := increg;
  9582. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9583. begin
  9584. Taicpu(hp1).ops:=2;
  9585. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9586. end;
  9587. Taicpu(hp1).loadreg(0,tmpreg);
  9588. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9589. Result := True;
  9590. { p is no longer a Jcc instruction, so exit }
  9591. Exit;
  9592. end;
  9593. end;
  9594. end;
  9595. { Detect the following:
  9596. jmp<cond> @Lbl1
  9597. jmp @Lbl2
  9598. ...
  9599. @Lbl1:
  9600. ret
  9601. Change to:
  9602. jmp<inv_cond> @Lbl2
  9603. ret
  9604. }
  9605. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9606. begin
  9607. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9608. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9609. MatchInstruction(hp2,A_RET,[S_NO]) then
  9610. begin
  9611. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9612. { Change label address to that of the unconditional jump }
  9613. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9614. TAsmLabel(symbol).DecRefs;
  9615. taicpu(hp1).opcode := A_RET;
  9616. taicpu(hp1).is_jmp := false;
  9617. taicpu(hp1).ops := taicpu(hp2).ops;
  9618. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9619. case taicpu(hp2).ops of
  9620. 0:
  9621. taicpu(hp1).clearop(0);
  9622. 1:
  9623. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9624. else
  9625. internalerror(2016041302);
  9626. end;
  9627. end;
  9628. {$ifndef i8086}
  9629. end
  9630. {
  9631. convert
  9632. j<c> .L1
  9633. mov 1,reg
  9634. jmp .L2
  9635. .L1
  9636. mov 0,reg
  9637. .L2
  9638. into
  9639. mov 0,reg
  9640. set<not(c)> reg
  9641. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9642. would destroy the flag contents
  9643. }
  9644. else if MatchInstruction(hp1,A_MOV,[]) and
  9645. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9646. {$ifdef i386}
  9647. (
  9648. { Under i386, ESI, EDI, EBP and ESP
  9649. don't have an 8-bit representation }
  9650. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9651. ) and
  9652. {$endif i386}
  9653. (taicpu(hp1).oper[0]^.val=1) and
  9654. GetNextInstruction(hp1,hp2) and
  9655. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9656. GetNextInstruction(hp2,hp3) and
  9657. { skip align }
  9658. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9659. (hp3.typ=ait_label) and
  9660. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9661. (tai_label(hp3).labsym.getrefs=1) and
  9662. GetNextInstruction(hp3,hp4) and
  9663. MatchInstruction(hp4,A_MOV,[]) and
  9664. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9665. (taicpu(hp4).oper[0]^.val=0) and
  9666. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9667. GetNextInstruction(hp4,hp5) and
  9668. (hp5.typ=ait_label) and
  9669. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9670. (tai_label(hp5).labsym.getrefs=1) then
  9671. begin
  9672. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9673. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9674. { remove last label }
  9675. RemoveInstruction(hp5);
  9676. { remove second label }
  9677. RemoveInstruction(hp3);
  9678. { if align is present remove it }
  9679. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9680. RemoveInstruction(hp3);
  9681. { remove jmp }
  9682. RemoveInstruction(hp2);
  9683. if taicpu(hp1).opsize=S_B then
  9684. RemoveInstruction(hp1)
  9685. else
  9686. taicpu(hp1).loadconst(0,0);
  9687. taicpu(hp4).opcode:=A_SETcc;
  9688. taicpu(hp4).opsize:=S_B;
  9689. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9690. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9691. taicpu(hp4).opercnt:=1;
  9692. taicpu(hp4).ops:=1;
  9693. taicpu(hp4).freeop(1);
  9694. RemoveCurrentP(p);
  9695. Result:=true;
  9696. exit;
  9697. end
  9698. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9699. begin
  9700. { check for
  9701. jCC xxx
  9702. <several movs>
  9703. xxx:
  9704. Also spot:
  9705. Jcc xxx
  9706. <several movs>
  9707. jmp xxx
  9708. Change to:
  9709. <several cmovs with inverted condition>
  9710. jmp xxx
  9711. }
  9712. l:=0;
  9713. while assigned(hp1) and
  9714. CanBeCMOV(hp1) and
  9715. { stop on labels }
  9716. not(hp1.typ=ait_label) do
  9717. begin
  9718. inc(l);
  9719. hp5 := hp1;
  9720. GetNextInstruction(hp1,hp1);
  9721. end;
  9722. if assigned(hp1) then
  9723. begin
  9724. TransferUsedRegs(TmpUsedRegs);
  9725. if (
  9726. MatchInstruction(hp1, A_JMP, []) and
  9727. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9728. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9729. ) or
  9730. FindLabel(tasmlabel(symbol),hp1) then
  9731. begin
  9732. if (l<=4) and (l>0) then
  9733. begin
  9734. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9735. condition:=inverse_cond(taicpu(p).condition);
  9736. UpdateUsedRegs(tai(p.next));
  9737. GetNextInstruction(p,hp1);
  9738. repeat
  9739. if not Assigned(hp1) then
  9740. InternalError(2018062900);
  9741. taicpu(hp1).opcode:=A_CMOVcc;
  9742. taicpu(hp1).condition:=condition;
  9743. UpdateUsedRegs(tai(hp1.next));
  9744. GetNextInstruction(hp1,hp1);
  9745. until not(CanBeCMOV(hp1));
  9746. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9747. hp2 := hp1;
  9748. repeat
  9749. if not Assigned(hp2) then
  9750. InternalError(2018062910);
  9751. case hp2.typ of
  9752. ait_label:
  9753. { What we expected - break out of the loop (it won't be a dead label at the top of
  9754. a cluster because that was optimised at an earlier stage) }
  9755. Break;
  9756. ait_align:
  9757. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9758. begin
  9759. hp2 := tai(hp2.Next);
  9760. Continue;
  9761. end;
  9762. ait_instruction:
  9763. begin
  9764. if taicpu(hp2).opcode<>A_JMP then
  9765. InternalError(2018062912);
  9766. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9767. Break;
  9768. end
  9769. else
  9770. begin
  9771. { Might be a comment or temporary allocation entry }
  9772. if not (hp2.typ in SkipInstr) then
  9773. InternalError(2018062911);
  9774. hp2 := tai(hp2.Next);
  9775. Continue;
  9776. end;
  9777. end;
  9778. until False;
  9779. { Now we can safely decrement the reference count }
  9780. tasmlabel(symbol).decrefs;
  9781. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9782. { Remove the original jump }
  9783. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9784. if hp2.typ=ait_instruction then
  9785. begin
  9786. p:=hp2;
  9787. Result:=True;
  9788. end
  9789. else
  9790. begin
  9791. UpdateUsedRegs(tai(hp2.next));
  9792. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9793. { Remove the label if this is its final reference }
  9794. if (tasmlabel(symbol).getrefs=0) then
  9795. StripLabelFast(hp1);
  9796. end;
  9797. exit;
  9798. end;
  9799. end
  9800. else
  9801. begin
  9802. { check further for
  9803. jCC xxx
  9804. <several movs 1>
  9805. jmp yyy
  9806. xxx:
  9807. <several movs 2>
  9808. yyy:
  9809. }
  9810. { hp2 points to jmp yyy }
  9811. hp2:=hp1;
  9812. { skip hp1 to xxx (or an align right before it) }
  9813. GetNextInstruction(hp1, hp1);
  9814. if assigned(hp2) and
  9815. assigned(hp1) and
  9816. (l<=3) and
  9817. (hp2.typ=ait_instruction) and
  9818. (taicpu(hp2).is_jmp) and
  9819. (taicpu(hp2).condition=C_None) and
  9820. { real label and jump, no further references to the
  9821. label are allowed }
  9822. (tasmlabel(symbol).getrefs=1) and
  9823. FindLabel(tasmlabel(symbol),hp1) then
  9824. begin
  9825. l:=0;
  9826. { skip hp1 to <several moves 2> }
  9827. if (hp1.typ = ait_align) then
  9828. GetNextInstruction(hp1, hp1);
  9829. GetNextInstruction(hp1, hpmov2);
  9830. hp1 := hpmov2;
  9831. while assigned(hp1) and
  9832. CanBeCMOV(hp1) do
  9833. begin
  9834. inc(l);
  9835. hp5 := hp1;
  9836. GetNextInstruction(hp1, hp1);
  9837. end;
  9838. { hp1 points to yyy (or an align right before it) }
  9839. hp3 := hp1;
  9840. if assigned(hp1) and
  9841. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9842. begin
  9843. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9844. condition:=inverse_cond(taicpu(p).condition);
  9845. UpdateUsedRegs(tai(p.next));
  9846. GetNextInstruction(p,hp1);
  9847. repeat
  9848. taicpu(hp1).opcode:=A_CMOVcc;
  9849. taicpu(hp1).condition:=condition;
  9850. UpdateUsedRegs(tai(hp1.next));
  9851. GetNextInstruction(hp1,hp1);
  9852. until not(assigned(hp1)) or
  9853. not(CanBeCMOV(hp1));
  9854. condition:=inverse_cond(condition);
  9855. if GetLastInstruction(hpmov2,hp1) then
  9856. UpdateUsedRegs(tai(hp1.next));
  9857. hp1 := hpmov2;
  9858. { hp1 is now at <several movs 2> }
  9859. while Assigned(hp1) and CanBeCMOV(hp1) do
  9860. begin
  9861. taicpu(hp1).opcode:=A_CMOVcc;
  9862. taicpu(hp1).condition:=condition;
  9863. UpdateUsedRegs(tai(hp1.next));
  9864. GetNextInstruction(hp1,hp1);
  9865. end;
  9866. hp1 := p;
  9867. { Get first instruction after label }
  9868. UpdateUsedRegs(tai(hp3.next));
  9869. GetNextInstruction(hp3, p);
  9870. if assigned(p) and (hp3.typ = ait_align) then
  9871. GetNextInstruction(p, p);
  9872. { Don't dereference yet, as doing so will cause
  9873. GetNextInstruction to skip the label and
  9874. optional align marker. [Kit] }
  9875. GetNextInstruction(hp2, hp4);
  9876. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9877. { remove jCC }
  9878. RemoveInstruction(hp1);
  9879. { Now we can safely decrement it }
  9880. tasmlabel(symbol).decrefs;
  9881. { Remove label xxx (it will have a ref of zero due to the initial check }
  9882. StripLabelFast(hp4);
  9883. { remove jmp }
  9884. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9885. RemoveInstruction(hp2);
  9886. { As before, now we can safely decrement it }
  9887. tasmlabel(symbol).decrefs;
  9888. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9889. if tasmlabel(symbol).getrefs = 0 then
  9890. StripLabelFast(hp3);
  9891. if Assigned(p) then
  9892. result:=true;
  9893. exit;
  9894. end;
  9895. end;
  9896. end;
  9897. end;
  9898. {$endif i8086}
  9899. end;
  9900. end;
  9901. end;
  9902. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9903. var
  9904. hp1,hp2,hp3: tai;
  9905. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9906. NewSize: TOpSize;
  9907. NewRegSize: TSubRegister;
  9908. Limit: TCgInt;
  9909. SwapOper: POper;
  9910. begin
  9911. result:=false;
  9912. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9913. GetNextInstruction(p,hp1) and
  9914. (hp1.typ = ait_instruction);
  9915. if reg_and_hp1_is_instr and
  9916. (
  9917. (taicpu(hp1).opcode <> A_LEA) or
  9918. { If the LEA instruction can be converted into an arithmetic instruction,
  9919. it may be possible to then fold it. }
  9920. (
  9921. { If the flags register is in use, don't change the instruction
  9922. to an ADD otherwise this will scramble the flags. [Kit] }
  9923. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9924. ConvertLEA(taicpu(hp1))
  9925. )
  9926. ) and
  9927. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9928. GetNextInstruction(hp1,hp2) and
  9929. MatchInstruction(hp2,A_MOV,[]) and
  9930. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9931. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9932. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9933. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9934. {$ifdef i386}
  9935. { not all registers have byte size sub registers on i386 }
  9936. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9937. {$endif i386}
  9938. (((taicpu(hp1).ops=2) and
  9939. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9940. ((taicpu(hp1).ops=1) and
  9941. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9942. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9943. begin
  9944. { change movsX/movzX reg/ref, reg2
  9945. add/sub/or/... reg3/$const, reg2
  9946. mov reg2 reg/ref
  9947. to add/sub/or/... reg3/$const, reg/ref }
  9948. { by example:
  9949. movswl %si,%eax movswl %si,%eax p
  9950. decl %eax addl %edx,%eax hp1
  9951. movw %ax,%si movw %ax,%si hp2
  9952. ->
  9953. movswl %si,%eax movswl %si,%eax p
  9954. decw %eax addw %edx,%eax hp1
  9955. movw %ax,%si movw %ax,%si hp2
  9956. }
  9957. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9958. {
  9959. ->
  9960. movswl %si,%eax movswl %si,%eax p
  9961. decw %si addw %dx,%si hp1
  9962. movw %ax,%si movw %ax,%si hp2
  9963. }
  9964. case taicpu(hp1).ops of
  9965. 1:
  9966. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9967. 2:
  9968. begin
  9969. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9970. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9971. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9972. end;
  9973. else
  9974. internalerror(2008042702);
  9975. end;
  9976. {
  9977. ->
  9978. decw %si addw %dx,%si p
  9979. }
  9980. DebugMsg(SPeepholeOptimization + 'var3',p);
  9981. RemoveCurrentP(p, hp1);
  9982. RemoveInstruction(hp2);
  9983. Result := True;
  9984. Exit;
  9985. end;
  9986. if reg_and_hp1_is_instr and
  9987. (taicpu(hp1).opcode = A_MOV) and
  9988. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9989. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9990. {$ifdef x86_64}
  9991. { check for implicit extension to 64 bit }
  9992. or
  9993. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9994. (taicpu(hp1).opsize=S_Q) and
  9995. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9996. )
  9997. {$endif x86_64}
  9998. )
  9999. then
  10000. begin
  10001. { change
  10002. movx %reg1,%reg2
  10003. mov %reg2,%reg3
  10004. dealloc %reg2
  10005. into
  10006. movx %reg,%reg3
  10007. }
  10008. TransferUsedRegs(TmpUsedRegs);
  10009. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10010. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10011. begin
  10012. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10013. {$ifdef x86_64}
  10014. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10015. (taicpu(hp1).opsize=S_Q) then
  10016. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10017. else
  10018. {$endif x86_64}
  10019. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10020. RemoveInstruction(hp1);
  10021. Result := True;
  10022. Exit;
  10023. end;
  10024. end;
  10025. if reg_and_hp1_is_instr and
  10026. ((taicpu(hp1).opcode=A_MOV) or
  10027. (taicpu(hp1).opcode=A_ADD) or
  10028. (taicpu(hp1).opcode=A_SUB) or
  10029. (taicpu(hp1).opcode=A_CMP) or
  10030. (taicpu(hp1).opcode=A_OR) or
  10031. (taicpu(hp1).opcode=A_XOR) or
  10032. (taicpu(hp1).opcode=A_AND)
  10033. ) and
  10034. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10035. begin
  10036. AndTest := (taicpu(hp1).opcode=A_AND) and
  10037. GetNextInstruction(hp1, hp2) and
  10038. (hp2.typ = ait_instruction) and
  10039. (
  10040. (
  10041. (taicpu(hp2).opcode=A_TEST) and
  10042. (
  10043. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10044. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10045. (
  10046. { If the AND and TEST instructions share a constant, this is also valid }
  10047. (taicpu(hp1).oper[0]^.typ = top_const) and
  10048. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10049. )
  10050. ) and
  10051. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10052. ) or
  10053. (
  10054. (taicpu(hp2).opcode=A_CMP) and
  10055. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10056. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10057. )
  10058. );
  10059. { change
  10060. movx (oper),%reg2
  10061. and $x,%reg2
  10062. test %reg2,%reg2
  10063. dealloc %reg2
  10064. into
  10065. op %reg1,%reg3
  10066. if the second op accesses only the bits stored in reg1
  10067. }
  10068. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10069. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10070. (taicpu(hp1).oper[0]^.typ = top_const) and
  10071. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10072. AndTest then
  10073. begin
  10074. { Check if the AND constant is in range }
  10075. case taicpu(p).opsize of
  10076. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10077. begin
  10078. NewSize := S_B;
  10079. Limit := $FF;
  10080. end;
  10081. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10082. begin
  10083. NewSize := S_W;
  10084. Limit := $FFFF;
  10085. end;
  10086. {$ifdef x86_64}
  10087. S_LQ:
  10088. begin
  10089. NewSize := S_L;
  10090. Limit := $FFFFFFFF;
  10091. end;
  10092. {$endif x86_64}
  10093. else
  10094. InternalError(2021120303);
  10095. end;
  10096. if (
  10097. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10098. { Check for negative operands }
  10099. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10100. ) and
  10101. GetNextInstruction(hp2,hp3) and
  10102. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10103. (taicpu(hp3).condition in [C_E,C_NE]) then
  10104. begin
  10105. TransferUsedRegs(TmpUsedRegs);
  10106. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10107. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10108. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10109. begin
  10110. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10111. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10112. taicpu(hp1).opcode := A_TEST;
  10113. taicpu(hp1).opsize := NewSize;
  10114. RemoveInstruction(hp2);
  10115. RemoveCurrentP(p, hp1);
  10116. Result:=true;
  10117. exit;
  10118. end;
  10119. end;
  10120. end;
  10121. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10122. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10123. (taicpu(hp1).opsize=S_B)) or
  10124. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10125. (taicpu(hp1).opsize=S_W))
  10126. {$ifdef x86_64}
  10127. or ((taicpu(p).opsize=S_LQ) and
  10128. (taicpu(hp1).opsize=S_L))
  10129. {$endif x86_64}
  10130. ) and
  10131. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10132. begin
  10133. { change
  10134. movx %reg1,%reg2
  10135. op %reg2,%reg3
  10136. dealloc %reg2
  10137. into
  10138. op %reg1,%reg3
  10139. if the second op accesses only the bits stored in reg1
  10140. }
  10141. TransferUsedRegs(TmpUsedRegs);
  10142. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10143. if AndTest then
  10144. begin
  10145. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10146. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10147. end
  10148. else
  10149. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10150. if not RegUsed then
  10151. begin
  10152. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10153. if taicpu(p).oper[0]^.typ=top_reg then
  10154. begin
  10155. case taicpu(hp1).opsize of
  10156. S_B:
  10157. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10158. S_W:
  10159. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10160. S_L:
  10161. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10162. else
  10163. Internalerror(2020102301);
  10164. end;
  10165. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10166. end
  10167. else
  10168. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10169. RemoveCurrentP(p);
  10170. if AndTest then
  10171. RemoveInstruction(hp2);
  10172. result:=true;
  10173. exit;
  10174. end;
  10175. end
  10176. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10177. (
  10178. { Bitwise operations only }
  10179. (taicpu(hp1).opcode=A_AND) or
  10180. (taicpu(hp1).opcode=A_TEST) or
  10181. (
  10182. (taicpu(hp1).oper[0]^.typ = top_const) and
  10183. (
  10184. (taicpu(hp1).opcode=A_OR) or
  10185. (taicpu(hp1).opcode=A_XOR)
  10186. )
  10187. )
  10188. ) and
  10189. (
  10190. (taicpu(hp1).oper[0]^.typ = top_const) or
  10191. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10192. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10193. ) then
  10194. begin
  10195. { change
  10196. movx %reg2,%reg2
  10197. op const,%reg2
  10198. into
  10199. op const,%reg2 (smaller version)
  10200. movx %reg2,%reg2
  10201. also change
  10202. movx %reg1,%reg2
  10203. and/test (oper),%reg2
  10204. dealloc %reg2
  10205. into
  10206. and/test (oper),%reg1
  10207. }
  10208. case taicpu(p).opsize of
  10209. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10210. begin
  10211. NewSize := S_B;
  10212. NewRegSize := R_SUBL;
  10213. Limit := $FF;
  10214. end;
  10215. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10216. begin
  10217. NewSize := S_W;
  10218. NewRegSize := R_SUBW;
  10219. Limit := $FFFF;
  10220. end;
  10221. {$ifdef x86_64}
  10222. S_LQ:
  10223. begin
  10224. NewSize := S_L;
  10225. NewRegSize := R_SUBD;
  10226. Limit := $FFFFFFFF;
  10227. end;
  10228. {$endif x86_64}
  10229. else
  10230. Internalerror(2021120302);
  10231. end;
  10232. TransferUsedRegs(TmpUsedRegs);
  10233. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10234. if AndTest then
  10235. begin
  10236. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10237. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10238. end
  10239. else
  10240. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10241. if
  10242. (
  10243. (taicpu(p).opcode = A_MOVZX) and
  10244. (
  10245. (taicpu(hp1).opcode=A_AND) or
  10246. (taicpu(hp1).opcode=A_TEST)
  10247. ) and
  10248. not (
  10249. { If both are references, then the final instruction will have
  10250. both operands as references, which is not allowed }
  10251. (taicpu(p).oper[0]^.typ = top_ref) and
  10252. (taicpu(hp1).oper[0]^.typ = top_ref)
  10253. ) and
  10254. not RegUsed
  10255. ) or
  10256. (
  10257. (
  10258. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10259. not RegUsed
  10260. ) and
  10261. (taicpu(p).oper[0]^.typ = top_reg) and
  10262. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10263. (taicpu(hp1).oper[0]^.typ = top_const) and
  10264. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10265. ) then
  10266. begin
  10267. {$if defined(i386) or defined(i8086)}
  10268. { If the target size is 8-bit, make sure we can actually encode it }
  10269. 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
  10270. Exit;
  10271. {$endif i386 or i8086}
  10272. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10273. taicpu(hp1).opsize := NewSize;
  10274. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10275. if AndTest then
  10276. begin
  10277. RemoveInstruction(hp2);
  10278. if not RegUsed then
  10279. begin
  10280. taicpu(hp1).opcode := A_TEST;
  10281. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10282. begin
  10283. { Make sure the reference is the second operand }
  10284. SwapOper := taicpu(hp1).oper[0];
  10285. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10286. taicpu(hp1).oper[1] := SwapOper;
  10287. end;
  10288. end;
  10289. end;
  10290. case taicpu(hp1).oper[0]^.typ of
  10291. top_reg:
  10292. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10293. top_const:
  10294. { For the AND/TEST case }
  10295. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10296. else
  10297. ;
  10298. end;
  10299. if RegUsed then
  10300. begin
  10301. AsmL.Remove(p);
  10302. AsmL.InsertAfter(p, hp1);
  10303. p := hp1;
  10304. end
  10305. else
  10306. RemoveCurrentP(p, hp1);
  10307. result:=true;
  10308. exit;
  10309. end;
  10310. end;
  10311. end;
  10312. if reg_and_hp1_is_instr and
  10313. (taicpu(p).oper[0]^.typ = top_reg) and
  10314. (
  10315. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10316. ) and
  10317. (taicpu(hp1).oper[0]^.typ = top_const) and
  10318. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10319. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10320. { Minimum shift value allowed is the bit difference between the sizes }
  10321. (taicpu(hp1).oper[0]^.val >=
  10322. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10323. 8 * (
  10324. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10325. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10326. )
  10327. ) then
  10328. begin
  10329. { For:
  10330. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10331. shl/sal ##, %reg1
  10332. Remove the movsx/movzx instruction if the shift overwrites the
  10333. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10334. }
  10335. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10336. RemoveCurrentP(p, hp1);
  10337. Result := True;
  10338. Exit;
  10339. end
  10340. else if reg_and_hp1_is_instr and
  10341. (taicpu(p).oper[0]^.typ = top_reg) and
  10342. (
  10343. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10344. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10345. ) and
  10346. (taicpu(hp1).oper[0]^.typ = top_const) and
  10347. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10348. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10349. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10350. (taicpu(hp1).oper[0]^.val <
  10351. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10352. 8 * (
  10353. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10354. )
  10355. ) then
  10356. begin
  10357. { For:
  10358. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10359. sar ##, %reg1 shr ##, %reg1
  10360. Move the shift to before the movx instruction if the shift value
  10361. is not too large.
  10362. }
  10363. asml.Remove(hp1);
  10364. asml.InsertBefore(hp1, p);
  10365. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10366. case taicpu(p).opsize of
  10367. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10368. taicpu(hp1).opsize := S_B;
  10369. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10370. taicpu(hp1).opsize := S_W;
  10371. {$ifdef x86_64}
  10372. S_LQ:
  10373. taicpu(hp1).opsize := S_L;
  10374. {$endif}
  10375. else
  10376. InternalError(2020112401);
  10377. end;
  10378. if (taicpu(hp1).opcode = A_SHR) then
  10379. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10380. else
  10381. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10382. Result := True;
  10383. end;
  10384. if reg_and_hp1_is_instr and
  10385. (taicpu(p).oper[0]^.typ = top_reg) and
  10386. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10387. (
  10388. (taicpu(hp1).opcode = taicpu(p).opcode)
  10389. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10390. {$ifdef x86_64}
  10391. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10392. {$endif x86_64}
  10393. ) then
  10394. begin
  10395. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10396. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10397. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10398. begin
  10399. {
  10400. For example:
  10401. movzbw %al,%ax
  10402. movzwl %ax,%eax
  10403. Compress into:
  10404. movzbl %al,%eax
  10405. }
  10406. RegUsed := False;
  10407. case taicpu(p).opsize of
  10408. S_BW:
  10409. case taicpu(hp1).opsize of
  10410. S_WL:
  10411. begin
  10412. taicpu(p).opsize := S_BL;
  10413. RegUsed := True;
  10414. end;
  10415. {$ifdef x86_64}
  10416. S_WQ:
  10417. begin
  10418. if taicpu(p).opcode = A_MOVZX then
  10419. begin
  10420. taicpu(p).opsize := S_BL;
  10421. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10422. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10423. end
  10424. else
  10425. taicpu(p).opsize := S_BQ;
  10426. RegUsed := True;
  10427. end;
  10428. {$endif x86_64}
  10429. else
  10430. ;
  10431. end;
  10432. {$ifdef x86_64}
  10433. S_BL:
  10434. case taicpu(hp1).opsize of
  10435. S_LQ:
  10436. begin
  10437. if taicpu(p).opcode = A_MOVZX then
  10438. begin
  10439. taicpu(p).opsize := S_BL;
  10440. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10441. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10442. end
  10443. else
  10444. taicpu(p).opsize := S_BQ;
  10445. RegUsed := True;
  10446. end;
  10447. else
  10448. ;
  10449. end;
  10450. S_WL:
  10451. case taicpu(hp1).opsize of
  10452. S_LQ:
  10453. begin
  10454. if taicpu(p).opcode = A_MOVZX then
  10455. begin
  10456. taicpu(p).opsize := S_WL;
  10457. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10458. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10459. end
  10460. else
  10461. taicpu(p).opsize := S_WQ;
  10462. RegUsed := True;
  10463. end;
  10464. else
  10465. ;
  10466. end;
  10467. {$endif x86_64}
  10468. else
  10469. ;
  10470. end;
  10471. if RegUsed then
  10472. begin
  10473. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10474. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10475. RemoveInstruction(hp1);
  10476. Result := True;
  10477. Exit;
  10478. end;
  10479. end;
  10480. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10481. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10482. GetNextInstruction(hp1, hp2) and
  10483. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10484. (
  10485. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10486. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10487. {$ifdef x86_64}
  10488. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10489. {$endif x86_64}
  10490. ) and
  10491. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10492. (
  10493. (
  10494. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10495. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10496. ) or
  10497. (
  10498. { Only allow the operands in reverse order for TEST instructions }
  10499. (taicpu(hp2).opcode = A_TEST) and
  10500. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10501. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10502. )
  10503. ) then
  10504. begin
  10505. {
  10506. For example:
  10507. movzbl %al,%eax
  10508. movzbl (ref),%edx
  10509. andl %edx,%eax
  10510. (%edx deallocated)
  10511. Change to:
  10512. andb (ref),%al
  10513. movzbl %al,%eax
  10514. Rules are:
  10515. - First two instructions have the same opcode and opsize
  10516. - First instruction's operands are the same super-register
  10517. - Second instruction operates on a different register
  10518. - Third instruction is AND, OR, XOR or TEST
  10519. - Third instruction's operands are the destination registers of the first two instructions
  10520. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10521. - Second instruction's destination register is deallocated afterwards
  10522. }
  10523. TransferUsedRegs(TmpUsedRegs);
  10524. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10525. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10526. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10527. begin
  10528. case taicpu(p).opsize of
  10529. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10530. NewSize := S_B;
  10531. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10532. NewSize := S_W;
  10533. {$ifdef x86_64}
  10534. S_LQ:
  10535. NewSize := S_L;
  10536. {$endif x86_64}
  10537. else
  10538. InternalError(2021120301);
  10539. end;
  10540. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10541. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10542. taicpu(hp2).opsize := NewSize;
  10543. RemoveInstruction(hp1);
  10544. { With TEST, it's best to keep the MOVX instruction at the top }
  10545. if (taicpu(hp2).opcode <> A_TEST) then
  10546. begin
  10547. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10548. asml.Remove(p);
  10549. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10550. asml.InsertAfter(p, hp2);
  10551. p := hp2;
  10552. end
  10553. else
  10554. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10555. Result := True;
  10556. Exit;
  10557. end;
  10558. end;
  10559. end;
  10560. if taicpu(p).opcode=A_MOVZX then
  10561. begin
  10562. { removes superfluous And's after movzx's }
  10563. if reg_and_hp1_is_instr and
  10564. (taicpu(hp1).opcode = A_AND) and
  10565. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10566. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10567. {$ifdef x86_64}
  10568. { check for implicit extension to 64 bit }
  10569. or
  10570. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10571. (taicpu(hp1).opsize=S_Q) and
  10572. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10573. )
  10574. {$endif x86_64}
  10575. )
  10576. then
  10577. begin
  10578. case taicpu(p).opsize Of
  10579. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10580. if (taicpu(hp1).oper[0]^.val = $ff) then
  10581. begin
  10582. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10583. RemoveInstruction(hp1);
  10584. Result:=true;
  10585. exit;
  10586. end;
  10587. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10588. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10589. begin
  10590. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10591. RemoveInstruction(hp1);
  10592. Result:=true;
  10593. exit;
  10594. end;
  10595. {$ifdef x86_64}
  10596. S_LQ:
  10597. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10598. begin
  10599. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10600. RemoveInstruction(hp1);
  10601. Result:=true;
  10602. exit;
  10603. end;
  10604. {$endif x86_64}
  10605. else
  10606. ;
  10607. end;
  10608. { we cannot get rid of the and, but can we get rid of the movz ?}
  10609. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10610. begin
  10611. case taicpu(p).opsize Of
  10612. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10613. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10614. begin
  10615. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10616. RemoveCurrentP(p,hp1);
  10617. Result:=true;
  10618. exit;
  10619. end;
  10620. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10621. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10622. begin
  10623. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10624. RemoveCurrentP(p,hp1);
  10625. Result:=true;
  10626. exit;
  10627. end;
  10628. {$ifdef x86_64}
  10629. S_LQ:
  10630. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10631. begin
  10632. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10633. RemoveCurrentP(p,hp1);
  10634. Result:=true;
  10635. exit;
  10636. end;
  10637. {$endif x86_64}
  10638. else
  10639. ;
  10640. end;
  10641. end;
  10642. end;
  10643. { changes some movzx constructs to faster synonyms (all examples
  10644. are given with eax/ax, but are also valid for other registers)}
  10645. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10646. begin
  10647. case taicpu(p).opsize of
  10648. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10649. (the machine code is equivalent to movzbl %al,%eax), but the
  10650. code generator still generates that assembler instruction and
  10651. it is silently converted. This should probably be checked.
  10652. [Kit] }
  10653. S_BW:
  10654. begin
  10655. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10656. (
  10657. not IsMOVZXAcceptable
  10658. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10659. or (
  10660. (cs_opt_size in current_settings.optimizerswitches) and
  10661. (taicpu(p).oper[1]^.reg = NR_AX)
  10662. )
  10663. ) then
  10664. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10665. begin
  10666. DebugMsg(SPeepholeOptimization + 'var7',p);
  10667. taicpu(p).opcode := A_AND;
  10668. taicpu(p).changeopsize(S_W);
  10669. taicpu(p).loadConst(0,$ff);
  10670. Result := True;
  10671. end
  10672. else if not IsMOVZXAcceptable and
  10673. GetNextInstruction(p, hp1) and
  10674. (tai(hp1).typ = ait_instruction) and
  10675. (taicpu(hp1).opcode = A_AND) and
  10676. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10677. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10678. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10679. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10680. begin
  10681. DebugMsg(SPeepholeOptimization + 'var8',p);
  10682. taicpu(p).opcode := A_MOV;
  10683. taicpu(p).changeopsize(S_W);
  10684. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10685. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10686. Result := True;
  10687. end;
  10688. end;
  10689. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10690. S_BL:
  10691. begin
  10692. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10693. (
  10694. not IsMOVZXAcceptable
  10695. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10696. or (
  10697. (cs_opt_size in current_settings.optimizerswitches) and
  10698. (taicpu(p).oper[1]^.reg = NR_EAX)
  10699. )
  10700. ) then
  10701. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10702. begin
  10703. DebugMsg(SPeepholeOptimization + 'var9',p);
  10704. taicpu(p).opcode := A_AND;
  10705. taicpu(p).changeopsize(S_L);
  10706. taicpu(p).loadConst(0,$ff);
  10707. Result := True;
  10708. end
  10709. else if not IsMOVZXAcceptable and
  10710. GetNextInstruction(p, hp1) and
  10711. (tai(hp1).typ = ait_instruction) and
  10712. (taicpu(hp1).opcode = A_AND) and
  10713. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10714. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10715. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10716. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10717. begin
  10718. DebugMsg(SPeepholeOptimization + 'var10',p);
  10719. taicpu(p).opcode := A_MOV;
  10720. taicpu(p).changeopsize(S_L);
  10721. { do not use R_SUBWHOLE
  10722. as movl %rdx,%eax
  10723. is invalid in assembler PM }
  10724. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10725. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10726. Result := True;
  10727. end;
  10728. end;
  10729. {$endif i8086}
  10730. S_WL:
  10731. if not IsMOVZXAcceptable then
  10732. begin
  10733. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10734. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10735. begin
  10736. DebugMsg(SPeepholeOptimization + 'var11',p);
  10737. taicpu(p).opcode := A_AND;
  10738. taicpu(p).changeopsize(S_L);
  10739. taicpu(p).loadConst(0,$ffff);
  10740. Result := True;
  10741. end
  10742. else if GetNextInstruction(p, hp1) and
  10743. (tai(hp1).typ = ait_instruction) and
  10744. (taicpu(hp1).opcode = A_AND) and
  10745. (taicpu(hp1).oper[0]^.typ = top_const) and
  10746. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10747. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10748. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10749. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10750. begin
  10751. DebugMsg(SPeepholeOptimization + 'var12',p);
  10752. taicpu(p).opcode := A_MOV;
  10753. taicpu(p).changeopsize(S_L);
  10754. { do not use R_SUBWHOLE
  10755. as movl %rdx,%eax
  10756. is invalid in assembler PM }
  10757. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10758. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10759. Result := True;
  10760. end;
  10761. end;
  10762. else
  10763. InternalError(2017050705);
  10764. end;
  10765. end
  10766. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10767. begin
  10768. if GetNextInstruction(p, hp1) and
  10769. (tai(hp1).typ = ait_instruction) and
  10770. (taicpu(hp1).opcode = A_AND) and
  10771. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10772. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10773. begin
  10774. //taicpu(p).opcode := A_MOV;
  10775. case taicpu(p).opsize Of
  10776. S_BL:
  10777. begin
  10778. DebugMsg(SPeepholeOptimization + 'var13',p);
  10779. taicpu(hp1).changeopsize(S_L);
  10780. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10781. end;
  10782. S_WL:
  10783. begin
  10784. DebugMsg(SPeepholeOptimization + 'var14',p);
  10785. taicpu(hp1).changeopsize(S_L);
  10786. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10787. end;
  10788. S_BW:
  10789. begin
  10790. DebugMsg(SPeepholeOptimization + 'var15',p);
  10791. taicpu(hp1).changeopsize(S_W);
  10792. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10793. end;
  10794. else
  10795. Internalerror(2017050704)
  10796. end;
  10797. Result := True;
  10798. end;
  10799. end;
  10800. end;
  10801. end;
  10802. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10803. var
  10804. hp1, hp2 : tai;
  10805. MaskLength : Cardinal;
  10806. MaskedBits : TCgInt;
  10807. ActiveReg : TRegister;
  10808. begin
  10809. Result:=false;
  10810. { There are no optimisations for reference targets }
  10811. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10812. Exit;
  10813. while GetNextInstruction(p, hp1) and
  10814. (hp1.typ = ait_instruction) do
  10815. begin
  10816. if (taicpu(p).oper[0]^.typ = top_const) then
  10817. begin
  10818. case taicpu(hp1).opcode of
  10819. A_AND:
  10820. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10821. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10822. { the second register must contain the first one, so compare their subreg types }
  10823. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10824. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10825. { change
  10826. and const1, reg
  10827. and const2, reg
  10828. to
  10829. and (const1 and const2), reg
  10830. }
  10831. begin
  10832. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10833. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10834. RemoveCurrentP(p, hp1);
  10835. Result:=true;
  10836. exit;
  10837. end;
  10838. A_CMP:
  10839. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10840. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10841. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10842. { Just check that the condition on the next instruction is compatible }
  10843. GetNextInstruction(hp1, hp2) and
  10844. (hp2.typ = ait_instruction) and
  10845. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10846. then
  10847. { change
  10848. and 2^n, reg
  10849. cmp 2^n, reg
  10850. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10851. to
  10852. and 2^n, reg
  10853. test reg, reg
  10854. j(~c) / set(~c) / cmov(~c)
  10855. }
  10856. begin
  10857. { Keep TEST instruction in, rather than remove it, because
  10858. it may trigger other optimisations such as MovAndTest2Test }
  10859. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10860. taicpu(hp1).opcode := A_TEST;
  10861. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10862. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10863. Result := True;
  10864. Exit;
  10865. end;
  10866. A_MOVZX:
  10867. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10868. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10869. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10870. (
  10871. (
  10872. (taicpu(p).opsize=S_W) and
  10873. (taicpu(hp1).opsize=S_BW)
  10874. ) or
  10875. (
  10876. (taicpu(p).opsize=S_L) and
  10877. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10878. )
  10879. {$ifdef x86_64}
  10880. or
  10881. (
  10882. (taicpu(p).opsize=S_Q) and
  10883. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10884. )
  10885. {$endif x86_64}
  10886. ) then
  10887. begin
  10888. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10889. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10890. ) or
  10891. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10892. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10893. then
  10894. begin
  10895. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10896. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10897. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10898. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10899. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10900. }
  10901. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10902. RemoveInstruction(hp1);
  10903. { See if there are other optimisations possible }
  10904. Continue;
  10905. end;
  10906. end;
  10907. A_SHL:
  10908. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10909. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10910. begin
  10911. {$ifopt R+}
  10912. {$define RANGE_WAS_ON}
  10913. {$R-}
  10914. {$endif}
  10915. { get length of potential and mask }
  10916. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10917. { really a mask? }
  10918. {$ifdef RANGE_WAS_ON}
  10919. {$R+}
  10920. {$endif}
  10921. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10922. { unmasked part shifted out? }
  10923. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10924. begin
  10925. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10926. RemoveCurrentP(p, hp1);
  10927. Result:=true;
  10928. exit;
  10929. end;
  10930. end;
  10931. A_SHR:
  10932. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10933. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10934. (taicpu(hp1).oper[0]^.val <= 63) then
  10935. begin
  10936. { Does SHR combined with the AND cover all the bits?
  10937. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10938. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10939. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10940. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10941. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10942. begin
  10943. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10944. RemoveCurrentP(p, hp1);
  10945. Result := True;
  10946. Exit;
  10947. end;
  10948. end;
  10949. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10950. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10951. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10952. begin
  10953. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10954. (
  10955. (
  10956. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10957. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10958. ) or (
  10959. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10960. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10961. {$ifdef x86_64}
  10962. ) or (
  10963. (taicpu(hp1).opsize = S_LQ) and
  10964. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10965. {$endif x86_64}
  10966. )
  10967. ) then
  10968. begin
  10969. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10970. begin
  10971. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10972. RemoveInstruction(hp1);
  10973. { See if there are other optimisations possible }
  10974. Continue;
  10975. end;
  10976. { The super-registers are the same though.
  10977. Note that this change by itself doesn't improve
  10978. code speed, but it opens up other optimisations. }
  10979. {$ifdef x86_64}
  10980. { Convert 64-bit register to 32-bit }
  10981. case taicpu(hp1).opsize of
  10982. S_BQ:
  10983. begin
  10984. taicpu(hp1).opsize := S_BL;
  10985. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10986. end;
  10987. S_WQ:
  10988. begin
  10989. taicpu(hp1).opsize := S_WL;
  10990. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10991. end
  10992. else
  10993. ;
  10994. end;
  10995. {$endif x86_64}
  10996. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10997. taicpu(hp1).opcode := A_MOVZX;
  10998. { See if there are other optimisations possible }
  10999. Continue;
  11000. end;
  11001. end;
  11002. else
  11003. ;
  11004. end;
  11005. end
  11006. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11007. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11008. begin
  11009. {$ifdef x86_64}
  11010. if (taicpu(p).opsize = S_Q) then
  11011. begin
  11012. { Never necessary }
  11013. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11014. RemoveCurrentP(p, hp1);
  11015. Result := True;
  11016. Exit;
  11017. end;
  11018. {$endif x86_64}
  11019. { Forward check to determine necessity of and %reg,%reg }
  11020. TransferUsedRegs(TmpUsedRegs);
  11021. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11022. { Saves on a bunch of dereferences }
  11023. ActiveReg := taicpu(p).oper[1]^.reg;
  11024. case taicpu(hp1).opcode of
  11025. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11026. if (
  11027. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11028. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11029. ) and
  11030. (
  11031. (taicpu(hp1).opcode <> A_MOV) or
  11032. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11033. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11034. ) and
  11035. not (
  11036. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11037. (taicpu(hp1).opcode = A_MOV) and
  11038. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11039. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11040. ) and
  11041. (
  11042. (
  11043. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11044. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11045. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11046. ) or
  11047. (
  11048. {$ifdef x86_64}
  11049. (
  11050. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11051. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11052. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11053. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11054. ) and
  11055. {$endif x86_64}
  11056. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11057. )
  11058. ) then
  11059. begin
  11060. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11061. RemoveCurrentP(p, hp1);
  11062. Result := True;
  11063. Exit;
  11064. end;
  11065. A_ADD,
  11066. A_AND,
  11067. A_BSF,
  11068. A_BSR,
  11069. A_BTC,
  11070. A_BTR,
  11071. A_BTS,
  11072. A_OR,
  11073. A_SUB,
  11074. A_XOR:
  11075. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11076. if (
  11077. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11078. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11079. ) and
  11080. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11081. begin
  11082. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11083. RemoveCurrentP(p, hp1);
  11084. Result := True;
  11085. Exit;
  11086. end;
  11087. A_CMP,
  11088. A_TEST:
  11089. if (
  11090. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11091. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11092. ) and
  11093. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11094. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11095. begin
  11096. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11097. RemoveCurrentP(p, hp1);
  11098. Result := True;
  11099. Exit;
  11100. end;
  11101. A_BSWAP,
  11102. A_NEG,
  11103. A_NOT:
  11104. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11105. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11106. begin
  11107. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11108. RemoveCurrentP(p, hp1);
  11109. Result := True;
  11110. Exit;
  11111. end;
  11112. else
  11113. ;
  11114. end;
  11115. end;
  11116. if (taicpu(hp1).is_jmp) and
  11117. (taicpu(hp1).opcode<>A_JMP) and
  11118. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11119. begin
  11120. { change
  11121. and x, reg
  11122. jxx
  11123. to
  11124. test x, reg
  11125. jxx
  11126. if reg is deallocated before the
  11127. jump, but only if it's a conditional jump (PFV)
  11128. }
  11129. taicpu(p).opcode := A_TEST;
  11130. Exit;
  11131. end;
  11132. Break;
  11133. end;
  11134. { Lone AND tests }
  11135. if (taicpu(p).oper[0]^.typ = top_const) then
  11136. begin
  11137. {
  11138. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11139. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11140. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11141. }
  11142. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11143. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11144. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11145. begin
  11146. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11147. if taicpu(p).opsize = S_L then
  11148. begin
  11149. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11150. Result := True;
  11151. end;
  11152. end;
  11153. end;
  11154. { Backward check to determine necessity of and %reg,%reg }
  11155. if (taicpu(p).oper[0]^.typ = top_reg) and
  11156. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11157. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11158. GetLastInstruction(p, hp2) and
  11159. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11160. { Check size of adjacent instruction to determine if the AND is
  11161. effectively a null operation }
  11162. (
  11163. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11164. { Note: Don't include S_Q }
  11165. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11166. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11167. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11168. ) then
  11169. begin
  11170. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11171. { If GetNextInstruction returned False, hp1 will be nil }
  11172. RemoveCurrentP(p, hp1);
  11173. Result := True;
  11174. Exit;
  11175. end;
  11176. end;
  11177. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11178. var
  11179. hp1: tai; NewRef: TReference;
  11180. { This entire nested function is used in an if-statement below, but we
  11181. want to avoid all the used reg transfers and GetNextInstruction calls
  11182. until we really have to check }
  11183. function MemRegisterNotUsedLater: Boolean; inline;
  11184. var
  11185. hp2: tai;
  11186. begin
  11187. TransferUsedRegs(TmpUsedRegs);
  11188. hp2 := p;
  11189. repeat
  11190. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11191. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11192. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11193. end;
  11194. begin
  11195. Result := False;
  11196. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  11197. Exit;
  11198. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  11199. begin
  11200. { Change:
  11201. add %reg2,%reg1
  11202. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11203. To:
  11204. mov/s/z #(%reg1,%reg2),%reg1
  11205. }
  11206. if MatchOpType(taicpu(p), top_reg, top_reg) and
  11207. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11208. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11209. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11210. (
  11211. (
  11212. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11213. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11214. { r/esp cannot be an index }
  11215. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11216. ) or (
  11217. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11218. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11219. )
  11220. ) and (
  11221. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11222. (
  11223. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11224. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11225. MemRegisterNotUsedLater
  11226. )
  11227. ) then
  11228. begin
  11229. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11230. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11231. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11232. RemoveCurrentp(p, hp1);
  11233. Result := True;
  11234. Exit;
  11235. end;
  11236. { Change:
  11237. addl/q $x,%reg1
  11238. movl/q %reg1,%reg2
  11239. To:
  11240. leal/q $x(%reg1),%reg2
  11241. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11242. Breaks the dependency chain.
  11243. }
  11244. if MatchOpType(taicpu(p),top_const,top_reg) and
  11245. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11246. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11247. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11248. (
  11249. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11250. not (cs_opt_size in current_settings.optimizerswitches) or
  11251. (
  11252. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11253. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11254. )
  11255. ) then
  11256. begin
  11257. { Change the MOV instruction to a LEA instruction, and update the
  11258. first operand }
  11259. reference_reset(NewRef, 1, []);
  11260. NewRef.base := taicpu(p).oper[1]^.reg;
  11261. NewRef.scalefactor := 1;
  11262. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11263. taicpu(hp1).opcode := A_LEA;
  11264. taicpu(hp1).loadref(0, NewRef);
  11265. TransferUsedRegs(TmpUsedRegs);
  11266. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11267. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11268. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11269. begin
  11270. { Move what is now the LEA instruction to before the SUB instruction }
  11271. Asml.Remove(hp1);
  11272. Asml.InsertBefore(hp1, p);
  11273. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11274. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11275. p := hp1;
  11276. end
  11277. else
  11278. begin
  11279. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11280. RemoveCurrentP(p, hp1);
  11281. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  11282. end;
  11283. Result := True;
  11284. end;
  11285. end;
  11286. end;
  11287. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11288. var
  11289. SubReg: TSubRegister;
  11290. begin
  11291. Result:=false;
  11292. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11293. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11294. with taicpu(p).oper[0]^.ref^ do
  11295. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11296. begin
  11297. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11298. begin
  11299. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11300. taicpu(p).opcode := A_ADD;
  11301. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11302. Result := True;
  11303. end
  11304. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11305. begin
  11306. if (base <> NR_NO) then
  11307. begin
  11308. if (scalefactor <= 1) then
  11309. begin
  11310. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11311. taicpu(p).opcode := A_ADD;
  11312. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11313. Result := True;
  11314. end;
  11315. end
  11316. else
  11317. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11318. if (scalefactor in [2, 4, 8]) then
  11319. begin
  11320. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11321. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11322. taicpu(p).opcode := A_SHL;
  11323. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11324. Result := True;
  11325. end;
  11326. end;
  11327. end;
  11328. end;
  11329. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11330. var
  11331. hp1: tai; NewRef: TReference;
  11332. begin
  11333. { Change:
  11334. subl/q $x,%reg1
  11335. movl/q %reg1,%reg2
  11336. To:
  11337. leal/q $-x(%reg1),%reg2
  11338. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11339. Breaks the dependency chain and potentially permits the removal of
  11340. a CMP instruction if one follows.
  11341. }
  11342. Result := False;
  11343. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11344. MatchOpType(taicpu(p),top_const,top_reg) and
  11345. GetNextInstruction(p, hp1) and
  11346. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11347. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11348. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11349. (
  11350. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11351. not (cs_opt_size in current_settings.optimizerswitches) or
  11352. (
  11353. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11354. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11355. )
  11356. ) then
  11357. begin
  11358. { Change the MOV instruction to a LEA instruction, and update the
  11359. first operand }
  11360. reference_reset(NewRef, 1, []);
  11361. NewRef.base := taicpu(p).oper[1]^.reg;
  11362. NewRef.scalefactor := 1;
  11363. NewRef.offset := -taicpu(p).oper[0]^.val;
  11364. taicpu(hp1).opcode := A_LEA;
  11365. taicpu(hp1).loadref(0, NewRef);
  11366. TransferUsedRegs(TmpUsedRegs);
  11367. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11368. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11369. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11370. begin
  11371. { Move what is now the LEA instruction to before the SUB instruction }
  11372. Asml.Remove(hp1);
  11373. Asml.InsertBefore(hp1, p);
  11374. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11375. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11376. p := hp1;
  11377. end
  11378. else
  11379. begin
  11380. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11381. RemoveCurrentP(p, hp1);
  11382. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11383. end;
  11384. Result := True;
  11385. end;
  11386. end;
  11387. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11388. begin
  11389. { we can skip all instructions not messing with the stack pointer }
  11390. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11391. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11392. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11393. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11394. ({(taicpu(hp1).ops=0) or }
  11395. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11396. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11397. ) and }
  11398. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11399. )
  11400. ) do
  11401. GetNextInstruction(hp1,hp1);
  11402. Result:=assigned(hp1);
  11403. end;
  11404. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11405. var
  11406. hp1, hp2, hp3, hp4, hp5: tai;
  11407. begin
  11408. Result:=false;
  11409. hp5:=nil;
  11410. { replace
  11411. leal(q) x(<stackpointer>),<stackpointer>
  11412. call procname
  11413. leal(q) -x(<stackpointer>),<stackpointer>
  11414. ret
  11415. by
  11416. jmp procname
  11417. but do it only on level 4 because it destroys stack back traces
  11418. }
  11419. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11420. MatchOpType(taicpu(p),top_ref,top_reg) and
  11421. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11422. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11423. { the -8 or -24 are not required, but bail out early if possible,
  11424. higher values are unlikely }
  11425. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11426. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11427. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11428. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11429. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11430. GetNextInstruction(p, hp1) and
  11431. { Take a copy of hp1 }
  11432. SetAndTest(hp1, hp4) and
  11433. { trick to skip label }
  11434. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11435. SkipSimpleInstructions(hp1) and
  11436. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11437. GetNextInstruction(hp1, hp2) and
  11438. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11439. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11440. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11441. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11442. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11443. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11444. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11445. { Segment register will be NR_NO }
  11446. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11447. GetNextInstruction(hp2, hp3) and
  11448. { trick to skip label }
  11449. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11450. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11451. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11452. SetAndTest(hp3,hp5) and
  11453. GetNextInstruction(hp3,hp3) and
  11454. MatchInstruction(hp3,A_RET,[S_NO])
  11455. )
  11456. ) and
  11457. (taicpu(hp3).ops=0) then
  11458. begin
  11459. taicpu(hp1).opcode := A_JMP;
  11460. taicpu(hp1).is_jmp := true;
  11461. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11462. RemoveCurrentP(p, hp4);
  11463. RemoveInstruction(hp2);
  11464. RemoveInstruction(hp3);
  11465. if Assigned(hp5) then
  11466. begin
  11467. AsmL.Remove(hp5);
  11468. ASmL.InsertBefore(hp5,hp1)
  11469. end;
  11470. Result:=true;
  11471. end;
  11472. end;
  11473. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11474. {$ifdef x86_64}
  11475. var
  11476. hp1, hp2, hp3, hp4, hp5: tai;
  11477. {$endif x86_64}
  11478. begin
  11479. Result:=false;
  11480. {$ifdef x86_64}
  11481. hp5:=nil;
  11482. { replace
  11483. push %rax
  11484. call procname
  11485. pop %rcx
  11486. ret
  11487. by
  11488. jmp procname
  11489. but do it only on level 4 because it destroys stack back traces
  11490. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11491. for all supported calling conventions
  11492. }
  11493. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11494. MatchOpType(taicpu(p),top_reg) and
  11495. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11496. GetNextInstruction(p, hp1) and
  11497. { Take a copy of hp1 }
  11498. SetAndTest(hp1, hp4) and
  11499. { trick to skip label }
  11500. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11501. SkipSimpleInstructions(hp1) and
  11502. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11503. GetNextInstruction(hp1, hp2) and
  11504. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11505. MatchOpType(taicpu(hp2),top_reg) and
  11506. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11507. GetNextInstruction(hp2, hp3) and
  11508. { trick to skip label }
  11509. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11510. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11511. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11512. SetAndTest(hp3,hp5) and
  11513. GetNextInstruction(hp3,hp3) and
  11514. MatchInstruction(hp3,A_RET,[S_NO])
  11515. )
  11516. ) and
  11517. (taicpu(hp3).ops=0) then
  11518. begin
  11519. taicpu(hp1).opcode := A_JMP;
  11520. taicpu(hp1).is_jmp := true;
  11521. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11522. RemoveCurrentP(p, hp4);
  11523. RemoveInstruction(hp2);
  11524. RemoveInstruction(hp3);
  11525. if Assigned(hp5) then
  11526. begin
  11527. AsmL.Remove(hp5);
  11528. ASmL.InsertBefore(hp5,hp1)
  11529. end;
  11530. Result:=true;
  11531. end;
  11532. {$endif x86_64}
  11533. end;
  11534. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11535. var
  11536. Value, RegName: string;
  11537. begin
  11538. Result:=false;
  11539. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11540. begin
  11541. case taicpu(p).oper[0]^.val of
  11542. 0:
  11543. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11544. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11545. begin
  11546. { change "mov $0,%reg" into "xor %reg,%reg" }
  11547. taicpu(p).opcode := A_XOR;
  11548. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11549. Result := True;
  11550. {$ifdef x86_64}
  11551. end
  11552. else if (taicpu(p).opsize = S_Q) then
  11553. begin
  11554. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11555. { The actual optimization }
  11556. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11557. taicpu(p).changeopsize(S_L);
  11558. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11559. Result := True;
  11560. end;
  11561. $1..$FFFFFFFF:
  11562. begin
  11563. { Code size reduction by J. Gareth "Kit" Moreton }
  11564. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11565. case taicpu(p).opsize of
  11566. S_Q:
  11567. begin
  11568. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11569. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11570. { The actual optimization }
  11571. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11572. taicpu(p).changeopsize(S_L);
  11573. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11574. Result := True;
  11575. end;
  11576. else
  11577. { Do nothing };
  11578. end;
  11579. {$endif x86_64}
  11580. end;
  11581. -1:
  11582. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11583. if (cs_opt_size in current_settings.optimizerswitches) and
  11584. (taicpu(p).opsize <> S_B) and
  11585. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11586. begin
  11587. { change "mov $-1,%reg" into "or $-1,%reg" }
  11588. { NOTES:
  11589. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11590. - This operation creates a false dependency on the register, so only do it when optimising for size
  11591. - 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
  11592. }
  11593. taicpu(p).opcode := A_OR;
  11594. Result := True;
  11595. end;
  11596. else
  11597. { Do nothing };
  11598. end;
  11599. end;
  11600. end;
  11601. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11602. var
  11603. hp1: tai;
  11604. begin
  11605. { Detect:
  11606. andw x, %ax (0 <= x < $8000)
  11607. ...
  11608. movzwl %ax,%eax
  11609. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11610. }
  11611. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11612. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11613. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11614. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11615. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11616. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11617. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11618. begin
  11619. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11620. taicpu(hp1).opcode := A_CWDE;
  11621. taicpu(hp1).clearop(0);
  11622. taicpu(hp1).clearop(1);
  11623. taicpu(hp1).ops := 0;
  11624. { A change was made, but not with p, so move forward 1 }
  11625. p := tai(p.Next);
  11626. Result := True;
  11627. end;
  11628. end;
  11629. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11630. begin
  11631. Result := False;
  11632. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11633. Exit;
  11634. { Convert:
  11635. movswl %ax,%eax -> cwtl
  11636. movslq %eax,%rax -> cdqe
  11637. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11638. refer to the same opcode and depends only on the assembler's
  11639. current operand-size attribute. [Kit]
  11640. }
  11641. with taicpu(p) do
  11642. case opsize of
  11643. S_WL:
  11644. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11645. begin
  11646. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11647. opcode := A_CWDE;
  11648. clearop(0);
  11649. clearop(1);
  11650. ops := 0;
  11651. Result := True;
  11652. end;
  11653. {$ifdef x86_64}
  11654. S_LQ:
  11655. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11656. begin
  11657. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11658. opcode := A_CDQE;
  11659. clearop(0);
  11660. clearop(1);
  11661. ops := 0;
  11662. Result := True;
  11663. end;
  11664. {$endif x86_64}
  11665. else
  11666. ;
  11667. end;
  11668. end;
  11669. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11670. var
  11671. hp1: tai;
  11672. begin
  11673. { Detect:
  11674. shr x, %ax (x > 0)
  11675. ...
  11676. movzwl %ax,%eax
  11677. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11678. }
  11679. Result := False;
  11680. if MatchOpType(taicpu(p), top_const, top_reg) and
  11681. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11682. (taicpu(p).oper[0]^.val > 0) and
  11683. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11684. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11685. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11686. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11687. begin
  11688. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11689. taicpu(hp1).opcode := A_CWDE;
  11690. taicpu(hp1).clearop(0);
  11691. taicpu(hp1).clearop(1);
  11692. taicpu(hp1).ops := 0;
  11693. { A change was made, but not with p, so move forward 1 }
  11694. p := tai(p.Next);
  11695. Result := True;
  11696. end;
  11697. end;
  11698. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11699. var
  11700. hp1, hp2: tai;
  11701. Opposite, SecondOpposite: TAsmOp;
  11702. NewCond: TAsmCond;
  11703. begin
  11704. Result := False;
  11705. { Change:
  11706. add/sub 128,(dest)
  11707. To:
  11708. sub/add -128,(dest)
  11709. This generaally takes fewer bytes to encode because -128 can be stored
  11710. in a signed byte, whereas +128 cannot.
  11711. }
  11712. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11713. begin
  11714. if taicpu(p).opcode = A_ADD then
  11715. Opposite := A_SUB
  11716. else
  11717. Opposite := A_ADD;
  11718. { Be careful if the flags are in use, because the CF flag inverts
  11719. when changing from ADD to SUB and vice versa }
  11720. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11721. GetNextInstruction(p, hp1) then
  11722. begin
  11723. TransferUsedRegs(TmpUsedRegs);
  11724. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11725. hp2 := hp1;
  11726. { Scan ahead to check if everything's safe }
  11727. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11728. begin
  11729. if (hp1.typ <> ait_instruction) then
  11730. { Probably unsafe since the flags are still in use }
  11731. Exit;
  11732. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11733. { Stop searching at an unconditional jump }
  11734. Break;
  11735. if not
  11736. (
  11737. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11738. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11739. ) and
  11740. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11741. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11742. Exit;
  11743. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11744. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11745. { Move to the next instruction }
  11746. GetNextInstruction(hp1, hp1);
  11747. end;
  11748. while Assigned(hp2) and (hp2 <> hp1) do
  11749. begin
  11750. NewCond := C_None;
  11751. case taicpu(hp2).condition of
  11752. C_A, C_NBE:
  11753. NewCond := C_BE;
  11754. C_B, C_C, C_NAE:
  11755. NewCond := C_AE;
  11756. C_AE, C_NB, C_NC:
  11757. NewCond := C_B;
  11758. C_BE, C_NA:
  11759. NewCond := C_A;
  11760. else
  11761. { No change needed };
  11762. end;
  11763. if NewCond <> C_None then
  11764. begin
  11765. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11766. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11767. taicpu(hp2).condition := NewCond;
  11768. end
  11769. else
  11770. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11771. begin
  11772. { Because of the flipping of the carry bit, to ensure
  11773. the operation remains equivalent, ADC becomes SBB
  11774. and vice versa, and the constant is not-inverted.
  11775. If multiple ADCs or SBBs appear in a row, each one
  11776. changed causes the carry bit to invert, so they all
  11777. need to be flipped }
  11778. if taicpu(hp2).opcode = A_ADC then
  11779. SecondOpposite := A_SBB
  11780. else
  11781. SecondOpposite := A_ADC;
  11782. if taicpu(hp2).oper[0]^.typ <> top_const then
  11783. { Should have broken out of this optimisation already }
  11784. InternalError(2021112901);
  11785. 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]^) + ' -> ' +
  11786. 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);
  11787. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11788. taicpu(hp2).opcode := SecondOpposite;
  11789. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11790. end;
  11791. { Move to the next instruction }
  11792. GetNextInstruction(hp2, hp2);
  11793. end;
  11794. if (hp2 <> hp1) then
  11795. InternalError(2021111501);
  11796. end;
  11797. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11798. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11799. taicpu(p).opcode := Opposite;
  11800. taicpu(p).oper[0]^.val := -128;
  11801. { No further optimisations can be made on this instruction, so move
  11802. onto the next one to save time }
  11803. p := tai(p.Next);
  11804. UpdateUsedRegs(p);
  11805. Result := True;
  11806. Exit;
  11807. end;
  11808. { Detect:
  11809. add/sub %reg2,(dest)
  11810. add/sub x, (dest)
  11811. (dest can be a register or a reference)
  11812. Swap the instructions to minimise a pipeline stall. This reverses the
  11813. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11814. optimisations could be made.
  11815. }
  11816. if (taicpu(p).oper[0]^.typ = top_reg) and
  11817. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11818. (
  11819. (
  11820. (taicpu(p).oper[1]^.typ = top_reg) and
  11821. { We can try searching further ahead if we're writing to a register }
  11822. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11823. ) or
  11824. (
  11825. (taicpu(p).oper[1]^.typ = top_ref) and
  11826. GetNextInstruction(p, hp1)
  11827. )
  11828. ) and
  11829. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11830. (taicpu(hp1).oper[0]^.typ = top_const) and
  11831. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11832. begin
  11833. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11834. TransferUsedRegs(TmpUsedRegs);
  11835. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11836. hp2 := p;
  11837. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11838. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11839. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11840. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11841. begin
  11842. asml.remove(hp1);
  11843. asml.InsertBefore(hp1, p);
  11844. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11845. Result := True;
  11846. end;
  11847. end;
  11848. end;
  11849. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11850. begin
  11851. Result:=false;
  11852. { change "cmp $0, %reg" to "test %reg, %reg" }
  11853. if MatchOpType(taicpu(p),top_const,top_reg) and
  11854. (taicpu(p).oper[0]^.val = 0) then
  11855. begin
  11856. taicpu(p).opcode := A_TEST;
  11857. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11858. Result:=true;
  11859. end;
  11860. end;
  11861. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11862. var
  11863. IsTestConstX : Boolean;
  11864. hp1,hp2 : tai;
  11865. begin
  11866. Result:=false;
  11867. { removes the line marked with (x) from the sequence
  11868. and/or/xor/add/sub/... $x, %y
  11869. test/or %y, %y | test $-1, %y (x)
  11870. j(n)z _Label
  11871. as the first instruction already adjusts the ZF
  11872. %y operand may also be a reference }
  11873. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11874. MatchOperand(taicpu(p).oper[0]^,-1);
  11875. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11876. GetLastInstruction(p, hp1) and
  11877. (tai(hp1).typ = ait_instruction) and
  11878. GetNextInstruction(p,hp2) and
  11879. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11880. case taicpu(hp1).opcode Of
  11881. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11882. { These two instructions set the zero flag if the result is zero }
  11883. A_POPCNT, A_LZCNT:
  11884. begin
  11885. if (
  11886. { With POPCNT, an input of zero will set the zero flag
  11887. because the population count of zero is zero }
  11888. (taicpu(hp1).opcode = A_POPCNT) and
  11889. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11890. (
  11891. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11892. { Faster than going through the second half of the 'or'
  11893. condition below }
  11894. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11895. )
  11896. ) or (
  11897. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11898. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11899. { and in case of carry for A(E)/B(E)/C/NC }
  11900. (
  11901. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11902. (
  11903. (taicpu(hp1).opcode <> A_ADD) and
  11904. (taicpu(hp1).opcode <> A_SUB) and
  11905. (taicpu(hp1).opcode <> A_LZCNT)
  11906. )
  11907. )
  11908. ) then
  11909. begin
  11910. RemoveCurrentP(p, hp2);
  11911. Result:=true;
  11912. Exit;
  11913. end;
  11914. end;
  11915. A_SHL, A_SAL, A_SHR, A_SAR:
  11916. begin
  11917. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11918. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11919. { therefore, it's only safe to do this optimization for }
  11920. { shifts by a (nonzero) constant }
  11921. (taicpu(hp1).oper[0]^.typ = top_const) and
  11922. (taicpu(hp1).oper[0]^.val <> 0) and
  11923. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11924. { and in case of carry for A(E)/B(E)/C/NC }
  11925. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11926. begin
  11927. RemoveCurrentP(p, hp2);
  11928. Result:=true;
  11929. Exit;
  11930. end;
  11931. end;
  11932. A_DEC, A_INC, A_NEG:
  11933. begin
  11934. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11935. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11936. { and in case of carry for A(E)/B(E)/C/NC }
  11937. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11938. begin
  11939. RemoveCurrentP(p, hp2);
  11940. Result:=true;
  11941. Exit;
  11942. end;
  11943. end
  11944. else
  11945. ;
  11946. end; { case }
  11947. { change "test $-1,%reg" into "test %reg,%reg" }
  11948. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11949. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11950. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11951. if MatchInstruction(p, A_OR, []) and
  11952. { Can only match if they're both registers }
  11953. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11954. begin
  11955. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11956. taicpu(p).opcode := A_TEST;
  11957. { No need to set Result to True, as we've done all the optimisations we can }
  11958. end;
  11959. end;
  11960. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11961. var
  11962. hp1,hp3 : tai;
  11963. {$ifndef x86_64}
  11964. hp2 : taicpu;
  11965. {$endif x86_64}
  11966. begin
  11967. Result:=false;
  11968. hp3:=nil;
  11969. {$ifndef x86_64}
  11970. { don't do this on modern CPUs, this really hurts them due to
  11971. broken call/ret pairing }
  11972. if (current_settings.optimizecputype < cpu_Pentium2) and
  11973. not(cs_create_pic in current_settings.moduleswitches) and
  11974. GetNextInstruction(p, hp1) and
  11975. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11976. MatchOpType(taicpu(hp1),top_ref) and
  11977. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11978. begin
  11979. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11980. InsertLLItem(p.previous, p, hp2);
  11981. taicpu(p).opcode := A_JMP;
  11982. taicpu(p).is_jmp := true;
  11983. RemoveInstruction(hp1);
  11984. Result:=true;
  11985. end
  11986. else
  11987. {$endif x86_64}
  11988. { replace
  11989. call procname
  11990. ret
  11991. by
  11992. jmp procname
  11993. but do it only on level 4 because it destroys stack back traces
  11994. else if the subroutine is marked as no return, remove the ret
  11995. }
  11996. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11997. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11998. GetNextInstruction(p, hp1) and
  11999. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12000. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12001. SetAndTest(hp1,hp3) and
  12002. GetNextInstruction(hp1,hp1) and
  12003. MatchInstruction(hp1,A_RET,[S_NO])
  12004. )
  12005. ) and
  12006. (taicpu(hp1).ops=0) then
  12007. begin
  12008. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12009. { we might destroy stack alignment here if we do not do a call }
  12010. (target_info.stackalign<=sizeof(SizeUInt)) then
  12011. begin
  12012. taicpu(p).opcode := A_JMP;
  12013. taicpu(p).is_jmp := true;
  12014. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12015. end
  12016. else
  12017. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12018. RemoveInstruction(hp1);
  12019. if Assigned(hp3) then
  12020. begin
  12021. AsmL.Remove(hp3);
  12022. AsmL.InsertBefore(hp3,p)
  12023. end;
  12024. Result:=true;
  12025. end;
  12026. end;
  12027. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12028. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12029. begin
  12030. case OpSize of
  12031. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12032. Result := (Val <= $FF) and (Val >= -128);
  12033. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12034. Result := (Val <= $FFFF) and (Val >= -32768);
  12035. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12036. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12037. else
  12038. Result := True;
  12039. end;
  12040. end;
  12041. var
  12042. hp1, hp2 : tai;
  12043. SizeChange: Boolean;
  12044. PreMessage: string;
  12045. begin
  12046. Result := False;
  12047. if (taicpu(p).oper[0]^.typ = top_reg) and
  12048. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12049. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12050. begin
  12051. { Change (using movzbl %al,%eax as an example):
  12052. movzbl %al, %eax movzbl %al, %eax
  12053. cmpl x, %eax testl %eax,%eax
  12054. To:
  12055. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12056. movzbl %al, %eax movzbl %al, %eax
  12057. Smaller instruction and minimises pipeline stall as the CPU
  12058. doesn't have to wait for the register to get zero-extended. [Kit]
  12059. Also allow if the smaller of the two registers is being checked,
  12060. as this still removes the false dependency.
  12061. }
  12062. if
  12063. (
  12064. (
  12065. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12066. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12067. ) or (
  12068. { If MatchOperand returns True, they must both be registers }
  12069. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12070. )
  12071. ) and
  12072. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12073. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12074. begin
  12075. 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);
  12076. asml.Remove(hp1);
  12077. asml.InsertBefore(hp1, p);
  12078. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12079. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12080. begin
  12081. taicpu(hp1).opcode := A_TEST;
  12082. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12083. end;
  12084. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12085. case taicpu(p).opsize of
  12086. S_BW, S_BL:
  12087. begin
  12088. SizeChange := taicpu(hp1).opsize <> S_B;
  12089. taicpu(hp1).changeopsize(S_B);
  12090. end;
  12091. S_WL:
  12092. begin
  12093. SizeChange := taicpu(hp1).opsize <> S_W;
  12094. taicpu(hp1).changeopsize(S_W);
  12095. end
  12096. else
  12097. InternalError(2020112701);
  12098. end;
  12099. UpdateUsedRegs(tai(p.Next));
  12100. { Check if the register is used aferwards - if not, we can
  12101. remove the movzx instruction completely }
  12102. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12103. begin
  12104. { Hp1 is a better position than p for debugging purposes }
  12105. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  12106. RemoveCurrentp(p, hp1);
  12107. Result := True;
  12108. end;
  12109. if SizeChange then
  12110. DebugMsg(SPeepholeOptimization + PreMessage +
  12111. 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)
  12112. else
  12113. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  12114. Exit;
  12115. end;
  12116. { Change (using movzwl %ax,%eax as an example):
  12117. movzwl %ax, %eax
  12118. movb %al, (dest) (Register is smaller than read register in movz)
  12119. To:
  12120. movb %al, (dest) (Move one back to avoid a false dependency)
  12121. movzwl %ax, %eax
  12122. }
  12123. if (taicpu(hp1).opcode = A_MOV) and
  12124. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12125. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  12126. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  12127. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  12128. begin
  12129. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  12130. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  12131. asml.Remove(hp1);
  12132. asml.InsertBefore(hp1, p);
  12133. if taicpu(hp1).oper[1]^.typ = top_reg then
  12134. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12135. { Check if the register is used aferwards - if not, we can
  12136. remove the movzx instruction completely }
  12137. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  12138. begin
  12139. { Hp1 is a better position than p for debugging purposes }
  12140. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  12141. RemoveCurrentp(p, hp1);
  12142. Result := True;
  12143. end;
  12144. Exit;
  12145. end;
  12146. end;
  12147. end;
  12148. {$ifdef x86_64}
  12149. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  12150. var
  12151. PreMessage, RegName: string;
  12152. begin
  12153. { Code size reduction by J. Gareth "Kit" Moreton }
  12154. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  12155. as this removes the REX prefix }
  12156. Result := False;
  12157. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  12158. Exit;
  12159. if taicpu(p).oper[0]^.typ <> top_reg then
  12160. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  12161. InternalError(2018011500);
  12162. case taicpu(p).opsize of
  12163. S_Q:
  12164. begin
  12165. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  12166. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  12167. { The actual optimization }
  12168. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12169. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12170. taicpu(p).changeopsize(S_L);
  12171. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  12172. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  12173. end;
  12174. else
  12175. ;
  12176. end;
  12177. end;
  12178. {$endif}
  12179. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  12180. var
  12181. XReg: TRegister;
  12182. begin
  12183. Result := False;
  12184. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  12185. Smaller encoding and slightly faster on some platforms (also works for
  12186. ZMM-sized registers) }
  12187. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  12188. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  12189. begin
  12190. XReg := taicpu(p).oper[0]^.reg;
  12191. if (taicpu(p).oper[1]^.reg = XReg) then
  12192. begin
  12193. taicpu(p).changeopsize(S_XMM);
  12194. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  12195. if (cs_opt_size in current_settings.optimizerswitches) then
  12196. begin
  12197. { Change input registers to %xmm0 to reduce size. Note that
  12198. there's a risk of a false dependency doing this, so only
  12199. optimise for size here }
  12200. XReg := NR_XMM0;
  12201. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  12202. end
  12203. else
  12204. begin
  12205. setsubreg(XReg, R_SUBMMX);
  12206. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  12207. end;
  12208. taicpu(p).oper[0]^.reg := XReg;
  12209. taicpu(p).oper[1]^.reg := XReg;
  12210. Result := True;
  12211. end;
  12212. end;
  12213. end;
  12214. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  12215. var
  12216. OperIdx: Integer;
  12217. begin
  12218. for OperIdx := 0 to p.ops - 1 do
  12219. if p.oper[OperIdx]^.typ = top_ref then
  12220. optimize_ref(p.oper[OperIdx]^.ref^, False);
  12221. end;
  12222. end.